index.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /**
  2. * CodeGraph MCP Server
  3. *
  4. * Model Context Protocol server that exposes CodeGraph functionality
  5. * as tools for AI assistants like Claude.
  6. *
  7. * @module mcp
  8. *
  9. * @example
  10. * ```typescript
  11. * import { MCPServer } from 'codegraph';
  12. *
  13. * const server = new MCPServer('/path/to/project');
  14. * await server.start();
  15. * ```
  16. */
  17. import * as path from 'path';
  18. import CodeGraph, { findNearestCodeGraphRoot } from '../index';
  19. import { StdioTransport, JsonRpcRequest, JsonRpcNotification, ErrorCodes } from './transport';
  20. import { tools, ToolHandler } from './tools';
  21. /**
  22. * Convert a file:// URI to a filesystem path.
  23. * Handles URL encoding and Windows drive letter paths.
  24. */
  25. function fileUriToPath(uri: string): string {
  26. try {
  27. const url = new URL(uri);
  28. let filePath = decodeURIComponent(url.pathname);
  29. // On Windows, file:///C:/path produces pathname /C:/path — strip leading /
  30. if (process.platform === 'win32' && /^\/[a-zA-Z]:/.test(filePath)) {
  31. filePath = filePath.slice(1);
  32. }
  33. return path.resolve(filePath);
  34. } catch {
  35. // Fallback for non-standard URIs
  36. return uri.replace(/^file:\/\/\/?/, '');
  37. }
  38. }
  39. /**
  40. * MCP Server Info
  41. */
  42. const SERVER_INFO = {
  43. name: 'codegraph',
  44. version: '0.1.0',
  45. };
  46. /**
  47. * MCP Protocol Version
  48. */
  49. const PROTOCOL_VERSION = '2024-11-05';
  50. /**
  51. * MCP Server for CodeGraph
  52. *
  53. * Implements the Model Context Protocol to expose CodeGraph
  54. * functionality as tools that can be called by AI assistants.
  55. */
  56. export class MCPServer {
  57. private transport: StdioTransport;
  58. private cg: CodeGraph | null = null;
  59. private toolHandler: ToolHandler;
  60. private projectPath: string | null;
  61. constructor(projectPath?: string) {
  62. this.projectPath = projectPath || null;
  63. this.transport = new StdioTransport();
  64. // Create ToolHandler eagerly — cross-project queries work even without a default project
  65. this.toolHandler = new ToolHandler(null);
  66. }
  67. /**
  68. * Start the MCP server
  69. *
  70. * Note: CodeGraph initialization is deferred until the initialize request
  71. * is received, which includes the rootUri from the client.
  72. */
  73. async start(): Promise<void> {
  74. // Start listening for messages immediately - don't check initialization yet
  75. // We'll get the project path from the initialize request's rootUri
  76. this.transport.start(this.handleMessage.bind(this));
  77. // Keep the process running
  78. process.on('SIGINT', () => this.stop());
  79. process.on('SIGTERM', () => this.stop());
  80. // When the parent process (Claude Code) exits, stdin closes.
  81. // Detect this and shut down gracefully to prevent orphaned processes.
  82. process.stdin.on('end', () => this.stop());
  83. process.stdin.on('close', () => this.stop());
  84. }
  85. /**
  86. * Try to initialize CodeGraph for the default project.
  87. *
  88. * Walks up parent directories to find the nearest .codegraph/ folder,
  89. * similar to how git finds .git/ directories.
  90. *
  91. * If initialization fails, the error is recorded but the server continues
  92. * to work — cross-project queries and retries on subsequent tool calls
  93. * are still possible.
  94. */
  95. private async tryInitializeDefault(projectPath: string): Promise<void> {
  96. // Walk up parent directories to find nearest .codegraph/
  97. const resolvedRoot = findNearestCodeGraphRoot(projectPath);
  98. if (!resolvedRoot) {
  99. this.projectPath = projectPath;
  100. return;
  101. }
  102. this.projectPath = resolvedRoot;
  103. try {
  104. this.cg = await CodeGraph.open(resolvedRoot);
  105. this.toolHandler.setDefaultCodeGraph(this.cg);
  106. this.startWatching();
  107. } catch (err) {
  108. // Log the error so transient failures are diagnosable (see issue #47)
  109. const msg = err instanceof Error ? err.message : String(err);
  110. process.stderr.write(`[CodeGraph MCP] Failed to open project at ${resolvedRoot}: ${msg}\n`);
  111. }
  112. }
  113. /**
  114. * Retry initialization of the default project if it previously failed.
  115. * Called lazily on tool calls that need the default project.
  116. * Re-walks parent directories each time so it picks up projects
  117. * initialized after the MCP server started.
  118. */
  119. private retryInitIfNeeded(): void {
  120. // Already initialized successfully
  121. if (this.toolHandler.hasDefaultCodeGraph()) return;
  122. // No project path to retry with
  123. if (!this.projectPath) return;
  124. const resolvedRoot = findNearestCodeGraphRoot(this.projectPath);
  125. if (!resolvedRoot) return;
  126. try {
  127. // Close any previously failed instance to avoid leaking resources
  128. if (this.cg) {
  129. try { this.cg.close(); } catch { /* ignore */ }
  130. this.cg = null;
  131. }
  132. this.cg = CodeGraph.openSync(resolvedRoot);
  133. this.projectPath = resolvedRoot;
  134. this.toolHandler.setDefaultCodeGraph(this.cg);
  135. this.startWatching();
  136. } catch {
  137. // Still failing — will retry on next tool call
  138. }
  139. }
  140. /**
  141. * Start file watching on the active CodeGraph instance.
  142. * Logs sync activity to stderr for diagnostics.
  143. */
  144. private startWatching(): void {
  145. if (!this.cg) return;
  146. const started = this.cg.watch({
  147. onSyncComplete: (result) => {
  148. if (result.filesChanged > 0) {
  149. process.stderr.write(
  150. `[CodeGraph MCP] Auto-synced ${result.filesChanged} file(s) in ${result.durationMs}ms\n`
  151. );
  152. }
  153. },
  154. onSyncError: (err) => {
  155. process.stderr.write(`[CodeGraph MCP] Auto-sync error: ${err.message}\n`);
  156. },
  157. });
  158. if (started) {
  159. process.stderr.write('[CodeGraph MCP] File watcher active — graph will auto-sync on changes\n');
  160. }
  161. }
  162. /**
  163. * Stop the server
  164. */
  165. stop(): void {
  166. // Close all cached cross-project connections first
  167. this.toolHandler.closeAll();
  168. // Close the main CodeGraph instance
  169. if (this.cg) {
  170. this.cg.close();
  171. this.cg = null;
  172. }
  173. this.transport.stop();
  174. process.exit(0);
  175. }
  176. /**
  177. * Handle incoming JSON-RPC messages
  178. */
  179. private async handleMessage(message: JsonRpcRequest | JsonRpcNotification): Promise<void> {
  180. // Check if it's a request (has id) or notification (no id)
  181. const isRequest = 'id' in message;
  182. switch (message.method) {
  183. case 'initialize':
  184. if (isRequest) {
  185. await this.handleInitialize(message as JsonRpcRequest);
  186. }
  187. break;
  188. case 'initialized':
  189. // Notification that client has finished initialization
  190. // No action needed - the client is ready
  191. break;
  192. case 'tools/list':
  193. if (isRequest) {
  194. await this.handleToolsList(message as JsonRpcRequest);
  195. }
  196. break;
  197. case 'tools/call':
  198. if (isRequest) {
  199. await this.handleToolsCall(message as JsonRpcRequest);
  200. }
  201. break;
  202. case 'ping':
  203. if (isRequest) {
  204. this.transport.sendResult((message as JsonRpcRequest).id, {});
  205. }
  206. break;
  207. default:
  208. if (isRequest) {
  209. this.transport.sendError(
  210. (message as JsonRpcRequest).id,
  211. ErrorCodes.MethodNotFound,
  212. `Method not found: ${message.method}`
  213. );
  214. }
  215. }
  216. }
  217. /**
  218. * Handle initialize request
  219. */
  220. private async handleInitialize(request: JsonRpcRequest): Promise<void> {
  221. const params = request.params as {
  222. rootUri?: string;
  223. workspaceFolders?: Array<{ uri: string; name: string }>;
  224. } | undefined;
  225. // Extract project path from rootUri or workspaceFolders
  226. let projectPath = this.projectPath;
  227. if (params?.rootUri) {
  228. projectPath = fileUriToPath(params.rootUri);
  229. } else if (params?.workspaceFolders?.[0]?.uri) {
  230. projectPath = fileUriToPath(params.workspaceFolders[0].uri);
  231. }
  232. // Fall back to current working directory if no path provided
  233. if (!projectPath) {
  234. projectPath = process.cwd();
  235. }
  236. // Try to initialize the default project (non-fatal if it fails)
  237. await this.tryInitializeDefault(projectPath);
  238. // We accept the client's protocol version but respond with our supported version
  239. this.transport.sendResult(request.id, {
  240. protocolVersion: PROTOCOL_VERSION,
  241. capabilities: {
  242. tools: {},
  243. },
  244. serverInfo: SERVER_INFO,
  245. });
  246. }
  247. /**
  248. * Handle tools/list request
  249. */
  250. private async handleToolsList(request: JsonRpcRequest): Promise<void> {
  251. this.retryInitIfNeeded();
  252. this.transport.sendResult(request.id, {
  253. tools: this.toolHandler.getTools(),
  254. });
  255. }
  256. /**
  257. * Handle tools/call request
  258. */
  259. private async handleToolsCall(request: JsonRpcRequest): Promise<void> {
  260. const params = request.params as {
  261. name: string;
  262. arguments?: Record<string, unknown>;
  263. };
  264. if (!params || !params.name) {
  265. this.transport.sendError(
  266. request.id,
  267. ErrorCodes.InvalidParams,
  268. 'Missing tool name'
  269. );
  270. return;
  271. }
  272. const toolName = params.name;
  273. const toolArgs = params.arguments || {};
  274. // Validate tool exists
  275. const tool = tools.find(t => t.name === toolName);
  276. if (!tool) {
  277. this.transport.sendError(
  278. request.id,
  279. ErrorCodes.InvalidParams,
  280. `Unknown tool: ${toolName}`
  281. );
  282. return;
  283. }
  284. // If the default project isn't initialized yet, retry in case it was
  285. // initialized after the MCP server started (e.g. user ran codegraph init)
  286. this.retryInitIfNeeded();
  287. const result = await this.toolHandler.execute(toolName, toolArgs);
  288. this.transport.sendResult(request.id, result);
  289. }
  290. }
  291. // Export for use in CLI
  292. export { StdioTransport } from './transport';
  293. export { tools, ToolHandler } from './tools';