import type { ChildProcess } from 'node:child_process'; type JsonRpcMessage = { jsonrpc?: string; id?: string | number; method?: string; result?: unknown; error?: { code?: number; message?: string } }; export type McpTool = { name: string; description?: string; inputSchema?: { type?: string; properties?: Record; required?: string[] }; annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean } }; type PendingRequest = { resolve: (value: unknown) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }; export class StdioMcpClient { private sequence = 0; private buffer = ''; private readonly pending = new Map(); private tools: McpTool[] = []; private closed = false; private stderr = ''; constructor(private readonly process: ChildProcess, private readonly label: string, private readonly secrets: string[] = []) { process.stdout?.setEncoding('utf8'); process.stdout?.on('data', (chunk: string) => this.read(chunk)); process.stderr?.setEncoding('utf8'); process.stderr?.on('data', (chunk: string) => { this.stderr = `${this.stderr}${chunk}`.slice(-4000); }); process.on('error', (error) => this.failAll(new Error(`${label}: server process could not start (${(error as NodeJS.ErrnoException).code ?? 'unknown'}).`))); process.on('exit', (code, signal) => { this.closed = true; const details = this.stderr.trim().split(/\r?\n/).slice(-8).join('\n').replace(/\x1b\[[0-9;]*m/g, ''); const redacted = this.secrets.filter(Boolean).reduce((text, secret) => text.split(secret).join('[redacted]'), details); this.failAll(new Error(`${label}: server exited (${signal ?? code ?? 'unknown'}).${redacted ? `\n${redacted}` : ''}`)); }); } async initialize(): Promise { await this.request('initialize', { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'ProjectOS MCP Fabric', version: '0.1.0' } }, 120_000); this.notify('notifications/initialized'); const result = await this.request('tools/list', {}); const tools = (result as { tools?: unknown } | null)?.tools; this.tools = Array.isArray(tools) ? tools.filter((item): item is McpTool => Boolean(item && typeof item === 'object' && typeof (item as { name?: unknown }).name === 'string')) : []; return this.tools; } get availableTools(): McpTool[] { return this.tools; } async callTool(name: string, args: Record = {}): Promise { if (!this.tools.some((tool) => tool.name === name)) throw new Error(`${this.label}: server does not expose tool '${name}'.`); const result = await this.request('tools/call', { name, arguments: args }); if ((result as { isError?: unknown } | null)?.isError === true) throw new Error(`${this.label}: tool '${name}' returned an error.`); return result; } async close(): Promise { if (this.closed) return; this.process.stdin?.end(); await new Promise((resolve) => { const timer = setTimeout(resolve, 2000); this.process.once('close', () => { clearTimeout(timer); resolve(); }); }); if (!this.closed) this.process.kill(); this.closed = true; this.failAll(new Error(`${this.label}: connection closed.`)); } private async request(method: string, params: unknown, timeoutMs = 30_000): Promise { if (this.closed || !this.process.stdin?.writable) throw new Error(`${this.label}: connection is not open.`); const id = ++this.sequence; const key = id; return new Promise((resolve, reject) => { const timer = setTimeout(() => { this.pending.delete(key); reject(new Error(`${this.label}: ${method} timed out.`)); }, timeoutMs); this.pending.set(key, { resolve, reject, timer }); this.process.stdin!.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`, (error) => { if (!error) return; const pending = this.pending.get(key); if (!pending) return; clearTimeout(pending.timer); this.pending.delete(key); reject(new Error(`${this.label}: could not send ${method}.`)); }); }); } private notify(method: string, params?: unknown): void { if (this.closed || !this.process.stdin?.writable) return; this.process.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', method, ...(params === undefined ? {} : { params }) })}\n`); } private read(chunk: string): void { this.buffer += chunk; let newline = this.buffer.indexOf('\n'); while (newline >= 0) { const line = this.buffer.slice(0, newline).trim(); this.buffer = this.buffer.slice(newline + 1); if (line) this.handleLine(line); newline = this.buffer.indexOf('\n'); } } private handleLine(line: string): void { let message: JsonRpcMessage; try { message = JSON.parse(line) as JsonRpcMessage; } catch { return; } if (message.id === undefined) return; const pending = this.pending.get(message.id); if (!pending) return; clearTimeout(pending.timer); this.pending.delete(message.id); if (message.error) pending.reject(new Error(`${this.label}: server rejected a request (${message.error.code ?? 'unknown'}).`)); else pending.resolve(message.result); } private failAll(error: Error): void { for (const [id, pending] of this.pending) { clearTimeout(pending.timer); pending.reject(error); this.pending.delete(id); } } }