index.ts 8.2 KB

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