diff --git a/mcp_codebase.py b/mcp_codebase.py index ca7a7f8..56203e0 100644 --- a/mcp_codebase.py +++ b/mcp_codebase.py @@ -4996,10 +4996,11 @@ def _build_enhanced_result(chunk_text: str, meta: dict, score: float, graph: Opt def _get_result_graph_context(meta: dict, graph: Optional[LocalGraph] = None) -> dict: """Enhanced graph context that provides queryable node IDs and relationships.""" + context = {} # Initialize context at the start + if graph is None or graph.graph.number_of_nodes() == 0: - return {} + return context - _format_enhanced_results = {} file_path = meta.get('file', '') entity_name = meta.get('name', '') entity_type = meta.get('type', '') @@ -5084,7 +5085,7 @@ def _format_enhanced_results(results: List[Dict], query: str, result_type: str) ] for result in results: - # Extract all fields + # Extract all fields with safe defaults file_path = result.get('file', '') line_num = result.get('line', '') entity_type = result.get('type', 'code') @@ -5092,7 +5093,7 @@ def _format_enhanced_results(results: List[Dict], query: str, result_type: str) language = result.get('language', '') score = result.get('score', 0.0) content = result.get('content', '') - graph_context = result.get('graph_context', {}) + graph_context = result.get('graph_context', {}) # Safe default: empty dict # Build compact graph context string for queries graph_parts = [] @@ -5103,15 +5104,22 @@ def _format_enhanced_results(results: List[Dict], query: str, result_type: str) # Cross-file dependencies for import/call queries if graph_context.get('cross_file'): - graph_parts.append(f"xfile:{'|'.join(graph_context['cross_file'][:4])}") + # Ensure we're working with a list and take first 4 + cross_files = graph_context['cross_file'] + if isinstance(cross_files, list): + graph_parts.append(f"xfile:{'|'.join(cross_files[:4])}") # Reverse dependencies for "used by" queries if graph_context.get('used_by'): - graph_parts.append(f"used:{'|'.join(graph_context['used_by'][:3])}") + used_by = graph_context['used_by'] + if isinstance(used_by, list): + graph_parts.append(f"used:{'|'.join(used_by[:3])}") # Same-file relationships for file context queries if graph_context.get('same_file'): - graph_parts.append(f"same:{'|'.join(graph_context['same_file'][:5])}") + same_files = graph_context['same_file'] + if isinstance(same_files, list): + graph_parts.append(f"same:{'|'.join(same_files[:5])}") graph_str = ";".join(graph_parts)