@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,607 @@
1
+ // MCP stdio front-end (dual-era: modern per-request _meta + legacy initialize).
2
+ // Exposes run_code / read_spill (and list_tools only when the embedded catalog
3
+ // does not fit) so a host can batch many tool calls in a single turn.
4
+ // stdout is the JSON-RPC transport: it is captured raw at import time and every
5
+ // diagnostic goes to stderr. This is a runner, not a sandbox.
6
+ import { createInterface } from 'node:readline';
7
+ import { boundOutput, createSpillHelper, executeProgram, parseMaxChars, readSpillPage, safeJsonStringify } from './executor.mjs';
8
+ import { mergeSignals } from './core.mjs';
9
+ import { ToolCallError } from './tools.mjs';
10
+
11
+ const MODERN_VERSION = '2026-07-28';
12
+ const LEGACY_VERSIONS = ['2025-11-25', '2024-11-05'];
13
+ const SUPPORTED_VERSIONS = [MODERN_VERSION, ...LEGACY_VERSIONS];
14
+ const CATALOG_LIMIT_CHARS = 6000;
15
+ const CATALOG_TIMEOUT_MS = 5000;
16
+ const FAILURE_BACKOFF_MS = 10000;
17
+ export const DEFAULT_RUN_TIMEOUT_MS = 120000;
18
+ const MAX_RUN_TIMEOUT_MS = 600000;
19
+ const MAX_LINE_CHARS = 16 * 1024 * 1024;
20
+
21
+ const SERVER_NAME = 'mcp-code-mode';
22
+ const SERVER_INSTRUCTIONS = [
23
+ 'Code-mode runner: call run_code with { code, args? } to execute JavaScript in a local Node process',
24
+ '(not a sandbox). Inside the program use tools.<ns>.<tool>(input, opts), args, mapBounded(items, n, fn),',
25
+ 'execTool, execJson, listTools(filter) and callTool(name, args). Return a value and log with console.log;',
26
+ 'the envelope carries result, logs and, when too large, spill.path. Use read_spill only to page spilled text.',
27
+ ].join(' ');
28
+
29
+ const rawStdoutWrite = process.stdout.write.bind(process.stdout);
30
+ const rawExit = process.exit.bind(process);
31
+
32
+ function clip(text, max) {
33
+ const str = String(text);
34
+ return str.length <= max ? str : `${str.slice(0, max - 1)}…`;
35
+ }
36
+
37
+ export function makeAllowMatcher(allowTools) {
38
+ if (allowTools === null || allowTools === undefined) return () => true;
39
+ const entries = Array.isArray(allowTools) ? allowTools.map((e) => String(e).trim()).filter(Boolean) : [];
40
+ // An explicit but empty allow-list means "allow nothing", never "allow all".
41
+ // Only an absent flag (null/undefined) keeps the filter disabled.
42
+ if (entries.length === 0) return () => false;
43
+ const exact = new Set();
44
+ const prefixes = [];
45
+ for (const entry of entries) {
46
+ if (entry.endsWith('*')) prefixes.push(entry.slice(0, -1));
47
+ else exact.add(entry);
48
+ }
49
+ return (name) => exact.has(name) || prefixes.some((prefix) => name.startsWith(prefix));
50
+ }
51
+
52
+ export function createScopedTools(registry, { signal, isAllowed = () => true } = {}) {
53
+ const denied = (name) => new ToolCallError(name, `tool not allowed by --allow-tools: ${name}`);
54
+ const bind = (name, fn) => (input = {}, opts) => {
55
+ if (!isAllowed(name)) throw denied(name);
56
+ return fn(input, { ...(opts ?? {}), signal: mergeSignals(signal, opts?.signal) });
57
+ };
58
+ // Wrap over a fresh, extensible target: the real registry is frozen, and a
59
+ // Proxy over non-configurable properties must return the exact same value.
60
+ const walk = (source, prefix) => {
61
+ const target = Object.create(null);
62
+ return new Proxy(target, {
63
+ get(_target, prop) {
64
+ if (typeof prop !== 'string') return undefined;
65
+ if (prop === 'then' || prop === 'toJSON' || prop === '$$typeof') return undefined;
66
+ const value = source[prop];
67
+ const name = prefix ? `${prefix}.${prop}` : prop;
68
+ if (typeof value === 'function') {
69
+ if (prop === 'describe') return value;
70
+ if (prop === 'call') {
71
+ return (toolName, input, opts) => {
72
+ const tool = String(toolName);
73
+ if (!isAllowed(tool)) throw denied(tool);
74
+ return value(tool, input, { ...(opts ?? {}), signal: mergeSignals(signal, opts?.signal) });
75
+ };
76
+ }
77
+ return bind(name, value);
78
+ }
79
+ if (value && typeof value === 'object') return walk(value, name);
80
+ return value;
81
+ },
82
+ has(_target, prop) {
83
+ return typeof prop === 'string' && source[prop] !== undefined;
84
+ },
85
+ ownKeys() {
86
+ return Reflect.ownKeys(source).filter((key) => typeof key === 'string');
87
+ },
88
+ getOwnPropertyDescriptor() {
89
+ return { enumerable: true, configurable: true };
90
+ },
91
+ });
92
+ };
93
+ return walk(registry, '');
94
+ }
95
+
96
+ function schemaRunCode() {
97
+ return {
98
+ type: 'object',
99
+ properties: {
100
+ code: {
101
+ type: 'string',
102
+ description: 'JavaScript body. May return a value; `return` works at top level.',
103
+ },
104
+ args: { type: 'object', description: 'Value exposed as `args` inside the program.' },
105
+ timeoutMs: { type: 'integer', minimum: 1, description: 'Hard timeout for this execution.' },
106
+ },
107
+ required: ['code'],
108
+ additionalProperties: false,
109
+ };
110
+ }
111
+
112
+ function schemaReadSpill() {
113
+ return {
114
+ type: 'object',
115
+ properties: {
116
+ name: { type: 'string', description: 'File name or path inside CODEMODE_OUT_DIR.' },
117
+ path: { type: 'string', description: 'Absolute path inside CODEMODE_OUT_DIR (from envelope spill.path).' },
118
+ offset: { type: 'integer', minimum: 0, description: 'Character offset to start reading from.' },
119
+ maxChars: { type: 'integer', minimum: 1, description: 'Maximum characters to return (default 20000).' },
120
+ },
121
+ additionalProperties: false,
122
+ };
123
+ }
124
+
125
+ function schemaListTools() {
126
+ return {
127
+ type: 'object',
128
+ properties: { filter: { type: 'string', description: 'Case-insensitive substring filter.' } },
129
+ additionalProperties: false,
130
+ };
131
+ }
132
+
133
+ export async function runMcpServer({
134
+ version,
135
+ registry,
136
+ mcpBridge = null,
137
+ outDir = '.agent/out',
138
+ allowTools = null,
139
+ timeoutMs = DEFAULT_RUN_TIMEOUT_MS,
140
+ }) {
141
+ // stdout is the JSON-RPC transport. A finished or aborted program can still
142
+ // fire timers or floating promises, and those writes must never reach the
143
+ // transport. Divert process.stdout.write to stderr for the whole server
144
+ // lifetime; during a run the executor replaces the same property to capture
145
+ // into that run's logs and restores this diverter afterwards. The transport
146
+ // itself uses the raw writer captured at import time, so it is unaffected.
147
+ const stderrWrite = process.stderr.write.bind(process.stderr);
148
+ process.stdout.write = (chunk, encoding, callback) => {
149
+ if (typeof encoding === 'function') {
150
+ stderrWrite(chunk, encoding);
151
+ } else if (encoding !== undefined) {
152
+ stderrWrite(chunk, encoding, callback);
153
+ } else {
154
+ stderrWrite(chunk, callback);
155
+ }
156
+ return true;
157
+ };
158
+
159
+ const isAllowed = makeAllowMatcher(allowTools);
160
+ const spill = createSpillHelper(outDir);
161
+ const aliasTools = new Map();
162
+ const aliasFailures = new Map();
163
+ const inflight = new Map();
164
+ // Readline can emit several buffered lines in one tick, so a
165
+ // notifications/cancelled can arrive before the request it targets has
166
+ // registered its controller. Remember those ids and honour them on start.
167
+ const cancelledEarly = new Set();
168
+ let catalogInFlight = null;
169
+ let legacyInitialized = false;
170
+ let shuttingDown = false;
171
+ let queueTail = Promise.resolve();
172
+ let writeChain = Promise.resolve();
173
+ let readline = null;
174
+
175
+ function send(payload) {
176
+ if (shuttingDown) return writeChain;
177
+ const line = `${JSON.stringify(payload)}\n`;
178
+ writeChain = writeChain
179
+ .then(() => new Promise((resolveWrite) => {
180
+ rawStdoutWrite(line, () => resolveWrite());
181
+ }))
182
+ .catch(() => {});
183
+ return writeChain;
184
+ }
185
+
186
+ const ok = (id, result) => send({ jsonrpc: '2.0', id, result });
187
+ const fail = (id, code, message, data) => send({
188
+ jsonrpc: '2.0',
189
+ id,
190
+ error: { code, message, ...(data !== undefined ? { data } : {}) },
191
+ });
192
+ const toolText = (id, text, isError = false) => ok(id, {
193
+ resultType: 'complete',
194
+ content: [{ type: 'text', text }],
195
+ ...(isError ? { isError: true } : {}),
196
+ });
197
+ const toolError = (id, message) => toolText(id, message, true);
198
+
199
+ // executeProgram always keeps the full envelope on disk, but its `text` can be
200
+ // far larger than maxChars. Never hand that verbatim to the host: return a
201
+ // small, valid-JSON envelope that points at the spill file instead.
202
+ function boundRunText(outcome) {
203
+ if (outcome.text.length <= outcome.maxChars) return outcome.text;
204
+ if (!outcome.spillPath) return boundOutput(outcome.text, outcome.maxChars).text;
205
+
206
+ const { envelope } = outcome;
207
+ const core = {
208
+ ok: outcome.ok,
209
+ ...(outcome.ok ? {} : { error: envelope.error }),
210
+ truncated: true,
211
+ totalChars: outcome.text.length,
212
+ spill: { path: outcome.spillPath },
213
+ };
214
+ const full = {
215
+ version: envelope.version,
216
+ program: envelope.program,
217
+ startedAt: envelope.startedAt,
218
+ finishedAt: envelope.finishedAt,
219
+ logs: envelope.logs,
220
+ hint: 'Output exceeded CODEMODE_MAX_OUTPUT_CHARS; page spill.path with read_spill.',
221
+ ...core,
222
+ };
223
+ for (const candidate of [full, core]) {
224
+ const text = safeJsonStringify(candidate);
225
+ if (text.length <= outcome.maxChars) return text;
226
+ }
227
+ return boundOutput(safeJsonStringify(core), outcome.maxChars).text;
228
+ }
229
+
230
+ function parseModernMeta(params) {
231
+ const meta = params && typeof params === 'object' ? params._meta : undefined;
232
+ if (!meta || typeof meta !== 'object') return null;
233
+ const protocolVersion = meta['io.modelcontextprotocol/protocolVersion'];
234
+ const clientCapabilities = meta['io.modelcontextprotocol/clientCapabilities'];
235
+ if (typeof protocolVersion !== 'string') return null;
236
+ if (!clientCapabilities || typeof clientCapabilities !== 'object') return null;
237
+ const clientInfo = meta['io.modelcontextprotocol/clientInfo'];
238
+ return {
239
+ protocolVersion,
240
+ clientInfo: clientInfo && typeof clientInfo === 'object' ? clientInfo : undefined,
241
+ };
242
+ }
243
+
244
+ // Returns null when the request is acceptable, or an error tuple.
245
+ // Deliberately synchronous: tools/call must reach its AbortController
246
+ // registration before the event loop can deliver a cancellation for it.
247
+ function rejectEra(id, params) {
248
+ const hasMeta = params && typeof params === 'object' && params._meta !== undefined;
249
+ if (hasMeta) {
250
+ const meta = parseModernMeta(params);
251
+ if (!meta) {
252
+ fail(id, -32602, 'Invalid params: _meta requires io.modelcontextprotocol/protocolVersion and io.modelcontextprotocol/clientCapabilities');
253
+ return true;
254
+ }
255
+ if (meta.protocolVersion !== MODERN_VERSION) {
256
+ fail(id, -32022, 'Unsupported protocol version', {
257
+ supported: [MODERN_VERSION],
258
+ requested: meta.protocolVersion,
259
+ });
260
+ return true;
261
+ }
262
+ return false;
263
+ }
264
+ if (legacyInitialized) return false;
265
+ fail(id, -32602, 'Invalid params: missing _meta (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities) or a prior initialize handshake');
266
+ return true;
267
+ }
268
+
269
+ function discoverResult() {
270
+ return {
271
+ resultType: 'complete',
272
+ supportedVersions: SUPPORTED_VERSIONS,
273
+ capabilities: { tools: {} },
274
+ _meta: {
275
+ 'io.modelcontextprotocol/serverInfo': { name: SERVER_NAME, version },
276
+ },
277
+ instructions: SERVER_INSTRUCTIONS,
278
+ ttlMs: 3600000,
279
+ cacheScope: 'public',
280
+ };
281
+ }
282
+
283
+ function initializeResult(params) {
284
+ const requested = params?.protocolVersion;
285
+ return {
286
+ resultType: 'complete',
287
+ protocolVersion: LEGACY_VERSIONS.includes(requested) ? requested : LEGACY_VERSIONS[0],
288
+ capabilities: { tools: {} },
289
+ serverInfo: { name: SERVER_NAME, version },
290
+ instructions: SERVER_INSTRUCTIONS,
291
+ };
292
+ }
293
+
294
+ async function refreshCatalog() {
295
+ const aliases = mcpBridge ? mcpBridge.aliases : [];
296
+ const now = Date.now();
297
+ const pending = [];
298
+ for (const alias of aliases) {
299
+ const failedAt = aliasFailures.get(alias);
300
+ if (failedAt !== undefined && now - failedAt < FAILURE_BACKOFF_MS) continue;
301
+ pending.push((async () => {
302
+ try {
303
+ const tools = await mcpBridge.getClient(alias).listTools({ timeout: CATALOG_TIMEOUT_MS });
304
+ aliasTools.set(alias, tools);
305
+ aliasFailures.delete(alias);
306
+ } catch {
307
+ aliasFailures.set(alias, Date.now());
308
+ }
309
+ })());
310
+ }
311
+ if (pending.length > 0) await Promise.allSettled(pending);
312
+ }
313
+
314
+ async function ensureCatalog() {
315
+ if (catalogInFlight) return catalogInFlight;
316
+ catalogInFlight = (async () => {
317
+ await refreshCatalog();
318
+ const staticEntries = typeof registry.describe === 'function' ? registry.describe() : [];
319
+ const upstreamEntries = [];
320
+ for (const alias of mcpBridge ? mcpBridge.aliases : []) {
321
+ const tools = aliasTools.get(alias);
322
+ if (Array.isArray(tools)) upstreamEntries.push(...tools);
323
+ }
324
+ return [...staticEntries, ...upstreamEntries].filter((entry) => isAllowed(entry.name));
325
+ })();
326
+ try {
327
+ return await catalogInFlight;
328
+ } finally {
329
+ catalogInFlight = null;
330
+ }
331
+ }
332
+
333
+ function formatParams(params) {
334
+ if (!params || typeof params !== 'object') return '';
335
+ return Object.entries(params).map(([key, label]) => `${key}: ${label}`).join(', ');
336
+ }
337
+
338
+ function catalogText(entries) {
339
+ return entries
340
+ .map((entry) => {
341
+ const params = formatParams(entry.params);
342
+ const description = entry.description ? ` — ${clip(entry.description, 110)}` : '';
343
+ return `- ${entry.name}(${params})${description}`;
344
+ })
345
+ .join('\n');
346
+ }
347
+
348
+ async function wireTools() {
349
+ const entries = await ensureCatalog();
350
+ const catalog = catalogText(entries);
351
+ const base = [
352
+ 'Run a JavaScript program in a local Node process (NOT a sandbox) and get one bounded envelope back.',
353
+ 'Inside: tools.<ns>.<tool>(input, opts), args, mapBounded(items, limit, fn), execTool, execJson, spill.read(), listTools(filter), callTool(name, args, opts).',
354
+ 'Return a value; console.log is captured; oversized output spills to disk (page it with read_spill).',
355
+ ].join('\n');
356
+ const notice = '\n… catalog truncated; call list_tools for the full list.';
357
+ const header = '\nTool catalog (hint, not a limit — listTools()/callTool() work for anything reachable):\n';
358
+ const partialHeader = '\nTool catalog (partial — call list_tools for the rest):\n';
359
+ const unavailable = (mcpBridge ? mcpBridge.aliases : [])
360
+ .filter((alias) => !aliasTools.has(alias) && aliasFailures.has(alias));
361
+ const failureNote = unavailable.length > 0
362
+ ? `\nUnavailable upstreams: ${unavailable.join(', ')} (retried with backoff).`
363
+ : '';
364
+ const available = CATALOG_LIMIT_CHARS - base.length - failureNote.length;
365
+ const embedded = entries.length === 0 || catalog.length + header.length <= available;
366
+ let tail;
367
+ if (entries.length === 0) {
368
+ tail = '\nNo tools beyond run_code are exposed; use args/execTool or ask the host to add --mcp upstreams.';
369
+ } else if (embedded) {
370
+ tail = header + catalog;
371
+ } else {
372
+ const budget = Math.max(0, available - partialHeader.length - notice.length);
373
+ tail = `${partialHeader}${clip(catalog, budget)}${notice}`;
374
+ }
375
+ const runCodeDescription = base + tail + failureNote;
376
+
377
+ const tools = [
378
+ {
379
+ name: 'run_code',
380
+ title: 'Run a code-mode program',
381
+ description: runCodeDescription,
382
+ inputSchema: schemaRunCode(),
383
+ },
384
+ {
385
+ name: 'read_spill',
386
+ title: 'Page spilled output',
387
+ description: 'Read a spilled envelope in chunks. Last resort: prefer returning summaries from run_code. Returns { text, totalChars, offset, truncated, nextOffset }; nextOffset is null at the end.',
388
+ inputSchema: schemaReadSpill(),
389
+ },
390
+ ];
391
+ if (!embedded) {
392
+ tools.push({
393
+ name: 'list_tools',
394
+ title: 'List callable tools',
395
+ description: 'List callable tools with compact parameter hints. The catalog was too large to embed in run_code, so use this once.',
396
+ inputSchema: schemaListTools(),
397
+ });
398
+ }
399
+ return tools;
400
+ }
401
+
402
+ function enqueueRun(task) {
403
+ const run = queueTail.then(task);
404
+ queueTail = run.then(() => {}, () => {});
405
+ return run;
406
+ }
407
+
408
+ function clampTimeout(value) {
409
+ const max = Number.isInteger(timeoutMs) && timeoutMs > 0 ? Math.min(timeoutMs, MAX_RUN_TIMEOUT_MS) : DEFAULT_RUN_TIMEOUT_MS;
410
+ const n = Number(value);
411
+ if (!Number.isInteger(n) || n <= 0) return max;
412
+ return Math.min(n, MAX_RUN_TIMEOUT_MS);
413
+ }
414
+
415
+ async function handleRunCode(id, args) {
416
+ const code = typeof args?.code === 'string' ? args.code : '';
417
+ if (code.trim().length === 0) {
418
+ return toolError(id, 'run_code requires a non-empty "code" string');
419
+ }
420
+ const controller = new AbortController();
421
+ inflight.set(id, controller);
422
+ if (cancelledEarly.delete(id)) {
423
+ controller.abort(new Error('run_code cancelled by client'));
424
+ }
425
+ try {
426
+ const outcome = await enqueueRun(async () => {
427
+ if (controller.signal.aborted) {
428
+ throw new Error('run_code was cancelled before it started');
429
+ }
430
+ const runTimeoutMs = clampTimeout(args?.timeoutMs);
431
+ // Abort the same controller the scoped tools and callTool receive, so a
432
+ // hard timeout also cancels in-flight upstream MCP requests instead of
433
+ // leaving them running with no notifications/cancelled.
434
+ const timeoutTimer = setTimeout(() => {
435
+ controller.abort(new Error(`run_code timed out after ${runTimeoutMs}ms`));
436
+ }, runTimeoutMs);
437
+ timeoutTimer.unref?.();
438
+ try {
439
+ const scopeTools = createScopedTools(registry, { signal: controller.signal, isAllowed });
440
+ return await executeProgram({
441
+ mode: 'code',
442
+ source: code,
443
+ args: args?.args && typeof args.args === 'object' ? args.args : {},
444
+ registry: scopeTools,
445
+ spill,
446
+ outDir,
447
+ label: 'run_code',
448
+ spillStem: 'run_code',
449
+ version,
450
+ maxChars: parseMaxChars(),
451
+ timeoutMs: runTimeoutMs,
452
+ signal: controller.signal,
453
+ isolateProcess: true,
454
+ listTools: async (filter) => {
455
+ const entries = await ensureCatalog();
456
+ const needle = filter ? String(filter).toLowerCase() : null;
457
+ return entries
458
+ .filter((entry) => !needle
459
+ || entry.name.toLowerCase().includes(needle)
460
+ || String(entry.description ?? '').toLowerCase().includes(needle))
461
+ .map((entry) => ({ name: entry.name, description: entry.description, params: entry.params }));
462
+ },
463
+ callTool: async (name, input, opts) => {
464
+ if (!isAllowed(String(name))) {
465
+ throw new ToolCallError(String(name), `tool not allowed by --allow-tools: ${name}`);
466
+ }
467
+ return registry.call(String(name), input ?? {}, {
468
+ ...(opts ?? {}),
469
+ signal: mergeSignals(controller.signal, opts?.signal),
470
+ });
471
+ },
472
+ });
473
+ } finally {
474
+ clearTimeout(timeoutTimer);
475
+ }
476
+ });
477
+ return toolText(id, boundRunText(outcome), !outcome.ok);
478
+ } catch (e) {
479
+ return toolError(id, e instanceof Error ? e.message : String(e));
480
+ } finally {
481
+ inflight.delete(id);
482
+ }
483
+ }
484
+
485
+ async function handleReadSpill(id, args) {
486
+ try {
487
+ const page = readSpillPage(outDir, {
488
+ name: typeof args?.name === 'string' ? args.name : undefined,
489
+ path: typeof args?.path === 'string' ? args.path : undefined,
490
+ offset: args?.offset,
491
+ maxChars: args?.maxChars,
492
+ });
493
+ return toolText(id, JSON.stringify(page));
494
+ } catch (e) {
495
+ return toolError(id, e instanceof Error ? e.message : String(e));
496
+ }
497
+ }
498
+
499
+ async function handleToolCall(id, params) {
500
+ const name = params?.name;
501
+ const args = params?.arguments && typeof params.arguments === 'object' ? params.arguments : {};
502
+ if (typeof name !== 'string' || name.length === 0) {
503
+ return fail(id, -32602, 'Invalid params: tools/call requires a tool name');
504
+ }
505
+ if (name === 'run_code') return handleRunCode(id, args);
506
+ if (name === 'read_spill') return handleReadSpill(id, args);
507
+ if (name === 'list_tools') {
508
+ const entries = await ensureCatalog();
509
+ const needle = args?.filter ? String(args.filter).toLowerCase() : null;
510
+ const filtered = needle
511
+ ? entries.filter((entry) => entry.name.toLowerCase().includes(needle)
512
+ || String(entry.description ?? '').toLowerCase().includes(needle))
513
+ : entries;
514
+ return toolText(id, JSON.stringify({ tools: filtered }));
515
+ }
516
+ return fail(id, -32602, `Unknown tool: ${name}`);
517
+ }
518
+
519
+ function cancelRequest(requestId) {
520
+ const controller = inflight.get(requestId);
521
+ if (controller) {
522
+ controller.abort(new Error('run_code cancelled by client'));
523
+ return;
524
+ }
525
+ if (cancelledEarly.size >= 256) {
526
+ cancelledEarly.delete(cancelledEarly.values().next().value);
527
+ }
528
+ cancelledEarly.add(requestId);
529
+ }
530
+
531
+ async function dispatch(line) {
532
+ if (line.length > MAX_LINE_CHARS) {
533
+ return fail(null, -32600, 'Request too large');
534
+ }
535
+ let msg;
536
+ try {
537
+ msg = JSON.parse(line);
538
+ } catch {
539
+ return fail(null, -32700, 'Parse error');
540
+ }
541
+ if (!msg || typeof msg !== 'object' || Array.isArray(msg) || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
542
+ return fail(msg?.id ?? null, -32600, 'Invalid Request');
543
+ }
544
+
545
+ const id = msg.id;
546
+ const isRequest = id !== undefined && id !== null;
547
+ const params = msg.params && typeof msg.params === 'object' ? msg.params : {};
548
+
549
+ if (!isRequest) {
550
+ if (msg.method === 'notifications/cancelled') cancelRequest(params.requestId);
551
+ return undefined;
552
+ }
553
+
554
+ try {
555
+ switch (msg.method) {
556
+ case 'initialize':
557
+ legacyInitialized = true;
558
+ return ok(id, initializeResult(params));
559
+ case 'ping':
560
+ if (rejectEra(id, params)) return undefined;
561
+ return ok(id, { resultType: 'complete' });
562
+ case 'server/discover': {
563
+ if (rejectEra(id, params)) return undefined;
564
+ return ok(id, discoverResult());
565
+ }
566
+ case 'tools/list':
567
+ if (rejectEra(id, params)) return undefined;
568
+ return ok(id, { resultType: 'complete', tools: await wireTools() });
569
+ case 'tools/call':
570
+ if (rejectEra(id, params)) return undefined;
571
+ return handleToolCall(id, params);
572
+ default:
573
+ return fail(id, -32601, `Method not found: ${msg.method}`);
574
+ }
575
+ } catch (e) {
576
+ return fail(id, -32603, `Internal error: ${e instanceof Error ? e.message : String(e)}`);
577
+ }
578
+ }
579
+
580
+ readline = createInterface({ input: process.stdin, crlfDelay: Infinity });
581
+ readline.on('line', (line) => {
582
+ const trimmed = line.trim();
583
+ if (!trimmed) return;
584
+ dispatch(trimmed).catch((e) => {
585
+ process.stderr.write(`[codemode] mcp-dispatch-failed: ${e instanceof Error ? e.message : String(e)}\n`);
586
+ });
587
+ });
588
+
589
+ async function shutdown(code = 0) {
590
+ if (shuttingDown) return;
591
+ shuttingDown = true;
592
+ try { readline?.close(); } catch {}
593
+ for (const controller of inflight.values()) {
594
+ try { controller.abort(new Error('server shutting down')); } catch {}
595
+ }
596
+ try { await mcpBridge?.closeAll(); } catch {}
597
+ process.exitCode = code;
598
+ rawExit(code);
599
+ }
600
+
601
+ readline.on('close', () => { void shutdown(0); });
602
+ process.on('SIGINT', () => { void shutdown(0); });
603
+ process.on('SIGTERM', () => { void shutdown(0); });
604
+ process.on('beforeExit', () => { if (!shuttingDown) void shutdown(0); });
605
+
606
+ await new Promise(() => {});
607
+ }
@@ -0,0 +1,32 @@
1
+ // Optional third-party Engram CLI read-only plugin. Keep writes on MCP mem_save.
2
+ import { assertPositiveInt, execTool, ToolCallError } from '../core.mjs';
3
+
4
+ export const engram = {
5
+ async search({ query, project, limit = 10, all = false } = {}, opts) {
6
+ const signal = opts?.signal;
7
+ if (typeof query !== 'string' || query.trim().length === 0) {
8
+ throw new ToolCallError('engram.search', 'query must be a non-empty string');
9
+ }
10
+ const validLimit = assertPositiveInt('engram.search', 'limit', limit);
11
+ const args = ['search', '--limit', String(validLimit)];
12
+ if (all) args.push('--all');
13
+ else if (project !== undefined && project !== null && project !== '') {
14
+ if (typeof project !== 'string' || project.startsWith('-')) {
15
+ throw new ToolCallError('engram.search', 'project must be a non-flag string');
16
+ }
17
+ args.push('--project', project);
18
+ }
19
+ args.push('--', query);
20
+ return (await execTool('engram.search', 'engram', args, { signal })).trim();
21
+ },
22
+ };
23
+
24
+ export const engramCatalog = [
25
+ {
26
+ name: 'engram.search',
27
+ source: 'plugin:engram',
28
+ description: 'Read-only search against optional Engram memory CLI',
29
+ params: { query: 'string (required)', project: 'non-flag string (optional)', limit: 'positive int', all: 'boolean' },
30
+ parse: 'text',
31
+ },
32
+ ];