|
| 1 | +import { spawn, type ChildProcess } from "child_process"; |
| 2 | +import { createInterface, type Interface } from "readline"; |
| 3 | +import * as os from "os"; |
| 4 | + |
| 5 | +type JsonRpcRequest = { |
| 6 | + jsonrpc: "2.0"; |
| 7 | + id: number; |
| 8 | + method: string; |
| 9 | + params?: Record<string, unknown>; |
| 10 | +}; |
| 11 | + |
| 12 | +type JsonRpcResponse = { |
| 13 | + jsonrpc: "2.0"; |
| 14 | + id: number; |
| 15 | + result?: unknown; |
| 16 | + error?: { code: number; message: string; data?: unknown }; |
| 17 | +}; |
| 18 | + |
| 19 | +export type McpToolDefinition = { |
| 20 | + name: string; |
| 21 | + description?: string; |
| 22 | + inputSchema: { |
| 23 | + type: "object"; |
| 24 | + properties: Record<string, unknown>; |
| 25 | + required?: string[]; |
| 26 | + }; |
| 27 | +}; |
| 28 | + |
| 29 | +type ListToolsResult = { |
| 30 | + tools: McpToolDefinition[]; |
| 31 | +}; |
| 32 | + |
| 33 | +type CallToolResult = { |
| 34 | + content: Array<{ type: string; text?: string }>; |
| 35 | + isError?: boolean; |
| 36 | +}; |
| 37 | + |
| 38 | +export class McpClient { |
| 39 | + private process: ChildProcess | null = null; |
| 40 | + private reader: Interface | null = null; |
| 41 | + private nextId = 1; |
| 42 | + private pendingRequests = new Map<number, { resolve: (value: unknown) => void; reject: (error: Error) => void }>(); |
| 43 | + private buffer = ""; |
| 44 | + |
| 45 | + constructor( |
| 46 | + private readonly serverName: string, |
| 47 | + private readonly command: string, |
| 48 | + private readonly args: string[] = [], |
| 49 | + private readonly env?: Record<string, string> |
| 50 | + ) {} |
| 51 | + |
| 52 | + async connect(): Promise<void> { |
| 53 | + return new Promise((resolve, reject) => { |
| 54 | + const childEnv = { |
| 55 | + ...process.env, |
| 56 | + ...this.env, |
| 57 | + }; |
| 58 | + |
| 59 | + const isWindows = os.platform() === "win32"; |
| 60 | + |
| 61 | + if (isWindows) { |
| 62 | + // On Windows, .cmd files require shell: true to be spawned. |
| 63 | + // Build a single command string so cmd.exe handles quoting correctly. |
| 64 | + const cmd = [this.command + ".cmd", ...this.args].join(" "); |
| 65 | + this.process = spawn(cmd, [], { |
| 66 | + stdio: ["pipe", "pipe", "pipe"], |
| 67 | + env: childEnv, |
| 68 | + shell: true, |
| 69 | + windowsHide: true, |
| 70 | + }); |
| 71 | + } else { |
| 72 | + this.process = spawn(this.command, this.args, { |
| 73 | + stdio: ["pipe", "pipe", "pipe"], |
| 74 | + env: childEnv, |
| 75 | + }); |
| 76 | + } |
| 77 | + |
| 78 | + this.process.on("error", (err) => { |
| 79 | + reject(new Error(`Failed to start MCP server "${this.serverName}" (${this.command}): ${err.message}`)); |
| 80 | + }); |
| 81 | + |
| 82 | + this.process.on("exit", (code) => { |
| 83 | + const error = new Error(`MCP server "${this.serverName}" exited with code ${code}`); |
| 84 | + for (const [, pending] of this.pendingRequests) { |
| 85 | + pending.reject(error); |
| 86 | + } |
| 87 | + this.pendingRequests.clear(); |
| 88 | + }); |
| 89 | + |
| 90 | + if (this.process.stderr) { |
| 91 | + this.process.stderr.on("data", (data: Buffer) => { |
| 92 | + // MCP servers log to stderr; we ignore for now |
| 93 | + }); |
| 94 | + } |
| 95 | + |
| 96 | + this.reader = createInterface({ input: this.process.stdout! }); |
| 97 | + this.reader.on("line", (line: string) => { |
| 98 | + this.handleLine(line); |
| 99 | + }); |
| 100 | + |
| 101 | + // Send initialize request (MCP protocol handshake) |
| 102 | + this.sendRequest("initialize", { |
| 103 | + protocolVersion: "2024-11-05", |
| 104 | + capabilities: {}, |
| 105 | + clientInfo: { name: "deepcode-cli", version: "0.1.0" }, |
| 106 | + }) |
| 107 | + .then(() => { |
| 108 | + // Send initialized notification |
| 109 | + this.sendNotification("notifications/initialized"); |
| 110 | + resolve(); |
| 111 | + }) |
| 112 | + .catch(reject); |
| 113 | + }); |
| 114 | + } |
| 115 | + |
| 116 | + async listTools(): Promise<McpToolDefinition[]> { |
| 117 | + const result = (await this.sendRequest("tools/list", {})) as ListToolsResult; |
| 118 | + return result.tools ?? []; |
| 119 | + } |
| 120 | + |
| 121 | + async callTool(name: string, args: Record<string, unknown>): Promise<CallToolResult> { |
| 122 | + return (await this.sendRequest("tools/call", { name, arguments: args })) as CallToolResult; |
| 123 | + } |
| 124 | + |
| 125 | + disconnect(): void { |
| 126 | + if (this.reader) { |
| 127 | + this.reader.close(); |
| 128 | + this.reader = null; |
| 129 | + } |
| 130 | + if (this.process) { |
| 131 | + this.process.kill(); |
| 132 | + this.process = null; |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + private sendRequest(method: string, params: Record<string, unknown>): Promise<unknown> { |
| 137 | + return new Promise((resolve, reject) => { |
| 138 | + const id = this.nextId++; |
| 139 | + const request: JsonRpcRequest = { |
| 140 | + jsonrpc: "2.0", |
| 141 | + id, |
| 142 | + method, |
| 143 | + params, |
| 144 | + }; |
| 145 | + this.pendingRequests.set(id, { resolve, reject }); |
| 146 | + this.writeLine(JSON.stringify(request)); |
| 147 | + }); |
| 148 | + } |
| 149 | + |
| 150 | + private sendNotification(method: string, params?: Record<string, unknown>): void { |
| 151 | + const notification = { |
| 152 | + jsonrpc: "2.0" as const, |
| 153 | + method, |
| 154 | + params, |
| 155 | + }; |
| 156 | + this.writeLine(JSON.stringify(notification)); |
| 157 | + } |
| 158 | + |
| 159 | + private writeLine(data: string): void { |
| 160 | + if (this.process?.stdin) { |
| 161 | + this.process.stdin.write(data + "\n"); |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + private handleLine(line: string): void { |
| 166 | + try { |
| 167 | + const message = JSON.parse(line) as JsonRpcResponse; |
| 168 | + if (message.id !== undefined && this.pendingRequests.has(message.id)) { |
| 169 | + const pending = this.pendingRequests.get(message.id)!; |
| 170 | + this.pendingRequests.delete(message.id); |
| 171 | + if (message.error) { |
| 172 | + pending.reject(new Error(`MCP error: ${message.error.message}`)); |
| 173 | + } else { |
| 174 | + pending.resolve(message.result); |
| 175 | + } |
| 176 | + } |
| 177 | + } catch { |
| 178 | + // Ignore unparseable lines |
| 179 | + } |
| 180 | + } |
| 181 | +} |
0 commit comments