1313from basic_memory .mcp .server import mcp
1414from basic_memory .mcp .tools .search import search_notes
1515from basic_memory .mcp .tools .read_note import read_note
16- from basic_memory .schemas .search import SearchResponse
1716from basic_memory .config import ConfigManager
17+ from basic_memory .schemas .search import SearchResponse , SearchResult
1818
1919
20- def _format_search_results_for_chatgpt (results : SearchResponse ) -> List [Dict [str , Any ]]:
20+ def _format_search_results_for_chatgpt (
21+ results : SearchResponse | list [SearchResult ] | list [dict [str , Any ]] | dict [str , Any ],
22+ ) -> List [Dict [str , Any ]]:
2123 """Format search results according to ChatGPT's expected schema.
2224
2325 Returns a list of result objects with id, title, and url fields.
2426 """
27+ if isinstance (results , SearchResponse ):
28+ raw_results : list [SearchResult ] | list [dict [str , Any ]] = results .results
29+ elif isinstance (results , dict ):
30+ nested_results = results .get ("results" )
31+ raw_results = nested_results if isinstance (nested_results , list ) else []
32+ else :
33+ raw_results = results
34+
2535 formatted_results = []
2636
27- for result in results .results :
37+ for result in raw_results :
38+ if isinstance (result , SearchResult ):
39+ title = result .title
40+ permalink = result .permalink
41+ elif isinstance (result , dict ):
42+ title = result .get ("title" )
43+ permalink = result .get ("permalink" )
44+ else :
45+ raise TypeError (f"Unexpected result type: { type (result ).__name__ } " )
46+
2847 formatted_result = {
29- "id" : result . permalink or f"doc-{ len (formatted_results )} " ,
30- "title" : result . title if result . title and result . title .strip () else "Untitled" ,
31- "url" : result . permalink or "" ,
48+ "id" : permalink or f"doc-{ len (formatted_results )} " ,
49+ "title" : title if isinstance ( title , str ) and title .strip () else "Untitled" ,
50+ "url" : permalink or "" ,
3251 }
3352 formatted_results .append (formatted_result )
3453
@@ -102,6 +121,7 @@ async def search(
102121 page = 1 ,
103122 page_size = 10 , # Reasonable default for ChatGPT consumption
104123 search_type = "text" , # Default to full-text search
124+ output_format = "json" ,
105125 context = context ,
106126 )
107127
@@ -115,10 +135,11 @@ async def search(
115135 }
116136 else :
117137 # Format successful results for ChatGPT
118- formatted_results = _format_search_results_for_chatgpt (results )
138+ raw_results = results .get ("results" , []) if isinstance (results , dict ) else []
139+ formatted_results = _format_search_results_for_chatgpt (raw_results )
119140 search_results = {
120141 "results" : formatted_results ,
121- "total_count" : len (results . results ), # Use actual count from results
142+ "total_count" : len (raw_results ), # Use actual count from results
122143 "query" : query ,
123144 }
124145 logger .info (f"Search completed: { len (formatted_results )} results returned" )
0 commit comments