@sontoriyama/mcp-code-mode 0.0.0-stage → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,891 @@
1
+ // Zero-dependency stdio MCP (JSON-RPC 2.0 over NDJSON) client with lazy-spawn,
2
+ // AbortSignal cancellation (notifications/cancelled), dirty-stdout tolerance,
3
+ // bidirectional JSON-RPC (server ping), bounded stdout buffer, schema compaction,
4
+ // Windows .cmd/.bat handling, and process-tree clean shutdown.
5
+ import { spawn } from 'node:child_process';
6
+ import { existsSync, readFileSync } from 'node:fs';
7
+ import { createRequire } from 'node:module';
8
+ import { delimiter, extname, join, resolve } from 'node:path';
9
+ import { ToolCallError } from './core.mjs';
10
+
11
+ const SAFE_ALIAS_RE = /^[A-Za-z][A-Za-z0-9_-]*$/;
12
+ const RESERVED_ALIASES = new Set(['__proto__', 'prototype', 'constructor', 'describe', 'call', 'close', 'list']);
13
+ const IGNORED_PROXY_PROPS = new Set([
14
+ ...RESERVED_ALIASES,
15
+ 'then', 'catch', 'finally',
16
+ 'toJSON', 'toString', 'valueOf', 'toLocaleString',
17
+ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
18
+ 'inspect', '$$typeof',
19
+ ]);
20
+ const DEFAULT_TIMEOUT_MS = 60000;
21
+ const MAX_LIST_PAGES = 20;
22
+ const MAX_BUFFER_CHARS = 16 * 1024 * 1024;
23
+ const MODERN_PROTOCOL_VERSION = '2026-07-28';
24
+ const LEGACY_PROTOCOL_VERSION = '2025-11-25';
25
+ const LEGACY_FALLBACK_VERSIONS = [LEGACY_PROTOCOL_VERSION, '2024-11-05'];
26
+ const MODERN_PROBE_TIMEOUT_MS = 2000;
27
+ const RECYCLE_AFTER_TIMEOUTS = 2;
28
+
29
+ const PKG = createRequire(import.meta.url)('../package.json');
30
+ const CLIENT_INFO = Object.freeze({ name: PKG.name, version: PKG.version });
31
+
32
+ function isModernVersion(version) {
33
+ return typeof version === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(version) && version >= MODERN_PROTOCOL_VERSION;
34
+ }
35
+
36
+ export function modernMeta(protocolVersion = MODERN_PROTOCOL_VERSION) {
37
+ return {
38
+ 'io.modelcontextprotocol/protocolVersion': protocolVersion,
39
+ 'io.modelcontextprotocol/clientInfo': { ...CLIENT_INFO },
40
+ 'io.modelcontextprotocol/clientCapabilities': {},
41
+ };
42
+ }
43
+
44
+ export function validateMcpAlias(alias) {
45
+ if (typeof alias !== 'string' || !SAFE_ALIAS_RE.test(alias) || RESERVED_ALIASES.has(alias)) {
46
+ throw new Error(`invalid MCP server alias: ${alias}`);
47
+ }
48
+ return alias;
49
+ }
50
+
51
+ function tokenizeCommand(raw) {
52
+ const tokens = [];
53
+ let current = '';
54
+ let hasToken = false;
55
+ let quote = null;
56
+ for (let i = 0; i < raw.length; i++) {
57
+ const ch = raw[i];
58
+ if (quote) {
59
+ if (ch === quote) {
60
+ quote = null;
61
+ } else if (ch === '\\' && quote === '"' && (raw[i + 1] === '"' || raw[i + 1] === '\\')) {
62
+ current += raw[++i];
63
+ } else {
64
+ current += ch;
65
+ }
66
+ continue;
67
+ }
68
+ if (ch === '"' || ch === "'") {
69
+ quote = ch;
70
+ hasToken = true;
71
+ } else if (/\s/.test(ch)) {
72
+ if (hasToken) {
73
+ tokens.push(current);
74
+ current = '';
75
+ hasToken = false;
76
+ }
77
+ } else {
78
+ current += ch;
79
+ hasToken = true;
80
+ }
81
+ }
82
+ if (quote) throw new Error(`unterminated quote in --mcp command: ${raw}`);
83
+ if (hasToken) tokens.push(current);
84
+ return tokens;
85
+ }
86
+
87
+ export function parseMcpInlineSpec(spec) {
88
+ if (typeof spec !== 'string' || !spec.includes('=')) {
89
+ throw new Error(`--mcp expects "alias=command [args...]", got: ${spec}`);
90
+ }
91
+ const eq = spec.indexOf('=');
92
+ const alias = validateMcpAlias(spec.slice(0, eq).trim());
93
+ const parts = tokenizeCommand(spec.slice(eq + 1).trim());
94
+ if (parts.length === 0) {
95
+ throw new Error(`--mcp "${alias}" requires a non-empty command`);
96
+ }
97
+ return { alias, config: { command: parts[0], args: parts.slice(1) } };
98
+ }
99
+
100
+ export function loadMcpConfig(configPath) {
101
+ const fullPath = resolve(configPath);
102
+ const parsed = JSON.parse(readFileSync(fullPath, 'utf8'));
103
+ const rawServers = parsed?.mcpServers ?? parsed?.servers;
104
+ if (!rawServers || typeof rawServers !== 'object' || Array.isArray(rawServers)) {
105
+ throw new Error('MCP config must contain an "mcpServers" object');
106
+ }
107
+ const servers = Object.create(null);
108
+ for (const [alias, cfg] of Object.entries(rawServers)) {
109
+ validateMcpAlias(alias);
110
+ if (!cfg || typeof cfg.command !== 'string' || cfg.command.trim().length === 0) {
111
+ throw new Error(`MCP server "${alias}" must specify a non-empty "command"`);
112
+ }
113
+ if (cfg.args !== undefined && !Array.isArray(cfg.args)) {
114
+ throw new Error(`MCP server "${alias}" "args" must be an array`);
115
+ }
116
+ let env;
117
+ if (cfg.env !== undefined) {
118
+ if (!cfg.env || typeof cfg.env !== 'object' || Array.isArray(cfg.env)) {
119
+ throw new Error(`MCP server "${alias}" "env" must be a plain object`);
120
+ }
121
+ env = {};
122
+ for (const [k, v] of Object.entries(cfg.env)) {
123
+ if (typeof v !== 'string' && typeof v !== 'number' && typeof v !== 'boolean') {
124
+ throw new Error(`MCP server "${alias}" env.${k} must be a primitive`);
125
+ }
126
+ env[k] = String(v);
127
+ }
128
+ }
129
+ servers[alias] = {
130
+ command: cfg.command,
131
+ args: Array.isArray(cfg.args) ? cfg.args.map(String) : [],
132
+ env,
133
+ cwd: typeof cfg.cwd === 'string' ? cfg.cwd : undefined,
134
+ timeout: Number.isInteger(cfg.timeout) && cfg.timeout > 0 ? cfg.timeout : DEFAULT_TIMEOUT_MS,
135
+ inheritEnv: cfg.inheritEnv !== false,
136
+ };
137
+ }
138
+ return servers;
139
+ }
140
+
141
+ export function compactInputSchema(schema) {
142
+ const out = Object.create(null);
143
+ if (!schema || typeof schema !== 'object') return out;
144
+ const props = schema.properties && typeof schema.properties === 'object' ? schema.properties : {};
145
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
146
+ for (const [name, prop] of Object.entries(props)) {
147
+ if (!prop || typeof prop !== 'object') {
148
+ out[name] = required.has(name) ? 'any (required)' : 'any (optional)';
149
+ continue;
150
+ }
151
+ let typeLabel = 'any';
152
+ if (Array.isArray(prop.enum) && prop.enum.length > 0) {
153
+ typeLabel = prop.enum.slice(0, 6).map(String).join('|') + (prop.enum.length > 6 ? '|...' : '');
154
+ } else if (Array.isArray(prop.anyOf) && prop.anyOf.length > 0) {
155
+ typeLabel = prop.anyOf.map((s) => s?.type || 'any').slice(0, 4).join('|');
156
+ } else if (Array.isArray(prop.oneOf) && prop.oneOf.length > 0) {
157
+ typeLabel = prop.oneOf.map((s) => s?.type || 'any').slice(0, 4).join('|');
158
+ } else if (Array.isArray(prop.type) && prop.type.length > 0) {
159
+ typeLabel = prop.type.slice(0, 4).join('|');
160
+ } else if (prop.type === 'array') {
161
+ typeLabel = `${prop.items?.type || 'any'}[]`;
162
+ } else if (typeof prop.type === 'string') {
163
+ typeLabel = prop.type;
164
+ }
165
+ let reqTag = 'optional';
166
+ if (required.has(name)) {
167
+ reqTag = 'required';
168
+ } else if (prop.default !== undefined) {
169
+ const defStr = JSON.stringify(prop.default);
170
+ reqTag = `default: ${defStr.length > 32 ? `${defStr.slice(0, 29)}...` : defStr}`;
171
+ }
172
+ const desc = typeof prop.description === 'string' && prop.description.trim()
173
+ ? ` — ${prop.description.trim().slice(0, 72)}`
174
+ : '';
175
+ out[name] = `${typeLabel} (${reqTag})${desc}`;
176
+ }
177
+ return out;
178
+ }
179
+
180
+ function unwrapMcpResult(toolName, result) {
181
+ if (!result || typeof result !== 'object') return result ?? null;
182
+ if (result.isError) {
183
+ const texts = Array.isArray(result.content)
184
+ ? result.content
185
+ .filter((c) => c?.type === 'text' && typeof c.text === 'string' && c.text.length > 0)
186
+ .map((c) => c.text)
187
+ : [];
188
+ throw new ToolCallError(toolName, texts.length > 0 ? texts.join('\n') : 'MCP tool returned isError=true');
189
+ }
190
+ if (result.structuredContent !== undefined) return result.structuredContent;
191
+ if (Array.isArray(result.content) && result.content.length === 1 && result.content[0]?.type === 'text') {
192
+ const text = result.content[0].text;
193
+ const trimmed = typeof text === 'string' ? text.trim() : '';
194
+ if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
195
+ try {
196
+ return JSON.parse(trimmed);
197
+ } catch {
198
+ return text;
199
+ }
200
+ }
201
+ return text;
202
+ }
203
+ return result.content ?? result;
204
+ }
205
+
206
+ function getEnvVar(env, name) {
207
+ if (!env) return undefined;
208
+ if (env[name] !== undefined) return env[name];
209
+ const upper = name.toUpperCase();
210
+ for (const [k, v] of Object.entries(env)) {
211
+ if (k.toUpperCase() === upper) return v;
212
+ }
213
+ return undefined;
214
+ }
215
+
216
+ function resolveWindowsBatchTarget(command, env, cwd) {
217
+ const ext = extname(command).toLowerCase();
218
+ if (ext === '.cmd' || ext === '.bat') return command.replaceAll('/', '\\');
219
+ if (ext) return null;
220
+
221
+ const pathext = (getEnvVar(env, 'PATHEXT') || '.COM;.EXE;.BAT;.CMD')
222
+ .split(';')
223
+ .map((e) => e.trim().toLowerCase())
224
+ .filter(Boolean);
225
+
226
+ if (command.includes('\\') || command.includes('/')) {
227
+ for (const candidateExt of pathext) {
228
+ const full = `${command}${candidateExt}`;
229
+ const probe = cwd ? resolve(cwd, full) : full;
230
+ if (existsSync(probe)) {
231
+ return candidateExt === '.cmd' || candidateExt === '.bat'
232
+ ? full.replaceAll('/', '\\')
233
+ : null;
234
+ }
235
+ }
236
+ return null;
237
+ }
238
+
239
+ const pathEnv = getEnvVar(env, 'PATH') || '';
240
+ const dirs = pathEnv.split(delimiter).filter(Boolean);
241
+ for (const dir of dirs) {
242
+ for (const candidateExt of pathext) {
243
+ const full = join(dir, `${command}${candidateExt}`);
244
+ if (existsSync(full)) {
245
+ return candidateExt === '.cmd' || candidateExt === '.bat' ? full : null;
246
+ }
247
+ }
248
+ }
249
+ return null;
250
+ }
251
+
252
+ export function quoteCmdArg(arg) {
253
+ const str = String(arg);
254
+ if (/[\r\n\0"%]/.test(str)) {
255
+ throw new Error('MCP .cmd/.bat argument contains forbidden character (newline, NUL, quote, or %)');
256
+ }
257
+ if (str.length === 0) return '""';
258
+ if (/[\s&|<>^!(),;=]/.test(str)) {
259
+ return `"${str.replace(/\\+$/, '$&$&')}"`;
260
+ }
261
+ return str;
262
+ }
263
+
264
+ function buildSpawnSpec(command, args, env, cwd) {
265
+ if (process.platform === 'win32') {
266
+ const batchTarget = resolveWindowsBatchTarget(command, env, cwd);
267
+ if (batchTarget) {
268
+ const comspec = getEnvVar(env, 'ComSpec') || process.env.ComSpec || 'cmd.exe';
269
+ const cmdLine = [quoteCmdArg(batchTarget), ...args.map(quoteCmdArg)].join(' ');
270
+ return {
271
+ cmd: comspec,
272
+ args: ['/d', '/s', '/c', `"${cmdLine}"`],
273
+ windowsVerbatimArguments: true,
274
+ };
275
+ }
276
+ }
277
+ return { cmd: command, args, windowsVerbatimArguments: false };
278
+ }
279
+
280
+ function raceWithAbort(promise, toolName, { signal, timeout } = {}) {
281
+ if (signal?.aborted) {
282
+ return Promise.reject(new ToolCallError(toolName, 'aborted'));
283
+ }
284
+ if (!signal && !(Number.isInteger(timeout) && timeout > 0)) {
285
+ return promise;
286
+ }
287
+ return new Promise((resolvePromise, rejectPromise) => {
288
+ let settled = false;
289
+ let timer = null;
290
+ const cleanup = () => {
291
+ if (timer) clearTimeout(timer);
292
+ if (signal) signal.removeEventListener('abort', onAbort);
293
+ };
294
+ const onAbort = () => {
295
+ if (settled) return;
296
+ settled = true;
297
+ cleanup();
298
+ rejectPromise(new ToolCallError(toolName, 'aborted while waiting for MCP initialization'));
299
+ };
300
+ if (signal) signal.addEventListener('abort', onAbort, { once: true });
301
+ if (Number.isInteger(timeout) && timeout > 0) {
302
+ timer = setTimeout(() => {
303
+ if (settled) return;
304
+ settled = true;
305
+ cleanup();
306
+ rejectPromise(new ToolCallError(toolName, `MCP initialization timed out after ${timeout}ms`));
307
+ }, timeout);
308
+ timer.unref?.();
309
+ }
310
+ promise.then(
311
+ (val) => {
312
+ if (settled) return;
313
+ settled = true;
314
+ cleanup();
315
+ resolvePromise(val);
316
+ },
317
+ (err) => {
318
+ if (settled) return;
319
+ settled = true;
320
+ cleanup();
321
+ rejectPromise(err);
322
+ },
323
+ );
324
+ });
325
+ }
326
+
327
+ export class McpStdioClient {
328
+ constructor(alias, config, opts) {
329
+ this.alias = validateMcpAlias(alias);
330
+ this.config = config;
331
+ this.verbose = Boolean(opts?.verbose) || process.env.CODEMODE_MCP_VERBOSE === '1';
332
+ this.child = null;
333
+ this.nextId = 1;
334
+ this.pending = new Map();
335
+ this.buffer = '';
336
+ this.readyPromise = null;
337
+ this.closePromise = null;
338
+ this.closed = false;
339
+ this.era = null; // 'modern' | 'legacy'
340
+ this.protocolVersion = null;
341
+ this.serverInfo = null;
342
+ this.instructions = undefined;
343
+ this.timeoutStreak = 0;
344
+ }
345
+
346
+ _modernMeta(protocolVersion = this.protocolVersion ?? MODERN_PROTOCOL_VERSION) {
347
+ return modernMeta(protocolVersion);
348
+ }
349
+
350
+ _resetChild(child, err) {
351
+ if (this.child !== child) return;
352
+ this.child = null;
353
+ this.readyPromise = null;
354
+ this.buffer = '';
355
+ if (err) this._failAll(err);
356
+ }
357
+
358
+ _spawnIfNeeded() {
359
+ if (this.child) return;
360
+ if (this.closed) {
361
+ throw new ToolCallError(`mcp.${this.alias}`, 'MCP client is closed');
362
+ }
363
+ const baseEnv = this.config.inheritEnv === false ? {} : { ...process.env };
364
+ const env = this.config.env ? { ...baseEnv, ...this.config.env } : baseEnv;
365
+ const spec = buildSpawnSpec(this.config.command, this.config.args ?? [], env, this.config.cwd);
366
+
367
+ const child = spawn(spec.cmd, spec.args, {
368
+ cwd: this.config.cwd,
369
+ env,
370
+ stdio: ['pipe', 'pipe', 'pipe'],
371
+ shell: false,
372
+ detached: process.platform !== 'win32',
373
+ windowsHide: true,
374
+ windowsVerbatimArguments: spec.windowsVerbatimArguments,
375
+ });
376
+ this.child = child;
377
+ this.buffer = '';
378
+
379
+ child.stdin.on('error', (err) => {
380
+ if (this.child !== child) return;
381
+ if (this.verbose) {
382
+ process.stderr.write(`[mcp:${this.alias}:stdin-error] ${err.code || err.message}\n`);
383
+ }
384
+ if (!this.closed && err.code !== 'EPIPE' && err.code !== 'ERR_STREAM_DESTROYED') {
385
+ this._failAll(new ToolCallError(`mcp.${this.alias}`, `stdin error: ${err.message}`));
386
+ }
387
+ });
388
+
389
+ child.stdout.setEncoding('utf8');
390
+ child.stdout.on('data', (chunk) => {
391
+ if (this.child !== child) return;
392
+ this._onStdoutChunk(chunk);
393
+ });
394
+
395
+ child.stderr.setEncoding('utf8');
396
+ child.stderr.on('data', (chunk) => {
397
+ if (this.verbose) process.stderr.write(`[mcp:${this.alias}:stderr] ${chunk}`);
398
+ });
399
+
400
+ child.on('error', (err) => {
401
+ this._resetChild(child, new ToolCallError(`mcp.${this.alias}`, `spawn failed: ${err.message}`));
402
+ });
403
+
404
+ child.on('close', (code, signal) => {
405
+ const reason = signal ? `signal ${signal}` : `code ${code}`;
406
+ this._resetChild(child, new ToolCallError(`mcp.${this.alias}`, `MCP server exited unexpectedly (${reason})`));
407
+ });
408
+ }
409
+
410
+ _handleLine(line) {
411
+ let msg;
412
+ try {
413
+ msg = JSON.parse(line);
414
+ } catch {
415
+ if (this.verbose) {
416
+ process.stderr.write(`[mcp:${this.alias}:stdout-ignored] ${line.slice(0, 160)}\n`);
417
+ }
418
+ return;
419
+ }
420
+ if (!msg || typeof msg !== 'object') return;
421
+
422
+ // 1) Incoming server request or notification (prevent client/server ID collision)
423
+ if (typeof msg.method === 'string') {
424
+ if (msg.id !== undefined && msg.id !== null) {
425
+ try {
426
+ if (msg.method === 'ping') {
427
+ this._send({ jsonrpc: '2.0', id: msg.id, result: {} });
428
+ } else {
429
+ this._send({
430
+ jsonrpc: '2.0',
431
+ id: msg.id,
432
+ error: { code: -32601, message: `Method not found: ${msg.method}` },
433
+ });
434
+ }
435
+ } catch {}
436
+ }
437
+ return;
438
+ }
439
+
440
+ // 2) Response to one of our pending requests
441
+ if (msg.id !== undefined && this.pending.has(msg.id)) {
442
+ const entry = this.pending.get(msg.id);
443
+ this.pending.delete(msg.id);
444
+ entry.cleanup();
445
+ this.timeoutStreak = 0;
446
+ if (msg.error !== undefined && msg.error !== null) {
447
+ const errMsg = msg.error.message || JSON.stringify(msg.error);
448
+ const err = new ToolCallError(entry.toolName, errMsg);
449
+ if (msg.error.code !== undefined) err.code = msg.error.code;
450
+ if (msg.error.data !== undefined) err.data = msg.error.data;
451
+ entry.reject(err);
452
+ } else {
453
+ entry.resolve(msg.result);
454
+ }
455
+ }
456
+ }
457
+
458
+ _onStdoutChunk(chunk) {
459
+ this.buffer += chunk;
460
+ if (this.buffer.length > MAX_BUFFER_CHARS) {
461
+ const doomed = this.child;
462
+ this._resetChild(doomed, new ToolCallError(`mcp.${this.alias}`, 'MCP stdout buffer exceeded limit'));
463
+ this._killTree(doomed, 'SIGKILL', { forceGroup: true });
464
+ return;
465
+ }
466
+ let start = 0;
467
+ let idx;
468
+ while ((idx = this.buffer.indexOf('\n', start)) !== -1) {
469
+ const line = this.buffer.slice(start, idx).replace(/\r$/, '').trim();
470
+ start = idx + 1;
471
+ if (!line) continue;
472
+ this._handleLine(line);
473
+ }
474
+ if (start > 0) this.buffer = this.buffer.slice(start);
475
+ }
476
+
477
+ _failAll(err) {
478
+ for (const [id, entry] of this.pending.entries()) {
479
+ this.pending.delete(id);
480
+ entry.cleanup();
481
+ entry.reject(err);
482
+ }
483
+ }
484
+
485
+ _killTree(child, signal, { forceGroup = false } = {}) {
486
+ if (!child) return;
487
+ const directAlive = child.exitCode === null && child.signalCode === null;
488
+ if (process.platform === 'win32') {
489
+ if (!directAlive || signal !== 'SIGKILL') return;
490
+ if (child.pid) {
491
+ try {
492
+ const killer = spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], {
493
+ windowsHide: true,
494
+ stdio: 'ignore',
495
+ });
496
+ killer.on('error', () => {
497
+ if (child.exitCode === null && child.signalCode === null) {
498
+ try { child.kill(); } catch {}
499
+ }
500
+ });
501
+ killer.unref?.();
502
+ return;
503
+ } catch {}
504
+ }
505
+ try { child.kill(); } catch {}
506
+ return;
507
+ }
508
+ if (child.pid && (directAlive || forceGroup)) {
509
+ try {
510
+ process.kill(-child.pid, signal);
511
+ return;
512
+ } catch {}
513
+ }
514
+ if (directAlive) {
515
+ try { child.kill(signal); } catch {}
516
+ }
517
+ }
518
+
519
+ _send(payload) {
520
+ if (!this.child || !this.child.stdin || this.child.stdin.destroyed) {
521
+ throw new ToolCallError(`mcp.${this.alias}`, 'MCP server stdin is not writable');
522
+ }
523
+ this.child.stdin.write(`${JSON.stringify(payload)}\n`);
524
+ }
525
+
526
+ _request(toolName, method, params, opts) {
527
+ const timeout = opts?.timeout;
528
+ const signal = opts?.signal;
529
+ if (this.closed) {
530
+ return Promise.reject(new ToolCallError(toolName, 'MCP client is closed'));
531
+ }
532
+ if (signal?.aborted) {
533
+ return Promise.reject(new ToolCallError(toolName, 'aborted'));
534
+ }
535
+
536
+ this._spawnIfNeeded();
537
+
538
+ const id = this.nextId++;
539
+ const ms = Number.isInteger(timeout) && timeout > 0
540
+ ? timeout
541
+ : (this.config.timeout ?? DEFAULT_TIMEOUT_MS);
542
+
543
+ return new Promise((resolvePromise, rejectPromise) => {
544
+ const timer = setTimeout(() => {
545
+ if (!this.pending.has(id)) return;
546
+ this.pending.delete(id);
547
+ cleanup();
548
+ try {
549
+ this._send({ jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId: id, reason: 'timeout' } });
550
+ } catch {}
551
+ this.timeoutStreak += 1;
552
+ const doomed = this.child;
553
+ if (this.timeoutStreak >= RECYCLE_AFTER_TIMEOUTS && doomed) {
554
+ this._resetChild(
555
+ doomed,
556
+ new ToolCallError(
557
+ `mcp.${this.alias}`,
558
+ `MCP server "${this.alias}" ignored cancellation and timed out ${this.timeoutStreak} times; client recycled`,
559
+ ),
560
+ );
561
+ this._killTree(doomed, 'SIGKILL', { forceGroup: true });
562
+ }
563
+ rejectPromise(new ToolCallError(toolName, `MCP request "${method}" timed out after ${ms}ms`));
564
+ }, ms);
565
+ timer.unref?.();
566
+
567
+ const onAbort = () => {
568
+ if (!this.pending.has(id)) return;
569
+ this.pending.delete(id);
570
+ cleanup();
571
+ try {
572
+ this._send({ jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId: id, reason: 'aborted' } });
573
+ } catch {}
574
+ rejectPromise(new ToolCallError(toolName, `MCP request "${method}" aborted`));
575
+ };
576
+
577
+ const cleanup = () => {
578
+ clearTimeout(timer);
579
+ if (signal) signal.removeEventListener('abort', onAbort);
580
+ };
581
+
582
+ if (signal) signal.addEventListener('abort', onAbort, { once: true });
583
+
584
+ this.pending.set(id, {
585
+ toolName,
586
+ resolve: resolvePromise,
587
+ reject: rejectPromise,
588
+ cleanup,
589
+ });
590
+
591
+ try {
592
+ const payloadParams = this._withRequestMeta(method, params);
593
+ this._send({ jsonrpc: '2.0', id, method, params: payloadParams });
594
+ } catch (err) {
595
+ this.pending.delete(id);
596
+ cleanup();
597
+ rejectPromise(err);
598
+ }
599
+ });
600
+ }
601
+
602
+ _withRequestMeta(method, params) {
603
+ if (this.era !== 'modern' || method === 'server/discover' || method === 'initialize') {
604
+ return params;
605
+ }
606
+ return {
607
+ ...(params && typeof params === 'object' ? params : {}),
608
+ _meta: this._modernMeta(),
609
+ };
610
+ }
611
+
612
+ async ensureReady(opts) {
613
+ const signal = opts?.signal;
614
+ const timeout = opts?.timeout;
615
+ const toolName = `mcp.${this.alias}`;
616
+ if (this.closed) {
617
+ throw new ToolCallError(toolName, 'MCP client is closed');
618
+ }
619
+ if (signal?.aborted) {
620
+ throw new ToolCallError(toolName, 'aborted');
621
+ }
622
+ if (!this.readyPromise) {
623
+ this.readyPromise = this._negotiate(toolName).catch((err) => {
624
+ const failedChild = this.child;
625
+ if (failedChild) {
626
+ this._resetChild(failedChild);
627
+ this._killTree(failedChild, 'SIGKILL', { forceGroup: true });
628
+ }
629
+ this.era = null;
630
+ this.protocolVersion = null;
631
+ throw err;
632
+ });
633
+ // Prevent unhandled rejection if every waiter aborted before handshake failed
634
+ this.readyPromise.catch(() => {});
635
+ }
636
+ await raceWithAbort(this.readyPromise, toolName, { signal, timeout });
637
+ }
638
+
639
+ // Dual-era negotiation, stdio rules: probe server/discover first (modern),
640
+ // any non-modern error means the server predates per-request _meta, so fall
641
+ // back to the initialize handshake on the same child.
642
+ async _negotiate(toolName) {
643
+ const probeTimeout = Math.min(
644
+ Number.isInteger(this.config.timeout) && this.config.timeout > 0
645
+ ? this.config.timeout
646
+ : DEFAULT_TIMEOUT_MS,
647
+ MODERN_PROBE_TIMEOUT_MS,
648
+ );
649
+ try {
650
+ const res = await this._request(
651
+ toolName,
652
+ 'server/discover',
653
+ { _meta: this._modernMeta(MODERN_PROTOCOL_VERSION) },
654
+ { timeout: probeTimeout },
655
+ );
656
+ this.era = 'modern';
657
+ this.protocolVersion = MODERN_PROTOCOL_VERSION;
658
+ this._absorbDiscover(res);
659
+ return;
660
+ } catch (err) {
661
+ if (this.verbose) {
662
+ process.stderr.write(`[mcp:${this.alias}:negotiate] discover failed (code ${err?.code}): ${err?.message}\n`);
663
+ }
664
+ if (err?.code === -32022 && Array.isArray(err?.data?.supported)) {
665
+ const chosen = err.data.supported.find((v) => isModernVersion(v));
666
+ if (chosen) {
667
+ const res = await this._request(
668
+ toolName,
669
+ 'server/discover',
670
+ { _meta: this._modernMeta(chosen) },
671
+ { timeout: probeTimeout },
672
+ );
673
+ this.era = 'modern';
674
+ this.protocolVersion = chosen;
675
+ this._absorbDiscover(res);
676
+ return;
677
+ }
678
+ } else if (err?.code === -32020 || err?.code === -32021) {
679
+ // A recognized modern error means the server speaks the modern era;
680
+ // let the next real request surface the actionable failure.
681
+ this.era = 'modern';
682
+ this.protocolVersion = MODERN_PROTOCOL_VERSION;
683
+ return;
684
+ }
685
+ }
686
+ await this._initializeLegacy(toolName);
687
+ }
688
+
689
+ _absorbDiscover(res) {
690
+ const info = res?._meta?.['io.modelcontextprotocol/serverInfo'];
691
+ if (info && typeof info === 'object') this.serverInfo = info;
692
+ if (typeof res?.instructions === 'string') this.instructions = res.instructions;
693
+ }
694
+
695
+ async _initializeLegacy(toolName) {
696
+ let lastError;
697
+ for (const version of LEGACY_FALLBACK_VERSIONS) {
698
+ try {
699
+ const res = await this._request(toolName, 'initialize', {
700
+ protocolVersion: version,
701
+ capabilities: {},
702
+ clientInfo: { ...CLIENT_INFO },
703
+ }, { timeout: this.config.timeout ?? DEFAULT_TIMEOUT_MS });
704
+ this.era = 'legacy';
705
+ this.protocolVersion = typeof res?.protocolVersion === 'string' ? res.protocolVersion : version;
706
+ if (res?.serverInfo && typeof res.serverInfo === 'object') this.serverInfo = res.serverInfo;
707
+ if (typeof res?.instructions === 'string') this.instructions = res.instructions;
708
+ this._send({ jsonrpc: '2.0', method: 'notifications/initialized' });
709
+ return;
710
+ } catch (err) {
711
+ lastError = err;
712
+ // Only a deliberate version rejection justifies retrying an older
713
+ // revision; a hang or transport failure must not respawn the child.
714
+ const rejectedVersion = err?.code === -32602 && /protocol/i.test(String(err?.message ?? ''));
715
+ if (!rejectedVersion) break;
716
+ }
717
+ }
718
+ throw lastError ?? new ToolCallError(toolName, 'MCP initialization failed');
719
+ }
720
+
721
+ async listTools(opts) {
722
+ await this.ensureReady(opts);
723
+ const items = [];
724
+ let cursor;
725
+ for (let page = 0; page < MAX_LIST_PAGES; page++) {
726
+ const res = await this._request(
727
+ `mcp.${this.alias}`,
728
+ 'tools/list',
729
+ cursor ? { cursor } : {},
730
+ opts,
731
+ );
732
+ if (Array.isArray(res?.tools)) {
733
+ for (const t of res.tools) {
734
+ if (!t || typeof t.name !== 'string') continue;
735
+ items.push({
736
+ name: `mcp.${this.alias}.${t.name}`,
737
+ rawName: t.name,
738
+ source: `mcp:${this.alias}`,
739
+ description: typeof t.description === 'string' ? t.description.trim().slice(0, 140) : '',
740
+ params: compactInputSchema(t.inputSchema),
741
+ parse: 'mcp',
742
+ });
743
+ }
744
+ }
745
+ if (!res?.nextCursor || res.nextCursor === cursor) break;
746
+ cursor = res.nextCursor;
747
+ }
748
+ return items;
749
+ }
750
+
751
+ async callTool(rawToolName, args = {}, opts) {
752
+ await this.ensureReady(opts);
753
+ const fullName = `mcp.${this.alias}.${rawToolName}`;
754
+ const res = await this._request(fullName, 'tools/call', {
755
+ name: rawToolName,
756
+ arguments: args && typeof args === 'object' ? args : {},
757
+ }, opts);
758
+ return unwrapMcpResult(fullName, res);
759
+ }
760
+
761
+ close() {
762
+ if (this.closePromise) return this.closePromise;
763
+ this.closed = true;
764
+ this._failAll(new ToolCallError(`mcp.${this.alias}`, 'MCP client closed'));
765
+ const child = this.child;
766
+ this.child = null;
767
+ this.readyPromise = null;
768
+ this.buffer = '';
769
+
770
+ if (!child || child.exitCode !== null || child.signalCode !== null) {
771
+ this.closePromise = Promise.resolve();
772
+ return this.closePromise;
773
+ }
774
+
775
+ this.closePromise = new Promise((resolveClose) => {
776
+ let settled = false;
777
+ const done = () => {
778
+ if (settled) return;
779
+ settled = true;
780
+ child.off('close', done);
781
+ child.off('error', done);
782
+ clearTimeout(termTimer);
783
+ clearTimeout(killTimer);
784
+ resolveClose();
785
+ };
786
+ child.once('close', done);
787
+ child.once('error', done);
788
+ try {
789
+ child.stdin?.end();
790
+ } catch {}
791
+ const termTimer = setTimeout(() => {
792
+ this._killTree(child, 'SIGTERM', { forceGroup: true });
793
+ }, 200);
794
+ termTimer.unref?.();
795
+ const killTimer = setTimeout(() => {
796
+ this._killTree(child, 'SIGKILL', { forceGroup: true });
797
+ done();
798
+ }, 700);
799
+ killTimer.unref?.();
800
+ });
801
+ return this.closePromise;
802
+ }
803
+ }
804
+
805
+ export function createMcpBridge(servers = {}, opts) {
806
+ const clients = new Map();
807
+ const configs = Object.create(null);
808
+ for (const [alias, cfg] of Object.entries(servers)) {
809
+ validateMcpAlias(alias);
810
+ configs[alias] = cfg;
811
+ }
812
+
813
+ function getClient(alias) {
814
+ if (!Object.prototype.hasOwnProperty.call(configs, alias)) {
815
+ throw new ToolCallError(`mcp.${alias}`, `unknown MCP server: ${alias}`);
816
+ }
817
+ if (!clients.has(alias)) {
818
+ clients.set(alias, new McpStdioClient(alias, configs[alias], opts));
819
+ }
820
+ return clients.get(alias);
821
+ }
822
+
823
+ const serverProxies = Object.create(null);
824
+ for (const alias of Object.keys(configs)) {
825
+ const base = Object.create(null);
826
+ base.list = (callOpts) => getClient(alias).listTools(callOpts);
827
+ base.call = (toolName, args = {}, callOpts) => getClient(alias).callTool(toolName, args, callOpts);
828
+ base.close = () => (clients.has(alias) ? clients.get(alias).close() : Promise.resolve());
829
+
830
+ serverProxies[alias] = new Proxy(Object.freeze(base), {
831
+ get(target, prop) {
832
+ if (typeof prop !== 'string') return undefined;
833
+ if (Object.prototype.hasOwnProperty.call(target, prop)) return target[prop];
834
+ if (IGNORED_PROXY_PROPS.has(prop)) return undefined;
835
+ return (args = {}, callOpts) => getClient(alias).callTool(prop, args, callOpts);
836
+ },
837
+ });
838
+ }
839
+
840
+ const namespace = Object.freeze(serverProxies);
841
+
842
+ async function listAll(filter) {
843
+ const needle = filter ? String(filter).toLowerCase() : null;
844
+ const allAliases = Object.keys(configs);
845
+ const matchingPrefix = needle
846
+ ? allAliases.filter((alias) => {
847
+ const a = alias.toLowerCase();
848
+ return a === needle
849
+ || needle === `mcp.${a}`
850
+ || needle.startsWith(`${a}.`)
851
+ || needle.startsWith(`mcp.${a}.`);
852
+ })
853
+ : allAliases;
854
+ const aliasesToQuery = matchingPrefix.length > 0 ? matchingPrefix : allAliases;
855
+
856
+ const settled = await Promise.allSettled(
857
+ aliasesToQuery.map((alias) => getClient(alias).listTools()),
858
+ );
859
+ const results = [];
860
+ for (let i = 0; i < settled.length; i++) {
861
+ const outcome = settled[i];
862
+ if (outcome.status === 'rejected') {
863
+ process.stderr.write(`[codemode] mcp:${aliasesToQuery[i]} list-tools failed: ${outcome.reason?.message || outcome.reason}\n`);
864
+ continue;
865
+ }
866
+ for (const item of outcome.value) {
867
+ if (
868
+ !needle
869
+ || item.name.toLowerCase().includes(needle)
870
+ || item.description.toLowerCase().includes(needle)
871
+ || item.source.toLowerCase().includes(needle)
872
+ ) {
873
+ results.push(item);
874
+ }
875
+ }
876
+ }
877
+ return results;
878
+ }
879
+
880
+ async function closeAll() {
881
+ await Promise.all([...clients.values()].map((c) => c.close()));
882
+ }
883
+
884
+ return {
885
+ aliases: Object.keys(configs),
886
+ namespace,
887
+ getClient,
888
+ listAll,
889
+ closeAll,
890
+ };
891
+ }