codegraphcontext-rust 0.5.5__cp311-cp311-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codegraphcontext/__init__.py +2 -0
- codegraphcontext/__main__.py +5 -0
- codegraphcontext/_cgc_rust.cp311-win_amd64.pyd +0 -0
- codegraphcontext/cli/__init__.py +1 -0
- codegraphcontext/cli/cli_helpers.py +774 -0
- codegraphcontext/cli/config_manager.py +1051 -0
- codegraphcontext/cli/main.py +2386 -0
- codegraphcontext/cli/registry_commands.py +404 -0
- codegraphcontext/cli/setup_macos.py +93 -0
- codegraphcontext/cli/setup_wizard.py +991 -0
- codegraphcontext/cli/visualizer.py +50 -0
- codegraphcontext/core/__init__.py +165 -0
- codegraphcontext/core/bundle_registry.py +181 -0
- codegraphcontext/core/cgc_bundle.py +858 -0
- codegraphcontext/core/cgcignore.py +118 -0
- codegraphcontext/core/database.py +273 -0
- codegraphcontext/core/database_falkordb.py +480 -0
- codegraphcontext/core/database_falkordb_remote.py +199 -0
- codegraphcontext/core/database_kuzu.py +636 -0
- codegraphcontext/core/falkor_worker.py +132 -0
- codegraphcontext/core/jobs.py +132 -0
- codegraphcontext/core/watcher.py +260 -0
- codegraphcontext/prompts.py +125 -0
- codegraphcontext/server.py +471 -0
- codegraphcontext/tool_definitions.py +220 -0
- codegraphcontext/tools/__init__.py +0 -0
- codegraphcontext/tools/advanced_language_query_tool.py +103 -0
- codegraphcontext/tools/code_finder.py +1160 -0
- codegraphcontext/tools/graph_builder.py +337 -0
- codegraphcontext/tools/handlers/analysis_handlers.py +114 -0
- codegraphcontext/tools/handlers/indexing_handlers.py +116 -0
- codegraphcontext/tools/handlers/management_handlers.py +339 -0
- codegraphcontext/tools/handlers/query_handlers.py +83 -0
- codegraphcontext/tools/handlers/watcher_handlers.py +83 -0
- codegraphcontext/tools/indexing/__init__.py +1 -0
- codegraphcontext/tools/indexing/constants.py +25 -0
- codegraphcontext/tools/indexing/discovery.py +64 -0
- codegraphcontext/tools/indexing/engine.py +109 -0
- codegraphcontext/tools/indexing/persistence/__init__.py +3 -0
- codegraphcontext/tools/indexing/persistence/parquet_loader.py +643 -0
- codegraphcontext/tools/indexing/persistence/writer.py +1114 -0
- codegraphcontext/tools/indexing/pipeline.py +171 -0
- codegraphcontext/tools/indexing/pre_scan.py +105 -0
- codegraphcontext/tools/indexing/resolution/__init__.py +8 -0
- codegraphcontext/tools/indexing/resolution/calls.py +253 -0
- codegraphcontext/tools/indexing/resolution/inheritance.py +91 -0
- codegraphcontext/tools/indexing/sanitize.py +41 -0
- codegraphcontext/tools/indexing/schema.py +79 -0
- codegraphcontext/tools/indexing/schema_contract.py +44 -0
- codegraphcontext/tools/indexing/scip_pipeline.py +140 -0
- codegraphcontext/tools/languages/c.py +563 -0
- codegraphcontext/tools/languages/cpp.py +616 -0
- codegraphcontext/tools/languages/csharp.py +551 -0
- codegraphcontext/tools/languages/dart.py +378 -0
- codegraphcontext/tools/languages/elixir.py +460 -0
- codegraphcontext/tools/languages/go.py +499 -0
- codegraphcontext/tools/languages/haskell.py +426 -0
- codegraphcontext/tools/languages/java.py +500 -0
- codegraphcontext/tools/languages/javascript.py +589 -0
- codegraphcontext/tools/languages/kotlin.py +640 -0
- codegraphcontext/tools/languages/perl.py +260 -0
- codegraphcontext/tools/languages/php.py +519 -0
- codegraphcontext/tools/languages/python.py +576 -0
- codegraphcontext/tools/languages/ruby.py +537 -0
- codegraphcontext/tools/languages/rust.py +295 -0
- codegraphcontext/tools/languages/scala.py +519 -0
- codegraphcontext/tools/languages/swift.py +491 -0
- codegraphcontext/tools/languages/typescript.py +575 -0
- codegraphcontext/tools/languages/typescriptjsx.py +151 -0
- codegraphcontext/tools/package_resolver.py +472 -0
- codegraphcontext/tools/query_tool_languages/c_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/cpp_toolkit.py +87 -0
- codegraphcontext/tools/query_tool_languages/csharp_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/dart_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/go_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/haskell_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/java_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/javascript_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/perl_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/python_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/ruby_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/rust_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/scala_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/swift_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/typescript_toolkit.py +5 -0
- codegraphcontext/tools/scip_indexer.py +467 -0
- codegraphcontext/tools/scip_pb2.py +2455 -0
- codegraphcontext/tools/system.py +133 -0
- codegraphcontext/tools/tree_sitter_parser.py +103 -0
- codegraphcontext/utils/debug_log.py +90 -0
- codegraphcontext/utils/path_ignore.py +55 -0
- codegraphcontext/utils/repo_path.py +27 -0
- codegraphcontext/utils/tree_sitter_manager.py +285 -0
- codegraphcontext/utils/visualize_graph.py +0 -0
- codegraphcontext/viz/server.py +282 -0
- codegraphcontext_rust-0.5.5.dist-info/METADATA +537 -0
- codegraphcontext_rust-0.5.5.dist-info/RECORD +101 -0
- codegraphcontext_rust-0.5.5.dist-info/WHEEL +4 -0
- codegraphcontext_rust-0.5.5.dist-info/entry_points.txt +3 -0
- codegraphcontext_rust-0.5.5.dist-info/licenses/LICENSE +21 -0
- codegraphcontext_rust-0.5.5.dist-info/sboms/cgc-python.cyclonedx.json +2333 -0
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
# src/codegraphcontext/server.py
|
|
2
|
+
import urllib.parse
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import importlib
|
|
6
|
+
import stdlibs
|
|
7
|
+
import sys
|
|
8
|
+
import traceback
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from dataclasses import asdict
|
|
14
|
+
|
|
15
|
+
from typing import Any, Dict, Coroutine, Optional, List
|
|
16
|
+
|
|
17
|
+
from .prompts import LLM_SYSTEM_PROMPT
|
|
18
|
+
from .core import get_database_manager
|
|
19
|
+
from .core.jobs import JobManager, JobStatus
|
|
20
|
+
from .core.watcher import CodeWatcher
|
|
21
|
+
from .tools.graph_builder import GraphBuilder
|
|
22
|
+
from .tools.code_finder import CodeFinder
|
|
23
|
+
from .tools.package_resolver import get_local_package_path
|
|
24
|
+
from .utils.debug_log import debug_log, info_logger, error_logger, warning_logger, debug_logger
|
|
25
|
+
from .cli.config_manager import (
|
|
26
|
+
resolve_context,
|
|
27
|
+
discover_child_contexts,
|
|
28
|
+
save_workspace_mapping,
|
|
29
|
+
get_workspace_mapping,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
# Import Tool Definitions and Handlers
|
|
33
|
+
from .tool_definitions import TOOLS
|
|
34
|
+
from .tools.handlers import (
|
|
35
|
+
analysis_handlers,
|
|
36
|
+
indexing_handlers,
|
|
37
|
+
management_handlers,
|
|
38
|
+
query_handlers,
|
|
39
|
+
watcher_handlers
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
DEFAULT_EDIT_DISTANCE = 2
|
|
43
|
+
DEFAULT_FUZZY_SEARCH = False
|
|
44
|
+
|
|
45
|
+
WORKSPACE_PREFIX = "/workspace/"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _is_path_key(key: str) -> bool:
|
|
49
|
+
"""Check if a dict key represents a file path field.
|
|
50
|
+
|
|
51
|
+
Matches keys like 'path', 'clone_path', 'caller_file_path', and also
|
|
52
|
+
Cypher-aliased keys like 'f.path', 'n.caller_file_path'.
|
|
53
|
+
"""
|
|
54
|
+
# Strip Cypher alias prefix (e.g. "f.path" -> "path")
|
|
55
|
+
bare = key.rsplit(".", 1)[-1] if "." in key else key
|
|
56
|
+
return bare == "path" or bare.endswith("_path")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _strip_path_value(value):
|
|
60
|
+
"""Strip /workspace/ prefix from a single string value."""
|
|
61
|
+
if isinstance(value, str) and value.startswith(WORKSPACE_PREFIX):
|
|
62
|
+
return value[len(WORKSPACE_PREFIX):]
|
|
63
|
+
return value
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _strip_workspace_prefix(obj):
|
|
67
|
+
"""Recursively strip /workspace/ prefix from path values in results."""
|
|
68
|
+
if isinstance(obj, dict):
|
|
69
|
+
return {
|
|
70
|
+
k: _strip_path_value(v) if _is_path_key(k) else _strip_workspace_prefix(v)
|
|
71
|
+
for k, v in obj.items()
|
|
72
|
+
}
|
|
73
|
+
elif isinstance(obj, list):
|
|
74
|
+
return [_strip_workspace_prefix(item) for item in obj]
|
|
75
|
+
return obj
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class MCPServer:
|
|
80
|
+
"""
|
|
81
|
+
The main MCP Server class.
|
|
82
|
+
|
|
83
|
+
This class orchestrates all the major components of the application, including:
|
|
84
|
+
- Database connection management (`DatabaseManager` or `FalkorDBManager`)
|
|
85
|
+
- Background job tracking (`JobManager`)
|
|
86
|
+
- File system watching for live updates (`CodeWatcher`)
|
|
87
|
+
- Tool handlers for graph building, code searching, etc.
|
|
88
|
+
- The main JSON-RPC communication loop for interacting with an AI assistant.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
def __init__(self, loop=None, cwd: Path | None = None):
|
|
92
|
+
"""
|
|
93
|
+
Initializes the MCP server and its components.
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
loop: The asyncio event loop to use. If not provided, it gets the current
|
|
97
|
+
running loop or creates a new one.
|
|
98
|
+
cwd: Working directory used for context resolution. Defaults to Path.cwd().
|
|
99
|
+
"""
|
|
100
|
+
self.cwd = (cwd or Path.cwd()).resolve()
|
|
101
|
+
self.discovered_child_contexts: List[dict] = []
|
|
102
|
+
self._context_note_pending = False
|
|
103
|
+
|
|
104
|
+
try:
|
|
105
|
+
ctx = resolve_context(cwd=self.cwd)
|
|
106
|
+
self.resolved_context = ctx
|
|
107
|
+
|
|
108
|
+
if ctx.database:
|
|
109
|
+
os.environ['CGC_RUNTIME_DB_TYPE'] = ctx.database
|
|
110
|
+
|
|
111
|
+
self.db_manager = get_database_manager(db_path=ctx.db_path)
|
|
112
|
+
self.db_manager.get_driver()
|
|
113
|
+
|
|
114
|
+
if not ctx.is_local:
|
|
115
|
+
try:
|
|
116
|
+
children = discover_child_contexts(self.cwd, max_depth=1)
|
|
117
|
+
if children:
|
|
118
|
+
self.discovered_child_contexts = [asdict(c) for c in children]
|
|
119
|
+
self._context_note_pending = True
|
|
120
|
+
except Exception:
|
|
121
|
+
pass
|
|
122
|
+
except ValueError as e:
|
|
123
|
+
raise ValueError(f"Database configuration error: {e}")
|
|
124
|
+
|
|
125
|
+
# Initialize managers for jobs and file watching.
|
|
126
|
+
self.job_manager = JobManager()
|
|
127
|
+
|
|
128
|
+
# Get the current event loop to pass to thread-sensitive components like the graph builder.
|
|
129
|
+
if loop is None:
|
|
130
|
+
try:
|
|
131
|
+
loop = asyncio.get_running_loop()
|
|
132
|
+
except RuntimeError:
|
|
133
|
+
loop = asyncio.new_event_loop()
|
|
134
|
+
asyncio.set_event_loop(loop)
|
|
135
|
+
self.loop = loop
|
|
136
|
+
|
|
137
|
+
# Initialize all the tool handlers, passing them the necessary managers and the event loop.
|
|
138
|
+
self.graph_builder = GraphBuilder(self.db_manager, self.job_manager, loop)
|
|
139
|
+
self.code_finder = CodeFinder(self.db_manager)
|
|
140
|
+
self.code_watcher = CodeWatcher(self.graph_builder, self.job_manager)
|
|
141
|
+
|
|
142
|
+
# Define the tool manifest that will be exposed to the AI assistant.
|
|
143
|
+
self._init_tools()
|
|
144
|
+
|
|
145
|
+
def _init_tools(self):
|
|
146
|
+
"""
|
|
147
|
+
Defines the complete tool manifest for the LLM.
|
|
148
|
+
"""
|
|
149
|
+
self.tools = TOOLS
|
|
150
|
+
|
|
151
|
+
def _get_version(self) -> str:
|
|
152
|
+
try:
|
|
153
|
+
from importlib.metadata import version
|
|
154
|
+
return version("codegraphcontext")
|
|
155
|
+
except Exception:
|
|
156
|
+
return "0.0.0-dev"
|
|
157
|
+
|
|
158
|
+
def get_database_status(self) -> dict:
|
|
159
|
+
"""Returns the current connection status of the Neo4j database."""
|
|
160
|
+
return {"connected": self.db_manager.is_connected()}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
# --- Tool Wrappers ---
|
|
164
|
+
# These methods delegate to the functional handlers, injecting the necessary dependencies.
|
|
165
|
+
|
|
166
|
+
def execute_cypher_query_tool(self, **args) -> Dict[str, Any]:
|
|
167
|
+
return query_handlers.execute_cypher_query(self.db_manager, **args)
|
|
168
|
+
|
|
169
|
+
def visualize_graph_query_tool(self, **args) -> Dict[str, Any]:
|
|
170
|
+
return query_handlers.visualize_graph_query(self.db_manager, **args)
|
|
171
|
+
|
|
172
|
+
def find_dead_code_tool(self, **args) -> Dict[str, Any]:
|
|
173
|
+
return analysis_handlers.find_dead_code(self.code_finder, **args)
|
|
174
|
+
|
|
175
|
+
def calculate_cyclomatic_complexity_tool(self, **args) -> Dict[str, Any]:
|
|
176
|
+
return analysis_handlers.calculate_cyclomatic_complexity(self.code_finder, **args)
|
|
177
|
+
|
|
178
|
+
def find_most_complex_functions_tool(self, **args) -> Dict[str, Any]:
|
|
179
|
+
return analysis_handlers.find_most_complex_functions(self.code_finder, **args)
|
|
180
|
+
|
|
181
|
+
def analyze_code_relationships_tool(self, **args) -> Dict[str, Any]:
|
|
182
|
+
return analysis_handlers.analyze_code_relationships(self.code_finder, **args)
|
|
183
|
+
|
|
184
|
+
def find_code_tool(self, **args) -> Dict[str, Any]:
|
|
185
|
+
return analysis_handlers.find_code(self.code_finder, **args)
|
|
186
|
+
|
|
187
|
+
def list_indexed_repositories_tool(self, **args) -> Dict[str, Any]:
|
|
188
|
+
return management_handlers.list_indexed_repositories(self.code_finder, **args)
|
|
189
|
+
|
|
190
|
+
def delete_repository_tool(self, **args) -> Dict[str, Any]:
|
|
191
|
+
return management_handlers.delete_repository(self.graph_builder, **args)
|
|
192
|
+
|
|
193
|
+
def check_job_status_tool(self, **args) -> Dict[str, Any]:
|
|
194
|
+
return management_handlers.check_job_status(self.job_manager, **args)
|
|
195
|
+
|
|
196
|
+
def list_jobs_tool(self) -> Dict[str, Any]:
|
|
197
|
+
return management_handlers.list_jobs(self.job_manager)
|
|
198
|
+
|
|
199
|
+
def list_watched_paths_tool(self, **args) -> Dict[str, Any]:
|
|
200
|
+
return watcher_handlers.list_watched_paths(self.code_watcher, **args)
|
|
201
|
+
|
|
202
|
+
def unwatch_directory_tool(self, **args) -> Dict[str, Any]:
|
|
203
|
+
return watcher_handlers.unwatch_directory(self.code_watcher, **args)
|
|
204
|
+
|
|
205
|
+
def add_code_to_graph_tool(self, **args) -> Dict[str, Any]:
|
|
206
|
+
return indexing_handlers.add_code_to_graph(
|
|
207
|
+
self.graph_builder,
|
|
208
|
+
self.job_manager,
|
|
209
|
+
self.loop,
|
|
210
|
+
self.list_indexed_repositories_tool, # Pass the wrapper or bound method so it executes correctly
|
|
211
|
+
**args
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
def add_package_to_graph_tool(self, **args) -> Dict[str, Any]:
|
|
215
|
+
return indexing_handlers.add_package_to_graph(
|
|
216
|
+
self.graph_builder,
|
|
217
|
+
self.job_manager,
|
|
218
|
+
self.loop,
|
|
219
|
+
self.list_indexed_repositories_tool,
|
|
220
|
+
**args
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
def watch_directory_tool(self, **args) -> Dict[str, Any]:
|
|
224
|
+
# watch_directory needs to call metadata tools.
|
|
225
|
+
return watcher_handlers.watch_directory(
|
|
226
|
+
self.code_watcher,
|
|
227
|
+
self.list_indexed_repositories_tool,
|
|
228
|
+
self.add_code_to_graph_tool,
|
|
229
|
+
**args
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
def load_bundle_tool(self, **args) -> Dict[str, Any]:
|
|
233
|
+
return management_handlers.load_bundle(self.code_finder, **args)
|
|
234
|
+
|
|
235
|
+
def search_registry_bundles_tool(self, **args) -> Dict[str, Any]:
|
|
236
|
+
return management_handlers.search_registry_bundles(self.code_finder, **args)
|
|
237
|
+
|
|
238
|
+
def get_repository_stats_tool(self, **args) -> Dict[str, Any]:
|
|
239
|
+
return management_handlers.get_repository_stats(self.code_finder, **args)
|
|
240
|
+
|
|
241
|
+
def discover_codegraph_contexts_tool(self, **args) -> Dict[str, Any]:
|
|
242
|
+
scan_path = Path(args.get("path", str(self.cwd))).resolve()
|
|
243
|
+
max_depth = int(args.get("max_depth", 1))
|
|
244
|
+
try:
|
|
245
|
+
children = discover_child_contexts(scan_path, max_depth=max_depth)
|
|
246
|
+
if not children:
|
|
247
|
+
return {
|
|
248
|
+
"status": "no_contexts_found",
|
|
249
|
+
"message": f"No .codegraphcontext folders found under {scan_path} (depth={max_depth}).",
|
|
250
|
+
"contexts": [],
|
|
251
|
+
}
|
|
252
|
+
return {
|
|
253
|
+
"status": "ok",
|
|
254
|
+
"message": f"Found {len(children)} context(s) under {scan_path}.",
|
|
255
|
+
"contexts": [asdict(c) for c in children],
|
|
256
|
+
}
|
|
257
|
+
except Exception as e:
|
|
258
|
+
return {"error": f"Discovery failed: {e}"}
|
|
259
|
+
|
|
260
|
+
def switch_context_tool(self, **args) -> Dict[str, Any]:
|
|
261
|
+
raw_path = args.get("context_path", "")
|
|
262
|
+
should_save = args.get("save", True)
|
|
263
|
+
|
|
264
|
+
if not raw_path:
|
|
265
|
+
return {"error": "context_path is required."}
|
|
266
|
+
|
|
267
|
+
target = Path(raw_path).resolve()
|
|
268
|
+
# Accept either the repo dir or the .codegraphcontext dir directly
|
|
269
|
+
if target.name == ".codegraphcontext":
|
|
270
|
+
cgc_dir = target
|
|
271
|
+
else:
|
|
272
|
+
cgc_dir = target / ".codegraphcontext"
|
|
273
|
+
|
|
274
|
+
if not cgc_dir.exists() or not cgc_dir.is_dir():
|
|
275
|
+
return {"error": f"No .codegraphcontext directory found at {cgc_dir}."}
|
|
276
|
+
|
|
277
|
+
local_db = "falkordb"
|
|
278
|
+
local_yaml = cgc_dir / "config.yaml"
|
|
279
|
+
if local_yaml.exists():
|
|
280
|
+
try:
|
|
281
|
+
import yaml
|
|
282
|
+
with open(local_yaml) as f:
|
|
283
|
+
raw = yaml.safe_load(f) or {}
|
|
284
|
+
local_db = raw.get("database", "falkordb")
|
|
285
|
+
except Exception:
|
|
286
|
+
pass
|
|
287
|
+
|
|
288
|
+
new_db_path = str(cgc_dir / "db" / local_db)
|
|
289
|
+
|
|
290
|
+
try:
|
|
291
|
+
# Tear down old connection
|
|
292
|
+
try:
|
|
293
|
+
self.db_manager.close_driver()
|
|
294
|
+
except Exception:
|
|
295
|
+
pass
|
|
296
|
+
|
|
297
|
+
os.environ['CGC_RUNTIME_DB_TYPE'] = local_db
|
|
298
|
+
new_manager = get_database_manager(db_path=new_db_path)
|
|
299
|
+
new_manager.get_driver()
|
|
300
|
+
|
|
301
|
+
self.db_manager = new_manager
|
|
302
|
+
self.resolved_context = type(self.resolved_context)(
|
|
303
|
+
mode="per-repo",
|
|
304
|
+
context_name="",
|
|
305
|
+
database=local_db,
|
|
306
|
+
db_path=new_db_path,
|
|
307
|
+
cgcignore_path=str(cgc_dir / ".cgcignore"),
|
|
308
|
+
is_local=True,
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
# Rebuild dependent components with the new DB manager
|
|
312
|
+
self.graph_builder = GraphBuilder(self.db_manager, self.job_manager, self.loop)
|
|
313
|
+
self.code_finder = CodeFinder(self.db_manager)
|
|
314
|
+
self.code_watcher = CodeWatcher(self.graph_builder, self.job_manager)
|
|
315
|
+
|
|
316
|
+
if should_save:
|
|
317
|
+
save_workspace_mapping(self.cwd, cgc_dir)
|
|
318
|
+
|
|
319
|
+
self._context_note_pending = False
|
|
320
|
+
|
|
321
|
+
return {
|
|
322
|
+
"status": "ok",
|
|
323
|
+
"message": f"Switched to context at {cgc_dir}.",
|
|
324
|
+
"database": local_db,
|
|
325
|
+
"db_path": new_db_path,
|
|
326
|
+
"saved": should_save,
|
|
327
|
+
}
|
|
328
|
+
except Exception as e:
|
|
329
|
+
return {"error": f"Failed to switch context: {e}"}
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
async def handle_tool_call(self, tool_name: str, args: Dict[str, Any]) -> Dict[str, Any]:
|
|
333
|
+
"""
|
|
334
|
+
Routes a tool call from the AI assistant to the appropriate handler function.
|
|
335
|
+
"""
|
|
336
|
+
tool_map: Dict[str, Coroutine] = {
|
|
337
|
+
"add_package_to_graph": self.add_package_to_graph_tool,
|
|
338
|
+
"find_dead_code": self.find_dead_code_tool,
|
|
339
|
+
"find_code": self.find_code_tool,
|
|
340
|
+
"analyze_code_relationships": self.analyze_code_relationships_tool,
|
|
341
|
+
"watch_directory": self.watch_directory_tool,
|
|
342
|
+
"execute_cypher_query": self.execute_cypher_query_tool,
|
|
343
|
+
"add_code_to_graph": self.add_code_to_graph_tool,
|
|
344
|
+
"check_job_status": self.check_job_status_tool,
|
|
345
|
+
"list_jobs": self.list_jobs_tool,
|
|
346
|
+
"calculate_cyclomatic_complexity": self.calculate_cyclomatic_complexity_tool,
|
|
347
|
+
"find_most_complex_functions": self.find_most_complex_functions_tool,
|
|
348
|
+
"list_indexed_repositories": self.list_indexed_repositories_tool,
|
|
349
|
+
"delete_repository": self.delete_repository_tool,
|
|
350
|
+
"visualize_graph_query": self.visualize_graph_query_tool,
|
|
351
|
+
"list_watched_paths": self.list_watched_paths_tool,
|
|
352
|
+
"unwatch_directory": self.unwatch_directory_tool,
|
|
353
|
+
"load_bundle": self.load_bundle_tool,
|
|
354
|
+
"search_registry_bundles": self.search_registry_bundles_tool,
|
|
355
|
+
"get_repository_stats": self.get_repository_stats_tool,
|
|
356
|
+
"discover_codegraph_contexts": self.discover_codegraph_contexts_tool,
|
|
357
|
+
"switch_context": self.switch_context_tool,
|
|
358
|
+
}
|
|
359
|
+
handler = tool_map.get(tool_name)
|
|
360
|
+
if handler:
|
|
361
|
+
result = await asyncio.to_thread(handler, **args)
|
|
362
|
+
|
|
363
|
+
if self._context_note_pending and tool_name not in (
|
|
364
|
+
"discover_codegraph_contexts", "switch_context"
|
|
365
|
+
):
|
|
366
|
+
names = [c["repo_name"] for c in self.discovered_child_contexts]
|
|
367
|
+
note = (
|
|
368
|
+
"NOTE: No CodeGraphContext database was found at the current workspace root. "
|
|
369
|
+
f"However, the following child directories have indexed databases: {names}. "
|
|
370
|
+
"Use the `switch_context` tool to connect to one, or "
|
|
371
|
+
"`discover_codegraph_contexts` for a deeper scan."
|
|
372
|
+
)
|
|
373
|
+
if isinstance(result, dict):
|
|
374
|
+
result["_context_discovery_note"] = note
|
|
375
|
+
self._context_note_pending = False
|
|
376
|
+
|
|
377
|
+
return result
|
|
378
|
+
else:
|
|
379
|
+
return {"error": f"Unknown tool: {tool_name}"}
|
|
380
|
+
|
|
381
|
+
async def run(self):
|
|
382
|
+
"""
|
|
383
|
+
Runs the main server loop, listening for JSON-RPC requests from stdin.
|
|
384
|
+
"""
|
|
385
|
+
# info_logger("MCP Server is running. Waiting for requests...")
|
|
386
|
+
print("MCP Server is running. Waiting for requests...", file=sys.stderr, flush=True)
|
|
387
|
+
self.code_watcher.start()
|
|
388
|
+
|
|
389
|
+
loop = asyncio.get_event_loop()
|
|
390
|
+
while True:
|
|
391
|
+
try:
|
|
392
|
+
# Read a request from the standard input.
|
|
393
|
+
line = await loop.run_in_executor(None, sys.stdin.readline)
|
|
394
|
+
if not line:
|
|
395
|
+
debug_logger("Client disconnected (EOF received). Shutting down.")
|
|
396
|
+
break
|
|
397
|
+
|
|
398
|
+
request = json.loads(line.strip())
|
|
399
|
+
method = request.get('method')
|
|
400
|
+
params = request.get('params', {})
|
|
401
|
+
request_id = request.get('id')
|
|
402
|
+
|
|
403
|
+
response = {}
|
|
404
|
+
# Route the request based on the JSON-RPC method.
|
|
405
|
+
if method == 'initialize':
|
|
406
|
+
response = {
|
|
407
|
+
"jsonrpc": "2.0", "id": request_id,
|
|
408
|
+
"result": {
|
|
409
|
+
"protocolVersion": "2025-03-26",
|
|
410
|
+
"serverInfo": {
|
|
411
|
+
"name": "CodeGraphContext", "version": self._get_version(),
|
|
412
|
+
"systemPrompt": LLM_SYSTEM_PROMPT
|
|
413
|
+
},
|
|
414
|
+
"capabilities": {"tools": {"listTools": True}},
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
elif method == 'tools/list':
|
|
418
|
+
# Return the list of tools defined in _init_tools.
|
|
419
|
+
response = {
|
|
420
|
+
"jsonrpc": "2.0", "id": request_id,
|
|
421
|
+
"result": {"tools": list(self.tools.values())}
|
|
422
|
+
}
|
|
423
|
+
elif method == 'tools/call':
|
|
424
|
+
# Execute a tool call and return the result.
|
|
425
|
+
tool_name = params.get('name')
|
|
426
|
+
args = params.get('arguments', {})
|
|
427
|
+
result = await self.handle_tool_call(tool_name, args)
|
|
428
|
+
result = _strip_workspace_prefix(result)
|
|
429
|
+
|
|
430
|
+
if "error" in result:
|
|
431
|
+
response = {
|
|
432
|
+
"jsonrpc": "2.0", "id": request_id,
|
|
433
|
+
"error": {"code": -32000, "message": "Tool execution error", "data": result}
|
|
434
|
+
}
|
|
435
|
+
else:
|
|
436
|
+
response = {
|
|
437
|
+
"jsonrpc": "2.0", "id": request_id,
|
|
438
|
+
"result": {"content": [{"type": "text", "text": json.dumps(result, indent=2)}]}
|
|
439
|
+
}
|
|
440
|
+
elif method == 'notifications/initialized':
|
|
441
|
+
# This is a notification, no response needed.
|
|
442
|
+
pass
|
|
443
|
+
else:
|
|
444
|
+
# Handle unknown methods.
|
|
445
|
+
if request_id is not None:
|
|
446
|
+
response = {
|
|
447
|
+
"jsonrpc": "2.0", "id": request_id,
|
|
448
|
+
"error": {"code": -32601, "message": f"Method not found: {method}"}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
# Send the response to standard output if it's not a notification.
|
|
452
|
+
if request_id is not None and response:
|
|
453
|
+
print(json.dumps(response), flush=True)
|
|
454
|
+
|
|
455
|
+
except Exception as e:
|
|
456
|
+
error_logger(f"Error processing request: {e}\n{traceback.format_exc()}")
|
|
457
|
+
request_id = "unknown"
|
|
458
|
+
if 'request' in locals() and isinstance(request, dict):
|
|
459
|
+
request_id = request.get('id', "unknown")
|
|
460
|
+
|
|
461
|
+
error_response = {
|
|
462
|
+
"jsonrpc": "2.0", "id": request_id,
|
|
463
|
+
"error": {"code": -32603, "message": f"Internal error: {str(e)}", "data": traceback.format_exc()}
|
|
464
|
+
}
|
|
465
|
+
print(json.dumps(error_response), flush=True)
|
|
466
|
+
|
|
467
|
+
def shutdown(self):
|
|
468
|
+
"""Gracefully shuts down the server and its components."""
|
|
469
|
+
debug_logger("Shutting down server...")
|
|
470
|
+
self.code_watcher.stop()
|
|
471
|
+
self.db_manager.close_driver()
|