@hop-top/kit 0.5.0-alpha.8 → 0.5.0-alpha.9
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.
- package/CHANGELOG.md +22 -0
- package/dist/{chunk-263IZ6Z6.js → chunk-B4ULGCCN.js} +43 -154
- package/dist/{chunk-JTMPNXVQ.js → chunk-P6GRX4RV.js} +486 -83
- package/dist/chunk-UZ65A27P.js +147 -0
- package/dist/{index-B-pqGHhU.d.ts → index-CaOXdl38.d.ts} +337 -24
- package/dist/index.d.ts +2 -2
- package/dist/index.js +4 -3
- package/dist/mcp/index.d.ts +2 -1
- package/dist/mcp/index.js +31 -2
- package/dist/{toolspec-UrWnoJ3Y.d.ts → toolspec-96rkLfsh.d.ts} +7 -2
- package/dist/toolspec.d.ts +1 -1
- package/dist/toolspec.js +3 -2
- package/package.json +1 -1
- package/src/mcp/README.md +6 -0
- package/src/mcp/args-separator.test.ts +164 -0
- package/src/mcp/args.test.ts +223 -0
- package/src/mcp/args.ts +160 -0
- package/src/mcp/audit.test.ts +520 -0
- package/src/mcp/audit.ts +70 -0
- package/src/mcp/bridge.test.ts +72 -0
- package/src/mcp/bridge.ts +50 -5
- package/src/mcp/conformance.test.ts +1 -1
- package/src/mcp/dispatch.ts +48 -2
- package/src/mcp/index.ts +33 -1
- package/src/mcp/legacy-notify.test.ts +59 -0
- package/src/mcp/legacy.ts +55 -15
- package/src/mcp/modern-confirm.ts +42 -10
- package/src/mcp/modern.ts +99 -35
- package/src/mcp/stdio.test.ts +313 -0
- package/src/mcp/stdio.ts +254 -0
- package/src/mcp/toolname.test.ts +147 -0
- package/src/mcp/types.ts +125 -18
- package/src/toolspec-internal.ts +24 -0
- package/src/toolspec-manifest.test.ts +25 -0
- package/src/toolspec-manifest.ts +5 -1
- package/src/toolspec.from-command.test.ts +51 -0
- package/src/toolspec.ts +29 -15
|
@@ -47,13 +47,22 @@ import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
|
|
|
47
47
|
import {
|
|
48
48
|
canonicalJSONStringify,
|
|
49
49
|
errorResultBlock,
|
|
50
|
+
MCP_SPEC_2026_07_28,
|
|
50
51
|
META_KEY_CLIENT_CAPABILITIES,
|
|
51
52
|
RESULT_TYPE_INPUT_REQUIRED,
|
|
52
53
|
toolName,
|
|
53
54
|
type Leaf,
|
|
55
|
+
type McpAuditHook,
|
|
54
56
|
} from './types.js';
|
|
55
57
|
import { headerValue } from './legacy.js';
|
|
56
58
|
import type { McpHttpRequest } from './dispatch.js';
|
|
59
|
+
import {
|
|
60
|
+
auditRefusal,
|
|
61
|
+
MCP_AUDIT_CONFIRMATION_DECLINED,
|
|
62
|
+
MCP_AUDIT_CONFIRMATION_REQUIRED,
|
|
63
|
+
MCP_AUDIT_CONFIRMATION_STATE_REJECTED,
|
|
64
|
+
MCP_CONFIRM_REJECTION_STATE,
|
|
65
|
+
} from './audit.js';
|
|
57
66
|
|
|
58
67
|
/**
|
|
59
68
|
* The single reserved `inputRequests` key the confirmation flow uses;
|
|
@@ -128,12 +137,22 @@ export class ElicitationConfirmGate {
|
|
|
128
137
|
private readonly key: Buffer;
|
|
129
138
|
|
|
130
139
|
/**
|
|
131
|
-
*
|
|
132
|
-
*
|
|
140
|
+
* In-memory records of rejected states, kept beside the mount's
|
|
141
|
+
* `audit` hook for callers holding the gate directly.
|
|
133
142
|
*/
|
|
134
143
|
readonly rejections: McpConfirmRejection[] = [];
|
|
135
144
|
|
|
136
|
-
|
|
145
|
+
/**
|
|
146
|
+
* `toolNameSeparator` names the tool in the confirmation prompt, as
|
|
147
|
+
* the mount's `toolNameSeparator` option does in tools/list. `audit`
|
|
148
|
+
* is the mount's refusal hook: it receives the gate's three refusals
|
|
149
|
+
* (confirmation required, declined, state rejected).
|
|
150
|
+
*/
|
|
151
|
+
constructor(
|
|
152
|
+
key: Uint8Array,
|
|
153
|
+
private readonly toolNameSeparator?: string,
|
|
154
|
+
private readonly audit?: McpAuditHook,
|
|
155
|
+
) {
|
|
137
156
|
if (key.length === 0) {
|
|
138
157
|
throw new Error('cmdsurface: confirmationKey: empty key');
|
|
139
158
|
}
|
|
@@ -153,7 +172,11 @@ export class ElicitationConfirmGate {
|
|
|
153
172
|
): McpConfirmDecision | undefined {
|
|
154
173
|
if (!leaf.class?.requiresConfirmation) return undefined;
|
|
155
174
|
if (!clientSupportsFormElicitation(params)) {
|
|
156
|
-
|
|
175
|
+
const refused = headerConfirmationGate(req);
|
|
176
|
+
if (refused !== undefined) {
|
|
177
|
+
this.emit(leaf, MCP_AUDIT_CONFIRMATION_REQUIRED);
|
|
178
|
+
}
|
|
179
|
+
return refused;
|
|
157
180
|
}
|
|
158
181
|
|
|
159
182
|
const binding: McpConfirmBinding = {
|
|
@@ -191,6 +214,7 @@ export class ElicitationConfirmGate {
|
|
|
191
214
|
|
|
192
215
|
if (retry.action === 'accept') return undefined;
|
|
193
216
|
if (retry.action === 'decline' || retry.action === 'cancel') {
|
|
217
|
+
this.emit(leaf, MCP_AUDIT_CONFIRMATION_DECLINED);
|
|
194
218
|
return { result: errorResultBlock('confirmation declined'), status: 200 };
|
|
195
219
|
}
|
|
196
220
|
// The confirm answer is missing or unusable (absent inputResponses,
|
|
@@ -221,7 +245,7 @@ export class ElicitationConfirmGate {
|
|
|
221
245
|
method: 'elicitation/create',
|
|
222
246
|
params: {
|
|
223
247
|
mode: 'form',
|
|
224
|
-
message: `Approve execution of ${JSON.stringify(toolName(leaf.path))}?`,
|
|
248
|
+
message: `Approve execution of ${JSON.stringify(toolName(leaf.path, this.toolNameSeparator))}?`,
|
|
225
249
|
// No form fields: the approval rides the elicit action
|
|
226
250
|
// (accept / decline / cancel), so the requested schema is
|
|
227
251
|
// the empty object.
|
|
@@ -235,16 +259,24 @@ export class ElicitationConfirmGate {
|
|
|
235
259
|
|
|
236
260
|
/**
|
|
237
261
|
* Records a failed `requestState` verification as a
|
|
238
|
-
* security-relevant audit event
|
|
239
|
-
*
|
|
240
|
-
*
|
|
241
|
-
*
|
|
262
|
+
* security-relevant audit event: in memory on `rejections`, and on
|
|
263
|
+
* the mount's audit hook with the `mcp_confirm_rejection` extra Go's
|
|
264
|
+
* surfaces attach. Best-effort by the same contract: recording never
|
|
265
|
+
* affects the response.
|
|
242
266
|
*/
|
|
243
267
|
private auditRejection(leaf: Leaf): void {
|
|
244
268
|
this.rejections.push({
|
|
245
269
|
path: leaf.path.join(' '),
|
|
246
|
-
mcpConfirmRejection:
|
|
270
|
+
mcpConfirmRejection: MCP_CONFIRM_REJECTION_STATE,
|
|
247
271
|
});
|
|
272
|
+
this.emit(leaf, MCP_AUDIT_CONFIRMATION_STATE_REJECTED, {
|
|
273
|
+
mcp_confirm_rejection: MCP_CONFIRM_REJECTION_STATE,
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Emits one 2026-07-28 refusal record to the mount's audit hook. */
|
|
278
|
+
private emit(leaf: Leaf, error: string, extra?: Record<string, string>): void {
|
|
279
|
+
auditRefusal(this.audit, leaf.path, MCP_SPEC_2026_07_28, error, extra);
|
|
248
280
|
}
|
|
249
281
|
}
|
|
250
282
|
|
package/src/mcp/modern.ts
CHANGED
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
* instance can serve any request.
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
|
+
import { mcpSplitArguments } from './args.js';
|
|
19
20
|
import {
|
|
20
21
|
buildToolEnvelope,
|
|
21
22
|
errorResultBlock,
|
|
@@ -65,8 +66,15 @@ import type {
|
|
|
65
66
|
JsonRpcRequest,
|
|
66
67
|
McpHttpRequest,
|
|
67
68
|
McpHttpResponse,
|
|
69
|
+
McpTransport,
|
|
68
70
|
} from './dispatch.js';
|
|
69
71
|
import { acceptedResponse } from './dispatch.js';
|
|
72
|
+
import {
|
|
73
|
+
auditRefusal,
|
|
74
|
+
MCP_AUDIT_AUTH_REFUSED,
|
|
75
|
+
MCP_AUDIT_CONFIRMATION_REQUIRED,
|
|
76
|
+
MCP_AUDIT_DESTRUCTIVE_BLOCKED,
|
|
77
|
+
} from './audit.js';
|
|
70
78
|
|
|
71
79
|
/** One validation-chain failure: code, message, status, optional data. */
|
|
72
80
|
interface CheckError {
|
|
@@ -100,12 +108,24 @@ export class ModernMcpHandler {
|
|
|
100
108
|
*/
|
|
101
109
|
readonly confirmGate?: ElicitationConfirmGate;
|
|
102
110
|
|
|
111
|
+
/**
|
|
112
|
+
* `transport` selects the binding. Streamable HTTP mirrors the method,
|
|
113
|
+
* tool name and protocol version into headers and requires them to
|
|
114
|
+
* agree with the body (V4, V6, V7). stdio has no header layer — the
|
|
115
|
+
* body is the only source of truth — so those three checks do not
|
|
116
|
+
* apply there; every other check runs unchanged.
|
|
117
|
+
*/
|
|
103
118
|
constructor(
|
|
104
119
|
private readonly bridge: McpBridge,
|
|
105
120
|
private readonly cfg: ResolvedMcpConfig,
|
|
121
|
+
private readonly transport: McpTransport = 'http',
|
|
106
122
|
) {
|
|
107
123
|
if (cfg.confirmationKey !== undefined) {
|
|
108
|
-
this.confirmGate = new ElicitationConfirmGate(
|
|
124
|
+
this.confirmGate = new ElicitationConfirmGate(
|
|
125
|
+
cfg.confirmationKey,
|
|
126
|
+
cfg.toolNameSeparator,
|
|
127
|
+
cfg.audit,
|
|
128
|
+
);
|
|
109
129
|
}
|
|
110
130
|
}
|
|
111
131
|
|
|
@@ -162,30 +182,10 @@ export class ModernMcpHandler {
|
|
|
162
182
|
// V4 — MCP-Protocol-Version header present and equal to the _meta
|
|
163
183
|
// protocolVersion value. Conflicting duplicates are themselves a
|
|
164
184
|
// mismatch, decided without comparing either value to the body.
|
|
165
|
-
|
|
166
|
-
if (
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
msg: `${HEADER_MCP_PROTOCOL_VERSION} header sent with conflicting duplicate values`,
|
|
170
|
-
status: 400,
|
|
171
|
-
});
|
|
172
|
-
}
|
|
173
|
-
if (proto.value === '') {
|
|
174
|
-
return this.writeModernError(rpc, {
|
|
175
|
-
code: MCP_ERR_HEADER_MISMATCH,
|
|
176
|
-
msg: `missing ${HEADER_MCP_PROTOCOL_VERSION} header`,
|
|
177
|
-
status: 400,
|
|
178
|
-
});
|
|
179
|
-
}
|
|
180
|
-
// A non-string _meta value can never equal the header string.
|
|
181
|
-
if (!meta.versionIsText || proto.value !== meta.version) {
|
|
182
|
-
return this.writeModernError(rpc, {
|
|
183
|
-
code: MCP_ERR_HEADER_MISMATCH,
|
|
184
|
-
msg:
|
|
185
|
-
`${HEADER_MCP_PROTOCOL_VERSION} header ${JSON.stringify(proto.value)} ` +
|
|
186
|
-
`does not match _meta protocolVersion ${goFormatValue(meta.versionRaw)}`,
|
|
187
|
-
status: 400,
|
|
188
|
-
});
|
|
185
|
+
// HTTP only: stdio carries no headers.
|
|
186
|
+
if (this.transport === 'http') {
|
|
187
|
+
const versionErr = this.validateVersionHeader(req, meta);
|
|
188
|
+
if (versionErr) return this.writeModernError(rpc, versionErr);
|
|
189
189
|
}
|
|
190
190
|
|
|
191
191
|
// V5 — requested version supported. This handler supports exactly
|
|
@@ -204,8 +204,11 @@ export class ModernMcpHandler {
|
|
|
204
204
|
}
|
|
205
205
|
|
|
206
206
|
// V6 — Mcp-Method header presence and header/body agreement.
|
|
207
|
-
|
|
208
|
-
if (
|
|
207
|
+
// HTTP only.
|
|
208
|
+
if (this.transport === 'http') {
|
|
209
|
+
const methodErr = this.validateMethodHeader(req, rpc);
|
|
210
|
+
if (methodErr) return this.writeModernError(rpc, methodErr);
|
|
211
|
+
}
|
|
209
212
|
|
|
210
213
|
// V8 — method routing. V7 (Mcp-Name) and V9 (per-method params)
|
|
211
214
|
// run inside the method handlers.
|
|
@@ -231,6 +234,39 @@ export class ModernMcpHandler {
|
|
|
231
234
|
}
|
|
232
235
|
}
|
|
233
236
|
|
|
237
|
+
/** V4: MCP-Protocol-Version header present and equal to _meta's. */
|
|
238
|
+
private validateVersionHeader(
|
|
239
|
+
req: McpHttpRequest,
|
|
240
|
+
meta: ModernRequestMeta,
|
|
241
|
+
): CheckError | undefined {
|
|
242
|
+
const proto = singleHeaderValue(req, HEADER_MCP_PROTOCOL_VERSION);
|
|
243
|
+
if (!proto.ok) {
|
|
244
|
+
return {
|
|
245
|
+
code: MCP_ERR_HEADER_MISMATCH,
|
|
246
|
+
msg: `${HEADER_MCP_PROTOCOL_VERSION} header sent with conflicting duplicate values`,
|
|
247
|
+
status: 400,
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
if (proto.value === '') {
|
|
251
|
+
return {
|
|
252
|
+
code: MCP_ERR_HEADER_MISMATCH,
|
|
253
|
+
msg: `missing ${HEADER_MCP_PROTOCOL_VERSION} header`,
|
|
254
|
+
status: 400,
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
// A non-string _meta value can never equal the header string.
|
|
258
|
+
if (!meta.versionIsText || proto.value !== meta.version) {
|
|
259
|
+
return {
|
|
260
|
+
code: MCP_ERR_HEADER_MISMATCH,
|
|
261
|
+
msg:
|
|
262
|
+
`${HEADER_MCP_PROTOCOL_VERSION} header ${JSON.stringify(proto.value)} ` +
|
|
263
|
+
`does not match _meta protocolVersion ${goFormatValue(meta.versionRaw)}`,
|
|
264
|
+
status: 400,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
return undefined;
|
|
268
|
+
}
|
|
269
|
+
|
|
234
270
|
/**
|
|
235
271
|
* server/discover — the mandatory modern discovery method. Carries
|
|
236
272
|
* no listChanged flag (notifications unimplemented), no extensions
|
|
@@ -257,7 +293,7 @@ export class ModernMcpHandler {
|
|
|
257
293
|
const tools: Array<Record<string, unknown>> = [];
|
|
258
294
|
for (const leaf of this.bridge.leaves()) {
|
|
259
295
|
if (!isExposed(leaf)) continue;
|
|
260
|
-
tools.push(buildToolEnvelope(leaf));
|
|
296
|
+
tools.push(buildToolEnvelope(leaf, this.cfg.toolNameSeparator));
|
|
261
297
|
}
|
|
262
298
|
const res: Record<string, unknown> = { tools };
|
|
263
299
|
this.applyCacheHints(res);
|
|
@@ -279,9 +315,12 @@ export class ModernMcpHandler {
|
|
|
279
315
|
// V7 — Mcp-Name agreement, run against a pre-decode peek of
|
|
280
316
|
// params.name so a header failure is reported even when the rest
|
|
281
317
|
// of params is unparseable.
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
318
|
+
// HTTP only: stdio has no header layer.
|
|
319
|
+
if (this.transport === 'http') {
|
|
320
|
+
const peek = rawToolCallName(rpc.params);
|
|
321
|
+
const nameErr = this.validateNameHeader(req, peek);
|
|
322
|
+
if (nameErr) return this.writeModernError(rpc, nameErr);
|
|
323
|
+
}
|
|
285
324
|
|
|
286
325
|
const params = (rpc.params ?? {}) as {
|
|
287
326
|
name?: unknown;
|
|
@@ -301,7 +340,7 @@ export class ModernMcpHandler {
|
|
|
301
340
|
);
|
|
302
341
|
}
|
|
303
342
|
|
|
304
|
-
const leaf = resolveLeaf(this.bridge, name);
|
|
343
|
+
const leaf = resolveLeaf(this.bridge, name, this.cfg.toolNameSeparator);
|
|
305
344
|
if (leaf === undefined || !isExposed(leaf)) {
|
|
306
345
|
return writeError(
|
|
307
346
|
rpc.id,
|
|
@@ -314,6 +353,7 @@ export class ModernMcpHandler {
|
|
|
314
353
|
// verifier authenticates, never a bare Authorization header.
|
|
315
354
|
const ident = await establishCaller(this.cfg.verifier, req);
|
|
316
355
|
if (leaf.class?.authRequired && ident === undefined) {
|
|
356
|
+
this.audit(leaf, MCP_AUDIT_AUTH_REFUSED);
|
|
317
357
|
return unauthenticated(
|
|
318
358
|
this.writeCallError(rpc, 'authentication required', 401),
|
|
319
359
|
);
|
|
@@ -324,6 +364,13 @@ export class ModernMcpHandler {
|
|
|
324
364
|
// IS the header gate, for everyone. Either way the decision is a
|
|
325
365
|
// pre-flight refusal or an interim prompt, stamped with the modern
|
|
326
366
|
// envelope like every other result on this path.
|
|
367
|
+
//
|
|
368
|
+
// Arguments are checked first: a person is never asked to
|
|
369
|
+
// approve a call that cannot run as sent.
|
|
370
|
+
const split = mcpSplitArguments(leaf, params.arguments);
|
|
371
|
+
if (split.error !== undefined) {
|
|
372
|
+
return this.writeCallError(rpc, split.error, 200);
|
|
373
|
+
}
|
|
327
374
|
const gated = this.confirmationGate(req, leaf, rpc.params);
|
|
328
375
|
if (gated !== undefined) {
|
|
329
376
|
return writeResult(
|
|
@@ -336,7 +383,8 @@ export class ModernMcpHandler {
|
|
|
336
383
|
try {
|
|
337
384
|
const res = await this.bridge.invoke({
|
|
338
385
|
path: [...leaf.path],
|
|
339
|
-
|
|
386
|
+
...(split.args !== undefined ? { args: split.args } : {}),
|
|
387
|
+
flags: split.flags,
|
|
340
388
|
meta: invocationMeta(ident, modernInvocationExtra(meta)),
|
|
341
389
|
});
|
|
342
390
|
const out = renderCallResult(res);
|
|
@@ -356,11 +404,21 @@ export class ModernMcpHandler {
|
|
|
356
404
|
);
|
|
357
405
|
}
|
|
358
406
|
// DestructiveBlockedError and every other invoke failure are
|
|
359
|
-
// complete isError results at HTTP 200, as on legacy.
|
|
407
|
+
// complete isError results at HTTP 200, as on legacy. Only the
|
|
408
|
+
// ceiling is a refusal the surface audits; a run that failed is
|
|
409
|
+
// the bridge's.
|
|
410
|
+
if (err instanceof DestructiveBlockedError) {
|
|
411
|
+
this.audit(leaf, MCP_AUDIT_DESTRUCTIVE_BLOCKED);
|
|
412
|
+
}
|
|
360
413
|
return this.writeCallError(rpc, errorMessage(err), 200);
|
|
361
414
|
}
|
|
362
415
|
}
|
|
363
416
|
|
|
417
|
+
/** Emits one 2026-07-28 refusal record to the mount's audit hook. */
|
|
418
|
+
private audit(leaf: Leaf, error: string): void {
|
|
419
|
+
auditRefusal(this.cfg.audit, leaf.path, MCP_SPEC_2026_07_28, error);
|
|
420
|
+
}
|
|
421
|
+
|
|
364
422
|
/**
|
|
365
423
|
* Selects and runs the confirmation strategy for one `tools/call`.
|
|
366
424
|
* Returns `undefined` to proceed with the invocation.
|
|
@@ -376,7 +434,13 @@ export class ModernMcpHandler {
|
|
|
376
434
|
params: unknown,
|
|
377
435
|
): McpConfirmDecision | undefined {
|
|
378
436
|
if (!leaf.class?.requiresConfirmation) return undefined;
|
|
379
|
-
if (this.confirmGate === undefined)
|
|
437
|
+
if (this.confirmGate === undefined) {
|
|
438
|
+
const refused = headerConfirmationGate(req);
|
|
439
|
+
if (refused !== undefined) {
|
|
440
|
+
this.audit(leaf, MCP_AUDIT_CONFIRMATION_REQUIRED);
|
|
441
|
+
}
|
|
442
|
+
return refused;
|
|
443
|
+
}
|
|
380
444
|
return this.confirmGate.evaluate(req, leaf, params);
|
|
381
445
|
}
|
|
382
446
|
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The stdio binding: newline framing, notifications never answered,
|
|
3
|
+
* ping, parse / batch refusals, concurrent requests, both eras with no
|
|
4
|
+
* header layer, and a clean end of session.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { PassThrough } from 'node:stream';
|
|
8
|
+
import { describe, expect, it } from 'vitest';
|
|
9
|
+
|
|
10
|
+
import { createMcpHandler, type McpHandler } from './dispatch.js';
|
|
11
|
+
import { serveStdio, type McpStdioServer } from './stdio.js';
|
|
12
|
+
import { legacyLockBridge, mrtrLockBridge } from './testtree.js';
|
|
13
|
+
import type { McpBridge, McpMountOptions } from './types.js';
|
|
14
|
+
|
|
15
|
+
const MODERN_META =
|
|
16
|
+
'"_meta":{"io.modelcontextprotocol/clientCapabilities":{},' +
|
|
17
|
+
'"io.modelcontextprotocol/protocolVersion":"2026-07-28"}';
|
|
18
|
+
|
|
19
|
+
interface Session {
|
|
20
|
+
server: McpStdioServer;
|
|
21
|
+
input: PassThrough;
|
|
22
|
+
/** Every line written to the output stream, in order. */
|
|
23
|
+
lines: () => string[];
|
|
24
|
+
/** Everything written to the log stream. */
|
|
25
|
+
log: () => string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function session(
|
|
29
|
+
target: McpBridge | McpHandler,
|
|
30
|
+
mount?: McpMountOptions,
|
|
31
|
+
): Session {
|
|
32
|
+
const input = new PassThrough();
|
|
33
|
+
const output = new PassThrough();
|
|
34
|
+
const log = new PassThrough();
|
|
35
|
+
let out = '';
|
|
36
|
+
let err = '';
|
|
37
|
+
output.on('data', (c: Buffer) => (out += c.toString('utf8')));
|
|
38
|
+
log.on('data', (c: Buffer) => (err += c.toString('utf8')));
|
|
39
|
+
const server = serveStdio(target, { input, output, log, mount });
|
|
40
|
+
return {
|
|
41
|
+
server,
|
|
42
|
+
input,
|
|
43
|
+
lines: () => out.split('\n').filter((l) => l !== ''),
|
|
44
|
+
log: () => err,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Writes each message as one line, ends input, waits for the session. */
|
|
49
|
+
async function run(s: Session, ...messages: string[]): Promise<string[]> {
|
|
50
|
+
for (const m of messages) s.input.write(`${m}\n`);
|
|
51
|
+
s.input.end();
|
|
52
|
+
await s.server.done;
|
|
53
|
+
return s.lines();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function byId(lines: string[]): Map<unknown, Record<string, unknown>> {
|
|
57
|
+
const out = new Map<unknown, Record<string, unknown>>();
|
|
58
|
+
for (const l of lines) {
|
|
59
|
+
const m = JSON.parse(l) as Record<string, unknown>;
|
|
60
|
+
out.set(m.id, m);
|
|
61
|
+
}
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A bridge whose `slow` leaf answers only after `fast` has. */
|
|
66
|
+
function orderedBridge(): McpBridge {
|
|
67
|
+
let releaseSlow: () => void = () => {};
|
|
68
|
+
const fastDone = new Promise<void>((r) => (releaseSlow = r));
|
|
69
|
+
return {
|
|
70
|
+
leaves: () => [
|
|
71
|
+
{ path: ['slow'], description: 'Slow', properties: {} },
|
|
72
|
+
{ path: ['fast'], description: 'Fast', properties: {} },
|
|
73
|
+
],
|
|
74
|
+
async invoke(inv) {
|
|
75
|
+
if (inv.path[0] === 'slow') {
|
|
76
|
+
await fastDone;
|
|
77
|
+
return { stdout: 'slow\n', exitCode: 0 };
|
|
78
|
+
}
|
|
79
|
+
setTimeout(releaseSlow, 5);
|
|
80
|
+
return { stdout: 'fast\n', exitCode: 0 };
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
describe('serveStdio', () => {
|
|
86
|
+
it('runs the legacy handshake and never answers a notification', async () => {
|
|
87
|
+
const lines = await run(
|
|
88
|
+
session(legacyLockBridge()),
|
|
89
|
+
'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"pipe","version":"0"}}}',
|
|
90
|
+
'{"jsonrpc":"2.0","method":"notifications/initialized"}',
|
|
91
|
+
'{"jsonrpc":"2.0","id":2,"method":"tools/list"}',
|
|
92
|
+
'{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"ping"}}',
|
|
93
|
+
);
|
|
94
|
+
expect(lines).toHaveLength(3);
|
|
95
|
+
const got = byId(lines);
|
|
96
|
+
expect([...got.keys()].sort()).toEqual([1, 2, 3]);
|
|
97
|
+
expect(got.get(1)?.result).toMatchObject({ protocolVersion: '2024-11-05' });
|
|
98
|
+
expect(JSON.stringify(got.get(3)?.result)).toContain('pong');
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('answers ping with an empty result', async () => {
|
|
102
|
+
const lines = await run(session(legacyLockBridge()), '{"jsonrpc":"2.0","id":"p1","method":"ping"}');
|
|
103
|
+
expect(lines).toEqual(['{"jsonrpc":"2.0","id":"p1","result":{}}']);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('drops every notification, even a malformed or failing one', async () => {
|
|
107
|
+
const lines = await run(
|
|
108
|
+
session(legacyLockBridge()),
|
|
109
|
+
'{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":1}}',
|
|
110
|
+
'{"jsonrpc":"1.0","method":"notifications/initialized"}',
|
|
111
|
+
'{"jsonrpc":"2.0","method":"tools/call","params":{"name":"ping"}}',
|
|
112
|
+
'{"jsonrpc":"2.0","method":"nope"}',
|
|
113
|
+
);
|
|
114
|
+
expect(lines).toEqual([]);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('answers unparseable input with -32700 and id null', async () => {
|
|
118
|
+
const lines = await run(session(legacyLockBridge()), '{not json');
|
|
119
|
+
expect(lines).toEqual([
|
|
120
|
+
'{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"parse error: invalid character \'n\' looking for beginning of object key string"}}',
|
|
121
|
+
]);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('refuses a batch and a non-object message with -32600 and id null', async () => {
|
|
125
|
+
const lines = await run(
|
|
126
|
+
session(legacyLockBridge()),
|
|
127
|
+
'[{"jsonrpc":"2.0","id":1,"method":"ping"}]',
|
|
128
|
+
'42',
|
|
129
|
+
);
|
|
130
|
+
expect(lines).toEqual([
|
|
131
|
+
'{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"invalid request: batch requests are not supported"}}',
|
|
132
|
+
'{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"invalid request: not a JSON-RPC object"}}',
|
|
133
|
+
]);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it('answers a request without a method with -32600 and its id', async () => {
|
|
137
|
+
const lines = await run(session(legacyLockBridge()), '{"jsonrpc":"2.0","id":9}');
|
|
138
|
+
expect(lines).toEqual([
|
|
139
|
+
'{"jsonrpc":"2.0","id":9,"error":{"code":-32600,"message":"invalid request: missing method"}}',
|
|
140
|
+
]);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it('ignores a client response on stdout and logs it to the log stream', async () => {
|
|
144
|
+
const s = session(legacyLockBridge());
|
|
145
|
+
const lines = await run(s, '{"jsonrpc":"2.0","id":1,"result":{}}');
|
|
146
|
+
expect(lines).toEqual([]);
|
|
147
|
+
expect(s.log()).toContain('ignored a JSON-RPC response');
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it('skips blank lines and accepts CRLF framing', async () => {
|
|
151
|
+
const s = session(legacyLockBridge());
|
|
152
|
+
s.input.write('\n \n{"jsonrpc":"2.0","id":1,"method":"ping"}\r\n');
|
|
153
|
+
s.input.end();
|
|
154
|
+
await s.server.done;
|
|
155
|
+
expect(s.lines()).toEqual(['{"jsonrpc":"2.0","id":1,"result":{}}']);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it('runs requests concurrently; replies arrive out of order, each with its id', async () => {
|
|
159
|
+
const lines = await run(
|
|
160
|
+
session(orderedBridge()),
|
|
161
|
+
'{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"slow"}}',
|
|
162
|
+
'{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"fast"}}',
|
|
163
|
+
);
|
|
164
|
+
expect(lines.map((l) => (JSON.parse(l) as { id: number }).id)).toEqual([2, 1]);
|
|
165
|
+
expect(lines[0]).toContain('fast');
|
|
166
|
+
expect(lines[1]).toContain('slow');
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it('serves 2026-07-28 from the body alone: no header layer on stdio', async () => {
|
|
170
|
+
const lines = await run(
|
|
171
|
+
session(legacyLockBridge()),
|
|
172
|
+
`{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{${MODERN_META}}}`,
|
|
173
|
+
`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ping",${MODERN_META}}}`,
|
|
174
|
+
`{"jsonrpc":"2.0","id":3,"method":"ping","params":{${MODERN_META}}}`,
|
|
175
|
+
);
|
|
176
|
+
const got = byId(lines);
|
|
177
|
+
expect(got.get(1)?.result).toMatchObject({
|
|
178
|
+
resultType: 'complete',
|
|
179
|
+
supportedVersions: ['2026-07-28'],
|
|
180
|
+
});
|
|
181
|
+
expect(got.get(2)?.result).toMatchObject({ resultType: 'complete', isError: false });
|
|
182
|
+
// 2026-07-28 removed ping: a modern ping is an unknown method.
|
|
183
|
+
expect(got.get(3)?.error).toMatchObject({ code: -32601 });
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
it('keeps the remaining modern validation (unsupported version)', async () => {
|
|
187
|
+
const lines = await run(
|
|
188
|
+
session(legacyLockBridge()),
|
|
189
|
+
'{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/clientCapabilities":{},"io.modelcontextprotocol/protocolVersion":"2099-01-01"}}}',
|
|
190
|
+
);
|
|
191
|
+
expect(JSON.parse(lines[0] ?? '{}')).toMatchObject({ id: 1, error: { code: -32022 } });
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it('reuses a createMcpHandler handler, mount options included', async () => {
|
|
195
|
+
const handler = createMcpHandler(legacyLockBridge(), {
|
|
196
|
+
serverInfo: { name: 'stdio-tool', version: '9.9.9' },
|
|
197
|
+
});
|
|
198
|
+
const lines = await run(
|
|
199
|
+
session(handler),
|
|
200
|
+
'{"jsonrpc":"2.0","id":1,"method":"initialize"}',
|
|
201
|
+
`{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{${MODERN_META}}}`,
|
|
202
|
+
);
|
|
203
|
+
const got = byId(lines);
|
|
204
|
+
expect(got.get(1)?.result).toMatchObject({ serverInfo: { name: 'stdio-tool', version: '9.9.9' } });
|
|
205
|
+
expect(got.get(2)?.result).toMatchObject({ resultType: 'complete' });
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it('applies mount options when serving a bridge', async () => {
|
|
209
|
+
const lines = await run(
|
|
210
|
+
session(legacyLockBridge(), { specVersions: ['2026-07-28'] }),
|
|
211
|
+
'{"jsonrpc":"2.0","id":1,"method":"initialize"}',
|
|
212
|
+
);
|
|
213
|
+
expect(lines[0]).toContain('supported protocol versions: 2026-07-28');
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
it('refuses mount options alongside a handler', () => {
|
|
217
|
+
expect(() =>
|
|
218
|
+
serveStdio(createMcpHandler(legacyLockBridge()), {
|
|
219
|
+
input: new PassThrough(),
|
|
220
|
+
output: new PassThrough(),
|
|
221
|
+
mount: {},
|
|
222
|
+
}),
|
|
223
|
+
).toThrow(TypeError);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it('drives a foreign handler as an HTTP-shaped POST', async () => {
|
|
227
|
+
const inner = createMcpHandler(legacyLockBridge());
|
|
228
|
+
const foreign: McpHandler = (req) => inner(req);
|
|
229
|
+
const lines = await run(
|
|
230
|
+
session(foreign),
|
|
231
|
+
'{"jsonrpc":"2.0","id":1,"method":"ping"}',
|
|
232
|
+
'{"jsonrpc":"2.0","method":"notifications/initialized"}',
|
|
233
|
+
);
|
|
234
|
+
expect(lines).toEqual(['{"jsonrpc":"2.0","id":1,"result":{}}']);
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
it('answers -32603 when the handler throws, and logs the cause', async () => {
|
|
238
|
+
const s = session((() => Promise.reject(new Error('boom'))) as McpHandler);
|
|
239
|
+
const lines = await run(s, '{"jsonrpc":"2.0","id":4,"method":"ping"}');
|
|
240
|
+
expect(lines).toEqual(['{"jsonrpc":"2.0","id":4,"error":{"code":-32603,"message":"internal error"}}']);
|
|
241
|
+
expect(s.log()).toContain('boom');
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
it('waits for in-flight requests before done resolves', async () => {
|
|
245
|
+
let release: () => void = () => {};
|
|
246
|
+
const gate = new Promise<void>((r) => (release = r));
|
|
247
|
+
const bridge: McpBridge = {
|
|
248
|
+
leaves: () => [{ path: ['wait'], description: 'Wait', properties: {} }],
|
|
249
|
+
async invoke() {
|
|
250
|
+
await gate;
|
|
251
|
+
return { stdout: 'done\n', exitCode: 0 };
|
|
252
|
+
},
|
|
253
|
+
};
|
|
254
|
+
const s = session(bridge);
|
|
255
|
+
s.input.write('{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"wait"}}\n');
|
|
256
|
+
s.input.end();
|
|
257
|
+
let finished = false;
|
|
258
|
+
void s.server.done.then(() => (finished = true));
|
|
259
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
260
|
+
expect(finished).toBe(false);
|
|
261
|
+
release();
|
|
262
|
+
await s.server.done;
|
|
263
|
+
expect(s.lines()).toHaveLength(1);
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
it('confirms in-band over MRTR; a client without elicitation is refused', async () => {
|
|
267
|
+
const { bridge, executions } = mrtrLockBridge();
|
|
268
|
+
const s = session(bridge, { confirmationKey: 'stdio-mrtr-suite-shared-secret-32' });
|
|
269
|
+
const meta = (caps: Record<string, unknown>) => ({
|
|
270
|
+
'io.modelcontextprotocol/clientCapabilities': caps,
|
|
271
|
+
'io.modelcontextprotocol/protocolVersion': '2026-07-28',
|
|
272
|
+
});
|
|
273
|
+
const call = (id: number, extra: Record<string, unknown>) =>
|
|
274
|
+
JSON.stringify({ jsonrpc: '2.0', id, method: 'tools/call', params: { name: 'purge', ...extra } });
|
|
275
|
+
const reply = async (n: number) => {
|
|
276
|
+
while (s.lines().length < n) await new Promise((r) => setTimeout(r, 1));
|
|
277
|
+
return JSON.parse(s.lines()[n - 1] ?? '{}') as { id: number; result: Record<string, unknown> };
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
s.input.write(`${call(1, { _meta: meta({ elicitation: { form: {} } }) })}\n`);
|
|
281
|
+
const r1 = await reply(1);
|
|
282
|
+
expect(r1.result.resultType).toBe('input_required');
|
|
283
|
+
expect(Object.keys(r1.result.inputRequests as object)).toEqual(['confirm']);
|
|
284
|
+
expect(executions()).toBe(0);
|
|
285
|
+
|
|
286
|
+
s.input.write(
|
|
287
|
+
`${call(2, {
|
|
288
|
+
_meta: meta({ elicitation: { form: {} } }),
|
|
289
|
+
requestState: r1.result.requestState,
|
|
290
|
+
inputResponses: { confirm: { action: 'accept' } },
|
|
291
|
+
})}\n`,
|
|
292
|
+
);
|
|
293
|
+
const r2 = await reply(2);
|
|
294
|
+
expect(r2.result).toMatchObject({ resultType: 'complete', isError: false });
|
|
295
|
+
expect(executions()).toBe(1);
|
|
296
|
+
|
|
297
|
+
// No elicitation declared: the header gate applies, and stdio has no headers.
|
|
298
|
+
const lines = await run(s, call(3, { _meta: meta({}) }));
|
|
299
|
+
const r3 = JSON.parse(lines[2] ?? '{}') as { result: Record<string, unknown> };
|
|
300
|
+
expect(r3.result).toMatchObject({ resultType: 'complete', isError: true });
|
|
301
|
+
expect(executions()).toBe(1);
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
it('close() stops reading and resolves once idle', async () => {
|
|
305
|
+
const s = session(legacyLockBridge());
|
|
306
|
+
s.input.write('{"jsonrpc":"2.0","id":1,"method":"ping"}\n');
|
|
307
|
+
await new Promise((r) => setTimeout(r, 5));
|
|
308
|
+
await s.server.close();
|
|
309
|
+
s.input.write('{"jsonrpc":"2.0","id":2,"method":"ping"}\n');
|
|
310
|
+
await new Promise((r) => setTimeout(r, 5));
|
|
311
|
+
expect(s.lines()).toEqual(['{"jsonrpc":"2.0","id":1,"result":{}}']);
|
|
312
|
+
});
|
|
313
|
+
});
|