File size: 5,510 Bytes
a8f4b72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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<string, unknown>; 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<string | number, PendingRequest>();
  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<McpTool[]> {
    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<string, unknown> = {}): Promise<unknown> {
    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<void> {
    if (this.closed) return;
    this.process.stdin?.end();
    await new Promise<void>((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<unknown> {
    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);
    }
  }
}