index.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. }
  83. /**
  84. * Try to initialize CodeGraph for the default project.
  85. *
  86. * Walks up parent directories to find the nearest .codegraph/ folder,
  87. * similar to how git finds .git/ directories.
  88. *
  89. * If initialization fails, the error is recorded but the server continues
  90. * to work — cross-project queries and retries on subsequent tool calls
  91. * are still possible.
  92. */
  93. private async tryInitializeDefault(projectPath: string): Promise<void> {
  94. // Walk up parent directories to find nearest .codegraph/
  95. const resolvedRoot = findNearestCodeGraphRoot(projectPath);
  96. if (!resolvedRoot) {
  97. this.projectPath = projectPath;
  98. return;
  99. }
  100. this.projectPath = resolvedRoot;
  101. try {
  102. this.cg = await CodeGraph.open(resolvedRoot);
  103. this.toolHandler.setDefaultCodeGraph(this.cg);
  104. } catch (err) {
  105. captureException(err);
  106. }
  107. }
  108. /**
  109. * Retry initialization of the default project if it previously failed.
  110. * Called lazily on tool calls that need the default project.
  111. */
  112. private retryInitIfNeeded(): void {
  113. // Already initialized successfully
  114. if (this.toolHandler.hasDefaultCodeGraph()) return;
  115. // No project path to retry with
  116. if (!this.projectPath) return;
  117. const resolvedRoot = findNearestCodeGraphRoot(this.projectPath);
  118. if (!resolvedRoot) return;
  119. try {
  120. this.cg = CodeGraph.openSync(resolvedRoot);
  121. this.projectPath = resolvedRoot;
  122. this.toolHandler.setDefaultCodeGraph(this.cg);
  123. } catch {
  124. // Still failing — will retry on next tool call
  125. }
  126. }
  127. /**
  128. * Stop the server
  129. */
  130. stop(): void {
  131. // Close all cached cross-project connections first
  132. this.toolHandler.closeAll();
  133. // Close the main CodeGraph instance
  134. if (this.cg) {
  135. this.cg.close();
  136. this.cg = null;
  137. }
  138. this.transport.stop();
  139. process.exit(0);
  140. }
  141. /**
  142. * Handle incoming JSON-RPC messages
  143. */
  144. private async handleMessage(message: JsonRpcRequest | JsonRpcNotification): Promise<void> {
  145. // Check if it's a request (has id) or notification (no id)
  146. const isRequest = 'id' in message;
  147. switch (message.method) {
  148. case 'initialize':
  149. if (isRequest) {
  150. await this.handleInitialize(message as JsonRpcRequest);
  151. }
  152. break;
  153. case 'initialized':
  154. // Notification that client has finished initialization
  155. // No action needed - the client is ready
  156. break;
  157. case 'tools/list':
  158. if (isRequest) {
  159. await this.handleToolsList(message as JsonRpcRequest);
  160. }
  161. break;
  162. case 'tools/call':
  163. if (isRequest) {
  164. await this.handleToolsCall(message as JsonRpcRequest);
  165. }
  166. break;
  167. case 'ping':
  168. if (isRequest) {
  169. this.transport.sendResult((message as JsonRpcRequest).id, {});
  170. }
  171. break;
  172. default:
  173. if (isRequest) {
  174. this.transport.sendError(
  175. (message as JsonRpcRequest).id,
  176. ErrorCodes.MethodNotFound,
  177. `Method not found: ${message.method}`
  178. );
  179. }
  180. }
  181. }
  182. /**
  183. * Handle initialize request
  184. */
  185. private async handleInitialize(request: JsonRpcRequest): Promise<void> {
  186. const params = request.params as {
  187. rootUri?: string;
  188. workspaceFolders?: Array<{ uri: string; name: string }>;
  189. } | undefined;
  190. // Extract project path from rootUri or workspaceFolders
  191. let projectPath = this.projectPath;
  192. if (params?.rootUri) {
  193. projectPath = fileUriToPath(params.rootUri);
  194. } else if (params?.workspaceFolders?.[0]?.uri) {
  195. projectPath = fileUriToPath(params.workspaceFolders[0].uri);
  196. }
  197. // Fall back to current working directory if no path provided
  198. if (!projectPath) {
  199. projectPath = process.cwd();
  200. }
  201. // Try to initialize the default project (non-fatal if it fails)
  202. await this.tryInitializeDefault(projectPath);
  203. // We accept the client's protocol version but respond with our supported version
  204. this.transport.sendResult(request.id, {
  205. protocolVersion: PROTOCOL_VERSION,
  206. capabilities: {
  207. tools: {},
  208. },
  209. serverInfo: SERVER_INFO,
  210. });
  211. }
  212. /**
  213. * Handle tools/list request
  214. */
  215. private async handleToolsList(request: JsonRpcRequest): Promise<void> {
  216. this.transport.sendResult(request.id, {
  217. tools: tools,
  218. });
  219. }
  220. /**
  221. * Handle tools/call request
  222. */
  223. private async handleToolsCall(request: JsonRpcRequest): Promise<void> {
  224. const params = request.params as {
  225. name: string;
  226. arguments?: Record<string, unknown>;
  227. };
  228. if (!params || !params.name) {
  229. this.transport.sendError(
  230. request.id,
  231. ErrorCodes.InvalidParams,
  232. 'Missing tool name'
  233. );
  234. return;
  235. }
  236. const toolName = params.name;
  237. const toolArgs = params.arguments || {};
  238. // Validate tool exists
  239. const tool = tools.find(t => t.name === toolName);
  240. if (!tool) {
  241. this.transport.sendError(
  242. request.id,
  243. ErrorCodes.InvalidParams,
  244. `Unknown tool: ${toolName}`
  245. );
  246. return;
  247. }
  248. // If the default project isn't initialized yet, retry in case it was
  249. // initialized after the MCP server started (e.g. user ran codegraph init)
  250. this.retryInitIfNeeded();
  251. const result = await this.toolHandler.execute(toolName, toolArgs);
  252. this.transport.sendResult(request.id, result);
  253. }
  254. }
  255. // Export for use in CLI
  256. export { StdioTransport } from './transport';
  257. export { tools, ToolHandler } from './tools';