@aisac/cli 0.4.0-beta.21 → 0.4.0-beta.22

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,463 @@
1
+ // The stdio subset of the Model Context Protocol that the manager server needs
2
+ // (spec aisac-engineering-manager D9, FR6, Q8): newline-delimited JSON-RPC 2.0
3
+ // framed the way the official SDK's stdio transport frames it, `initialize`,
4
+ // `ping`, `tools/list`, `tools/call` and cancellation. Written here so that the
5
+ // published client keeps one runtime dependency; tested against the SDK's
6
+ // client as the peer.
7
+
8
+ /**
9
+ * @typedef {object} ToolResult
10
+ * @property {{ type: 'text', text: string }[]} content
11
+ * @property {Record<string, unknown>} [structuredContent]
12
+ * @property {boolean} [isError]
13
+ */
14
+ /**
15
+ * @typedef {object} ToolDefinition
16
+ * @property {string} name
17
+ * @property {string} description
18
+ * @property {Record<string, unknown>} inputSchema JSON Schema (type: 'object')
19
+ * @property {Record<string, unknown>} [annotations] e.g. { readOnlyHint: true }
20
+ * @property {(args: Record<string, unknown>, extra: { signal: AbortSignal }) => Promise<ToolResult>} handler
21
+ */
22
+ /**
23
+ * @typedef {object} ServeOptions
24
+ * @property {{ name: string, version: string }} serverInfo
25
+ * @property {string} [instructions]
26
+ * @property {ToolDefinition[]} tools
27
+ * @property {import('node:stream').Readable} input
28
+ * @property {import('node:stream').Writable} output
29
+ */
30
+ /** @typedef {string | number} RequestId */
31
+
32
+ /** Newest first: the list of `@modelcontextprotocol/sdk` 1.32.1 (`types.js`). */
33
+ export const SUPPORTED_PROTOCOL_VERSIONS = Object.freeze([
34
+ '2025-11-25',
35
+ '2025-06-18',
36
+ '2025-03-26',
37
+ '2024-11-05',
38
+ '2024-10-07',
39
+ ]);
40
+
41
+ const JSONRPC_VERSION = '2.0';
42
+ const NEWLINE_BYTE = 0x0a;
43
+ /** A longer line is dropped while it streams in, never buffered whole. */
44
+ const MAX_LINE_BYTES = 1024 * 1024;
45
+ /** The bytes kept from each end of a dropped line to look for its request id. */
46
+ const ID_WINDOW_BYTES = 256;
47
+ const MAX_CONCURRENT_CALLS = 32;
48
+ const ERROR_CODES = Object.freeze({
49
+ parse: -32700,
50
+ invalidRequest: -32600,
51
+ methodNotFound: -32601,
52
+ invalidParams: -32602,
53
+ // The SDK's Streamable HTTP transport answers a request before `initialize`
54
+ // with -32000; the stdio subset mirrors that code.
55
+ server: -32000,
56
+ });
57
+ const INTERNAL_ERROR_RESULT = Object.freeze({
58
+ content: Object.freeze([Object.freeze({ type: 'text', text: 'internal_error' })]),
59
+ isError: true,
60
+ });
61
+ // An id the SDK's client writes last (`{...request, jsonrpc, id}`) or a client
62
+ // writes first. Both patterns only match an id of the top-level object of a
63
+ // well-formed line: the quotes they rely on cannot be escaped ones.
64
+ const ID_VALUE = String.raw`(-?\d{1,16}|"(?:[^"\\]|\\.){0,128}")`;
65
+ const LEADING_ID_PATTERN = new RegExp(
66
+ String.raw`^\s*\{\s*(?:"jsonrpc"\s*:\s*"2\.0"\s*,\s*)?"id"\s*:\s*${ID_VALUE}\s*,`,
67
+ 'u',
68
+ );
69
+ const TRAILING_ID_PATTERN = new RegExp(String.raw`,\s*"id"\s*:\s*${ID_VALUE}\s*\}\s*$`, 'u');
70
+
71
+ /**
72
+ * @param {unknown} value
73
+ * @returns {value is Record<string, unknown>}
74
+ */
75
+ function isPlainObject(value) {
76
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
77
+ }
78
+
79
+ /**
80
+ * @param {unknown} value
81
+ * @returns {value is RequestId}
82
+ */
83
+ function isRequestId(value) {
84
+ return typeof value === 'string' || Number.isInteger(value);
85
+ }
86
+
87
+ /**
88
+ * A message without a method that carries a result or an error.
89
+ * @param {Record<string, unknown>} message
90
+ */
91
+ function isResponse(message) {
92
+ return (
93
+ !Object.hasOwn(message, 'method') &&
94
+ (Object.hasOwn(message, 'result') || Object.hasOwn(message, 'error'))
95
+ );
96
+ }
97
+
98
+ /** @param {string} requested */
99
+ function negotiateProtocolVersion(requested) {
100
+ return SUPPORTED_PROTOCOL_VERSIONS.includes(requested)
101
+ ? requested
102
+ : SUPPORTED_PROTOCOL_VERSIONS[0];
103
+ }
104
+
105
+ /**
106
+ * The last `ID_WINDOW_BYTES` of `previous` followed by `segment`, copied so
107
+ * that the window never pins a large chunk in memory.
108
+ * @param {Buffer} previous
109
+ * @param {Buffer} segment
110
+ */
111
+ function rollWindow(previous, segment) {
112
+ const recent = segment.subarray(Math.max(0, segment.length - ID_WINDOW_BYTES));
113
+ const joined = Buffer.concat([previous, recent]);
114
+ return Buffer.from(joined.subarray(Math.max(0, joined.length - ID_WINDOW_BYTES)));
115
+ }
116
+
117
+ /**
118
+ * @param {Buffer} head
119
+ * @param {Buffer} tail
120
+ * @returns {RequestId | undefined}
121
+ */
122
+ function recoverRequestId(head, tail) {
123
+ const match =
124
+ LEADING_ID_PATTERN.exec(head.toString('utf8')) ??
125
+ TRAILING_ID_PATTERN.exec(tail.toString('utf8'));
126
+ if (match?.[1] === undefined) return undefined;
127
+ try {
128
+ const id = JSON.parse(match[1]);
129
+ return isRequestId(id) ? id : undefined;
130
+ } catch {
131
+ return undefined;
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Splits a byte stream into lines. A line longer than `MAX_LINE_BYTES` is
137
+ * dropped as it streams in: only its first and last `ID_WINDOW_BYTES` are kept.
138
+ * @param {(line: Buffer) => void} onLine
139
+ * @param {(head: Buffer, tail: Buffer) => void} onOversizedLine
140
+ */
141
+ function createLineSplitter(onLine, onOversizedLine) {
142
+ /** @type {Buffer[]} */
143
+ let parts = [];
144
+ let size = 0;
145
+ /** @type {{ head: Buffer, tail: Buffer } | undefined} */
146
+ let dropped;
147
+
148
+ function reset() {
149
+ parts = [];
150
+ size = 0;
151
+ dropped = undefined;
152
+ }
153
+
154
+ /** @param {Buffer} segment */
155
+ function startDropping(segment) {
156
+ const all = [...parts, segment];
157
+ const head = Buffer.concat(all, Math.min(ID_WINDOW_BYTES, size + segment.length));
158
+ dropped = { head, tail: all.reduce(rollWindow, Buffer.alloc(0)) };
159
+ parts = [];
160
+ size = 0;
161
+ }
162
+
163
+ /** @param {Buffer} segment */
164
+ function extendLine(segment) {
165
+ if (dropped) {
166
+ dropped.tail = rollWindow(dropped.tail, segment);
167
+ return;
168
+ }
169
+ if (size + segment.length > MAX_LINE_BYTES) {
170
+ startDropping(segment);
171
+ return;
172
+ }
173
+ // A copy, so that a short remainder does not pin the whole chunk.
174
+ parts.push(Buffer.from(segment));
175
+ size += segment.length;
176
+ }
177
+
178
+ /** @param {Buffer} segment */
179
+ function endLine(segment) {
180
+ if (!dropped && size + segment.length <= MAX_LINE_BYTES) {
181
+ const line = parts.length === 0 ? segment : Buffer.concat([...parts, segment]);
182
+ reset();
183
+ onLine(line);
184
+ return;
185
+ }
186
+ extendLine(segment);
187
+ const { head, tail } = /** @type {{ head: Buffer, tail: Buffer }} */ (dropped);
188
+ reset();
189
+ onOversizedLine(head, tail);
190
+ }
191
+
192
+ /** @param {Buffer} chunk */
193
+ return function push(chunk) {
194
+ let start = 0;
195
+ for (
196
+ let index = chunk.indexOf(NEWLINE_BYTE);
197
+ index !== -1;
198
+ index = chunk.indexOf(NEWLINE_BYTE, start)
199
+ ) {
200
+ endLine(chunk.subarray(start, index));
201
+ start = index + 1;
202
+ }
203
+ if (start < chunk.length) extendLine(chunk.subarray(start));
204
+ };
205
+ }
206
+
207
+ /**
208
+ * Serves the tools over newline-delimited JSON-RPC on `input`/`output` until
209
+ * the input ends, the output fails or `close()` is called.
210
+ * @param {ServeOptions} options
211
+ * @returns {{ closed: Promise<void>, close(): void }}
212
+ */
213
+ export function serveStdioMcp(options) {
214
+ const { serverInfo, instructions, tools, input, output } = options;
215
+ const toolsByName = new Map(tools.map((tool) => [tool.name, tool]));
216
+ if (toolsByName.size !== tools.length) throw new TypeError('duplicate tool name');
217
+ const toolList = tools.map(({ name, description, inputSchema, annotations }) => ({
218
+ name,
219
+ description,
220
+ inputSchema,
221
+ ...(annotations && { annotations }),
222
+ }));
223
+ /** @type {Map<RequestId, AbortController>} */
224
+ const inFlight = new Map();
225
+ let isInitialized = false;
226
+ let isClosed = false;
227
+ let isWaitingForDrain = false;
228
+ /** @type {() => void} */
229
+ let resolveClosed = () => {};
230
+ /** @type {Promise<void>} */
231
+ const closed = new Promise((resolve) => {
232
+ resolveClosed = () => resolve();
233
+ });
234
+
235
+ function shutdown() {
236
+ if (isClosed) return;
237
+ isClosed = true;
238
+ input.off('data', onData);
239
+ input.off('end', shutdown);
240
+ input.off('close', shutdown);
241
+ output.off('drain', onDrain);
242
+ output.off('close', shutdown);
243
+ // The 'error' listeners stay: a late error on either stream must remain handled.
244
+ for (const controller of inFlight.values()) controller.abort();
245
+ inFlight.clear();
246
+ input.pause();
247
+ resolveClosed();
248
+ }
249
+
250
+ function onDrain() {
251
+ isWaitingForDrain = false;
252
+ if (!isClosed) input.resume();
253
+ }
254
+
255
+ /** @param {Error | null | undefined} error */
256
+ function onWriteDone(error) {
257
+ if (error) shutdown();
258
+ }
259
+
260
+ /**
261
+ * One write per frame; a full output pauses the input until it drains.
262
+ * @param {string} frame
263
+ */
264
+ function writeFrame(frame) {
265
+ if (isClosed) return;
266
+ try {
267
+ if (output.write(frame, onWriteDone) || isWaitingForDrain) return;
268
+ } catch {
269
+ shutdown();
270
+ return;
271
+ }
272
+ isWaitingForDrain = true;
273
+ input.pause();
274
+ output.once('drain', onDrain);
275
+ }
276
+
277
+ /**
278
+ * @param {RequestId} id
279
+ * @param {unknown} result
280
+ */
281
+ function replyResult(id, result) {
282
+ writeFrame(`${JSON.stringify({ jsonrpc: JSONRPC_VERSION, id, result })}\n`);
283
+ }
284
+
285
+ /**
286
+ * @param {RequestId | null} id
287
+ * @param {number} code
288
+ * @param {string} message
289
+ */
290
+ function replyError(id, code, message) {
291
+ writeFrame(`${JSON.stringify({ jsonrpc: JSONRPC_VERSION, id, error: { code, message } })}\n`);
292
+ }
293
+
294
+ /**
295
+ * A result that is not a tool result or cannot be serialised is answered as
296
+ * an internal error, so that the frame on the wire is always valid.
297
+ * @param {RequestId} id
298
+ * @param {unknown} result
299
+ */
300
+ function replyToolResult(id, result) {
301
+ if (!isPlainObject(result) || !Array.isArray(result.content)) {
302
+ replyResult(id, INTERNAL_ERROR_RESULT);
303
+ return;
304
+ }
305
+ let frame;
306
+ try {
307
+ frame = `${JSON.stringify({ jsonrpc: JSONRPC_VERSION, id, result })}\n`;
308
+ } catch {
309
+ replyResult(id, INTERNAL_ERROR_RESULT);
310
+ return;
311
+ }
312
+ writeFrame(frame);
313
+ }
314
+
315
+ /**
316
+ * @param {ToolDefinition} tool
317
+ * @param {Record<string, unknown>} args
318
+ * @param {AbortSignal} signal
319
+ * @returns {Promise<unknown>} never rejects
320
+ */
321
+ async function runTool(tool, args, signal) {
322
+ try {
323
+ return await tool.handler(args, { signal });
324
+ } catch {
325
+ return INTERNAL_ERROR_RESULT;
326
+ }
327
+ }
328
+
329
+ /**
330
+ * @param {RequestId} id
331
+ * @param {Record<string, unknown>} params
332
+ */
333
+ function callTool(id, params) {
334
+ const tool = typeof params.name === 'string' ? toolsByName.get(params.name) : undefined;
335
+ if (!tool) return replyError(id, ERROR_CODES.invalidParams, 'Unknown tool');
336
+ const args = params.arguments === undefined ? {} : params.arguments;
337
+ if (!isPlainObject(args)) return replyError(id, ERROR_CODES.invalidParams, 'Invalid arguments');
338
+ if (inFlight.has(id)) return replyError(id, ERROR_CODES.invalidRequest, 'Duplicate request id');
339
+ if (inFlight.size >= MAX_CONCURRENT_CALLS) {
340
+ return replyError(id, ERROR_CODES.server, 'Too many concurrent calls');
341
+ }
342
+ const controller = new AbortController();
343
+ inFlight.set(id, controller);
344
+ void runTool(tool, args, controller.signal).then((result) => {
345
+ if (inFlight.get(id) === controller) inFlight.delete(id);
346
+ // A cancelled call gets no response (MCP cancellation); a closed server writes nothing.
347
+ if (!controller.signal.aborted) replyToolResult(id, result);
348
+ });
349
+ }
350
+
351
+ /** @param {string} requestedVersion */
352
+ function initializeResult(requestedVersion) {
353
+ return {
354
+ protocolVersion: negotiateProtocolVersion(requestedVersion),
355
+ capabilities: { tools: {} },
356
+ serverInfo,
357
+ ...(instructions !== undefined && { instructions }),
358
+ };
359
+ }
360
+
361
+ /**
362
+ * @param {RequestId} id
363
+ * @param {string} method
364
+ * @param {Record<string, unknown>} params
365
+ */
366
+ function handleRequest(id, method, params) {
367
+ if (method === 'ping') return replyResult(id, {});
368
+ if (method === 'initialize') {
369
+ if (isInitialized) {
370
+ return replyError(id, ERROR_CODES.invalidRequest, 'Server already initialized');
371
+ }
372
+ if (typeof params.protocolVersion !== 'string') {
373
+ return replyError(id, ERROR_CODES.invalidParams, 'Invalid params');
374
+ }
375
+ isInitialized = true;
376
+ return replyResult(id, initializeResult(params.protocolVersion));
377
+ }
378
+ if (!isInitialized) return replyError(id, ERROR_CODES.server, 'Server not initialized');
379
+ if (method === 'tools/list') return replyResult(id, { tools: toolList });
380
+ if (method === 'tools/call') return callTool(id, params);
381
+ return replyError(id, ERROR_CODES.methodNotFound, 'Method not found');
382
+ }
383
+
384
+ /**
385
+ * `notifications/initialized` needs nothing: requests are served from the
386
+ * `initialize` response on. Unknown notifications are ignored.
387
+ * @param {string} method
388
+ * @param {Record<string, unknown>} params
389
+ */
390
+ function handleNotification(method, params) {
391
+ if (method !== 'notifications/cancelled' || !isRequestId(params.requestId)) return;
392
+ const controller = inFlight.get(params.requestId);
393
+ if (!controller) return;
394
+ inFlight.delete(params.requestId);
395
+ controller.abort();
396
+ }
397
+
398
+ /** @param {unknown} message */
399
+ function dispatch(message) {
400
+ // A batch (array) is not part of MCP since 2025-06-18.
401
+ if (!isPlainObject(message)) {
402
+ replyError(null, ERROR_CODES.invalidRequest, 'Invalid Request');
403
+ return;
404
+ }
405
+ // The server sends no requests, so a response has nothing to answer.
406
+ if (isResponse(message)) return;
407
+ const { id, method, params = {} } = message;
408
+ const hasId = Object.hasOwn(message, 'id');
409
+ if (
410
+ message.jsonrpc !== JSONRPC_VERSION ||
411
+ typeof method !== 'string' ||
412
+ (hasId && !isRequestId(id)) ||
413
+ !isPlainObject(params)
414
+ ) {
415
+ replyError(isRequestId(id) ? id : null, ERROR_CODES.invalidRequest, 'Invalid Request');
416
+ return;
417
+ }
418
+ if (isRequestId(id)) handleRequest(id, method, params);
419
+ else handleNotification(method, params);
420
+ }
421
+
422
+ /** @param {Buffer} line */
423
+ function handleLine(line) {
424
+ if (isClosed) return;
425
+ // JSON whitespace includes '\r', so a CRLF-framed line parses as is.
426
+ const text = line.toString('utf8');
427
+ if (text.trim() === '') return;
428
+ let message;
429
+ try {
430
+ message = JSON.parse(text);
431
+ } catch {
432
+ replyError(null, ERROR_CODES.parse, 'Parse error');
433
+ return;
434
+ }
435
+ dispatch(message);
436
+ }
437
+
438
+ /**
439
+ * @param {Buffer} head
440
+ * @param {Buffer} tail
441
+ */
442
+ function handleOversizedLine(head, tail) {
443
+ if (isClosed) return;
444
+ const id = recoverRequestId(head, tail);
445
+ if (id !== undefined) replyError(id, ERROR_CODES.invalidRequest, 'Request too large');
446
+ }
447
+
448
+ const pushChunk = createLineSplitter(handleLine, handleOversizedLine);
449
+
450
+ /** @param {Buffer | string} chunk */
451
+ function onData(chunk) {
452
+ pushChunk(typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk);
453
+ }
454
+
455
+ input.on('data', onData);
456
+ input.on('end', shutdown);
457
+ input.on('close', shutdown);
458
+ input.on('error', shutdown);
459
+ output.on('close', shutdown);
460
+ output.on('error', shutdown);
461
+
462
+ return { closed, close: shutdown };
463
+ }