@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.3

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.
Files changed (107) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +333 -9
  3. package/dist/aim-CTp-kJW2.d.ts +139 -0
  4. package/dist/aim.d.ts +1 -116
  5. package/dist/alias-dhhr08Ei.d.ts +88 -0
  6. package/dist/alias.d.ts +2 -73
  7. package/dist/api-miiso81x.d.ts +77 -0
  8. package/dist/api.d.ts +1 -62
  9. package/dist/auth-2-jfgiHn.d.ts +34 -0
  10. package/dist/auth.d.ts +1 -26
  11. package/dist/cli-DLygZLi9.d.ts +450 -0
  12. package/dist/cli.d.ts +6 -309
  13. package/dist/cli.js +192 -63
  14. package/dist/config-BUY7_W2n.d.ts +103 -0
  15. package/dist/config.d.ts +1 -97
  16. package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
  17. package/dist/errcorrect.d.ts +1 -37
  18. package/dist/error-DISJKeDu.d.ts +144 -0
  19. package/dist/id/index.d.ts +2 -83
  20. package/dist/index-Bc5c7Ty5.d.ts +328 -0
  21. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  22. package/dist/index-MLrRDvEG.d.ts +1073 -0
  23. package/dist/index-QSffbLnj.d.ts +94 -0
  24. package/dist/index.d.ts +28 -0
  25. package/dist/index.js +6794 -0
  26. package/dist/llm-B5XUWH8T.d.ts +231 -0
  27. package/dist/llm.d.ts +1 -188
  28. package/dist/mcp/index.d.ts +2 -0
  29. package/dist/mcp/index.js +1453 -0
  30. package/dist/netpolicy-asvCfwi8.d.ts +138 -0
  31. package/dist/netpolicy.d.ts +1 -0
  32. package/dist/netpolicy.js +118 -0
  33. package/dist/output-4aXs91GY.d.ts +396 -0
  34. package/dist/output.d.ts +3 -213
  35. package/dist/output.js +567 -43
  36. package/dist/progress-CAzyxeWl.d.ts +38 -0
  37. package/dist/progress.d.ts +1 -30
  38. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  39. package/dist/provenance.d.ts +1 -24
  40. package/dist/routellm-PGSt2D1y.d.ts +75 -0
  41. package/dist/routellm.d.ts +2 -64
  42. package/dist/rpc-D5xLEf8V.d.ts +32 -0
  43. package/dist/rpc.d.ts +2 -25
  44. package/dist/safety-CUaYEjZc.d.ts +30 -0
  45. package/dist/safety.d.ts +1 -24
  46. package/dist/scope-BrhYB4ij.d.ts +141 -0
  47. package/dist/scope.d.ts +1 -121
  48. package/dist/serve-DE-jscpb.d.ts +646 -0
  49. package/dist/serve.d.ts +3 -0
  50. package/dist/serve.js +1019 -0
  51. package/dist/stream-CrjeCp0M.d.ts +44 -0
  52. package/dist/stream.d.ts +1 -35
  53. package/dist/telemetry/index.d.ts +1 -315
  54. package/dist/telemetry/index.js +12 -1
  55. package/dist/tui/index.d.ts +5 -298
  56. package/dist/tui/index.js +3 -10
  57. package/dist/upgrade-p_zh3pvV.d.ts +102 -0
  58. package/dist/upgrade.d.ts +1 -95
  59. package/dist/xdg-DB7Shoib.d.ts +179 -0
  60. package/dist/xdg.d.ts +1 -169
  61. package/package.json +26 -3
  62. package/src/cli.offline.test.ts +93 -0
  63. package/src/cli.parity.test.ts +192 -0
  64. package/src/cli.ts +112 -12
  65. package/src/index.test.ts +58 -0
  66. package/src/index.ts +37 -0
  67. package/src/log.parity.test.ts +105 -0
  68. package/src/log.ts +64 -13
  69. package/src/mcp/bridge.test.ts +150 -0
  70. package/src/mcp/bridge.ts +246 -0
  71. package/src/mcp/conformance.test.ts +336 -0
  72. package/src/mcp/dispatch.ts +313 -0
  73. package/src/mcp/index.ts +138 -0
  74. package/src/mcp/legacy.ts +314 -0
  75. package/src/mcp/mcp.test.ts +697 -0
  76. package/src/mcp/modern-confirm.test.ts +520 -0
  77. package/src/mcp/modern-confirm.ts +452 -0
  78. package/src/mcp/modern.ts +723 -0
  79. package/src/mcp/tasks.ts +82 -0
  80. package/src/mcp/testtree.ts +250 -0
  81. package/src/mcp/types.ts +504 -0
  82. package/src/netpolicy.test.ts +202 -0
  83. package/src/netpolicy.ts +231 -0
  84. package/src/output/dispatch.ts +10 -2
  85. package/src/output/error.ts +316 -0
  86. package/src/output/formatter.ts +29 -5
  87. package/src/output/formatters/csv.ts +48 -12
  88. package/src/output/formatters/json.ts +4 -25
  89. package/src/output/formatters/project.ts +34 -0
  90. package/src/output/formatters/table.ts +8 -6
  91. package/src/output/formatters/text.ts +7 -3
  92. package/src/output/formatters/yaml.ts +5 -22
  93. package/src/output/projection.test.ts +298 -0
  94. package/src/output/projection.ts +33 -59
  95. package/src/output/template.ts +11 -21
  96. package/src/output.surface.test.ts +41 -0
  97. package/src/output.ts +41 -3
  98. package/src/serve.test.ts +1257 -0
  99. package/src/serve.ts +1665 -0
  100. package/src/telemetry/client.test.ts +31 -0
  101. package/src/telemetry/client.ts +7 -1
  102. package/src/telemetry/offline.test.ts +64 -0
  103. package/src/tui/parity.test.ts +120 -31
  104. package/src/tui/parity.ts +58 -7
  105. package/test/output/csv.test.ts +164 -0
  106. package/test/output/error.test.ts +246 -0
  107. package/src/tui/parity.json +0 -74
@@ -0,0 +1,723 @@
1
+ /**
2
+ * @module mcp/modern
3
+ * @package @hop-top/kit
4
+ *
5
+ * The 2026-07-28 MCP handler: the stateless request core behind the
6
+ * era dispatcher. Implements ADR 0042's validation order V1-V9,
7
+ * `server/discover`, the modern error writers (-32020 / -32021 /
8
+ * -32022 with their status mapping), result-envelope stamping
9
+ * (`resultType` + serverInfo `_meta`), and cache-hint application.
10
+ *
11
+ * Statelessness is the revision's core contract: every request
12
+ * carries protocol version, client identity, and capabilities in
13
+ * `params._meta` under reserved io.modelcontextprotocol/* keys;
14
+ * there is no initialize/initialized handshake and no session id.
15
+ * The handler holds only immutable mount configuration, so any
16
+ * instance can serve any request.
17
+ */
18
+
19
+ import {
20
+ buildToolEnvelope,
21
+ errorResultBlock,
22
+ HEADER_MCP_METHOD,
23
+ HEADER_MCP_NAME,
24
+ HEADER_MCP_PROTOCOL_VERSION,
25
+ MCP_ERR_HEADER_MISMATCH,
26
+ MCP_ERR_INVALID_PARAMS,
27
+ MCP_ERR_INVALID_REQUEST,
28
+ MCP_ERR_METHOD_NOT_FOUND,
29
+ MCP_ERR_UNSUPPORTED_VERSION,
30
+ MCP_SPEC_2026_07_28,
31
+ META_KEY_CLIENT_CAPABILITIES,
32
+ META_KEY_CLIENT_INFO,
33
+ META_KEY_PROTOCOL_VERSION,
34
+ META_KEY_SERVER_INFO,
35
+ RESULT_TYPE_COMPLETE,
36
+ renderCallResult,
37
+ SURFACE_MCP,
38
+ type Leaf,
39
+ type McpBridge,
40
+ type RawJSON,
41
+ type ResolvedMcpConfig,
42
+ } from './types.js';
43
+ import {
44
+ DestructiveBlockedError,
45
+ SurfaceNotEnabledError,
46
+ UnknownCommandError,
47
+ } from './types.js';
48
+ import {
49
+ errorMessage,
50
+ headerValue,
51
+ headerValues,
52
+ isExposed,
53
+ resolveLeaf,
54
+ writeError,
55
+ writeResult,
56
+ } from './legacy.js';
57
+ import { isTaskMethod, taskMethodNotFound } from './tasks.js';
58
+ import {
59
+ ElicitationConfirmGate,
60
+ headerConfirmationGate,
61
+ type McpConfirmDecision,
62
+ } from './modern-confirm.js';
63
+ import type {
64
+ JsonRpcRequest,
65
+ McpHttpRequest,
66
+ McpHttpResponse,
67
+ } from './dispatch.js';
68
+ import { acceptedResponse } from './dispatch.js';
69
+
70
+ /** One validation-chain failure: code, message, status, optional data. */
71
+ interface CheckError {
72
+ code: number;
73
+ msg: string;
74
+ status: number;
75
+ data?: unknown;
76
+ }
77
+
78
+ /** The decoded view of the reserved params._meta keys (V3). */
79
+ export interface ModernRequestMeta {
80
+ version: string;
81
+ versionIsText: boolean;
82
+ versionRaw: unknown;
83
+ clientName?: string;
84
+ clientVersion?: string;
85
+ hasClientInfo: boolean;
86
+ }
87
+
88
+ /** Base64 sentinel delimiters for header values (spec: Value Encoding). */
89
+ const SENTINEL_PREFIX = '=?base64?';
90
+ const SENTINEL_SUFFIX = '?=';
91
+
92
+ /** The 2026-07-28 handler. */
93
+ export class ModernMcpHandler {
94
+ /**
95
+ * The MRTR confirmation strategy, installed only when the mount was
96
+ * given key material. Without a key there is nothing to MAC state
97
+ * with, so every client — elicitation-capable or not — keeps the
98
+ * `X-Confirm-Token` header gate.
99
+ */
100
+ readonly confirmGate?: ElicitationConfirmGate;
101
+
102
+ constructor(
103
+ private readonly bridge: McpBridge,
104
+ private readonly cfg: ResolvedMcpConfig,
105
+ ) {
106
+ if (cfg.confirmationKey !== undefined) {
107
+ this.confirmGate = new ElicitationConfirmGate(cfg.confirmationKey);
108
+ }
109
+ }
110
+
111
+ /**
112
+ * The modern entry point. The validation chain runs in ADR 0042's
113
+ * order V1-V9; the first failure responds and stops. HTTP status is
114
+ * 400/404 only where the spec mandates it — application-level
115
+ * JSON-RPC errors ride HTTP 200, matching legacy's convention.
116
+ */
117
+ async serve(
118
+ req: McpHttpRequest,
119
+ rpc: JsonRpcRequest,
120
+ ): Promise<McpHttpResponse> {
121
+ // Origin allowlist (opt-in): modern path only, before any
122
+ // protocol validation.
123
+ if (!this.originAllowed(req)) {
124
+ return this.writeModernError(rpc, {
125
+ code: MCP_ERR_INVALID_REQUEST,
126
+ msg: 'origin not allowed',
127
+ status: 403,
128
+ });
129
+ }
130
+
131
+ // V1 — jsonrpc member absent or "2.0" (same tolerance as legacy).
132
+ if (rpc.jsonrpc !== undefined && rpc.jsonrpc !== '2.0') {
133
+ return this.writeModernError(rpc, {
134
+ code: MCP_ERR_INVALID_REQUEST,
135
+ msg: 'invalid jsonrpc version',
136
+ status: 400,
137
+ });
138
+ }
139
+
140
+ // V2 — id absent → notification (HTTP 202, empty body, discarded);
141
+ // present id MUST be a string or an integer. null, boolean, float,
142
+ // object, and array ids are all malformed.
143
+ if (rpc.id === undefined) {
144
+ return acceptedResponse();
145
+ }
146
+ if (!validModernRequestId(rpc.id)) {
147
+ return this.writeModernError(rpc, {
148
+ code: MCP_ERR_INVALID_REQUEST,
149
+ msg: `invalid request id: must be a string or integer, got ${rpc.id.raw}`,
150
+ status: 400,
151
+ });
152
+ }
153
+
154
+ // V3 — params._meta carries the required reserved keys.
155
+ const parsed = parseModernMeta(rpc.params);
156
+ if ('error' in parsed) {
157
+ return this.writeModernError(rpc, parsed.error);
158
+ }
159
+ const meta = parsed.meta;
160
+
161
+ // V4 — MCP-Protocol-Version header present and equal to the _meta
162
+ // protocolVersion value. Conflicting duplicates are themselves a
163
+ // mismatch, decided without comparing either value to the body.
164
+ const proto = singleHeaderValue(req, HEADER_MCP_PROTOCOL_VERSION);
165
+ if (!proto.ok) {
166
+ return this.writeModernError(rpc, {
167
+ code: MCP_ERR_HEADER_MISMATCH,
168
+ msg: `${HEADER_MCP_PROTOCOL_VERSION} header sent with conflicting duplicate values`,
169
+ status: 400,
170
+ });
171
+ }
172
+ if (proto.value === '') {
173
+ return this.writeModernError(rpc, {
174
+ code: MCP_ERR_HEADER_MISMATCH,
175
+ msg: `missing ${HEADER_MCP_PROTOCOL_VERSION} header`,
176
+ status: 400,
177
+ });
178
+ }
179
+ // A non-string _meta value can never equal the header string.
180
+ if (!meta.versionIsText || proto.value !== meta.version) {
181
+ return this.writeModernError(rpc, {
182
+ code: MCP_ERR_HEADER_MISMATCH,
183
+ msg:
184
+ `${HEADER_MCP_PROTOCOL_VERSION} header ${JSON.stringify(proto.value)} ` +
185
+ `does not match _meta protocolVersion ${goFormatValue(meta.versionRaw)}`,
186
+ status: 400,
187
+ });
188
+ }
189
+
190
+ // V5 — requested version supported. This handler supports exactly
191
+ // "2026-07-28"; the supported list deliberately excludes
192
+ // "2024-11-05", which is reachable only through its handshake.
193
+ if (meta.version !== MCP_SPEC_2026_07_28) {
194
+ return this.writeModernError(rpc, {
195
+ code: MCP_ERR_UNSUPPORTED_VERSION,
196
+ msg: `unsupported protocol version: ${meta.version}`,
197
+ status: 400,
198
+ data: {
199
+ supported: [MCP_SPEC_2026_07_28],
200
+ requested: meta.versionRaw,
201
+ },
202
+ });
203
+ }
204
+
205
+ // V6 — Mcp-Method header presence and header/body agreement.
206
+ const methodErr = this.validateMethodHeader(req, rpc);
207
+ if (methodErr) return this.writeModernError(rpc, methodErr);
208
+
209
+ // V8 — method routing. V7 (Mcp-Name) and V9 (per-method params)
210
+ // run inside the method handlers.
211
+ switch (rpc.method) {
212
+ case 'server/discover':
213
+ return this.handleDiscover(rpc);
214
+ case 'tools/list':
215
+ return this.handleToolsList(rpc);
216
+ case 'tools/call':
217
+ return this.handleToolsCall(req, rpc, meta);
218
+ default:
219
+ // The tasks extension is not supported: capabilities.extensions
220
+ // is omitted from server/discover, so tasks/* is simply an
221
+ // unknown method (-32601 @ 404), like any other.
222
+ if (isTaskMethod(rpc.method)) {
223
+ return this.writeModernError(rpc, taskMethodNotFound(rpc.method));
224
+ }
225
+ return this.writeModernError(rpc, {
226
+ code: MCP_ERR_METHOD_NOT_FOUND,
227
+ msg: `method not found: ${rpc.method}`,
228
+ status: 404,
229
+ });
230
+ }
231
+ }
232
+
233
+ /**
234
+ * server/discover — the mandatory modern discovery method. Carries
235
+ * no listChanged flag (notifications unimplemented), no extensions
236
+ * map (none supported, which is what makes tasks/* method-not-found),
237
+ * and no instructions.
238
+ */
239
+ private handleDiscover(rpc: JsonRpcRequest): McpHttpResponse {
240
+ const res: Record<string, unknown> = {
241
+ supportedVersions: [MCP_SPEC_2026_07_28],
242
+ capabilities: { tools: {} },
243
+ };
244
+ this.applyCacheHints(res);
245
+ this.stampResultEnvelope(res);
246
+ return writeResult(rpc.id, res, 200);
247
+ }
248
+
249
+ /**
250
+ * Modern tools/list: the same tool envelopes the legacy handler
251
+ * emits (so schema drift between eras cannot happen), wrapped in
252
+ * the modern complete-result envelope with cache hints. Pagination
253
+ * is not implemented — a cursor param is ignored, no nextCursor.
254
+ */
255
+ private handleToolsList(rpc: JsonRpcRequest): McpHttpResponse {
256
+ const tools: Array<Record<string, unknown>> = [];
257
+ for (const leaf of this.bridge.leaves()) {
258
+ if (!isExposed(leaf)) continue;
259
+ tools.push(buildToolEnvelope(leaf));
260
+ }
261
+ const res: Record<string, unknown> = { tools };
262
+ this.applyCacheHints(res);
263
+ this.stampResultEnvelope(res);
264
+ return writeResult(rpc.id, res, 200);
265
+ }
266
+
267
+ /**
268
+ * Modern tools/call: V7, V9, the legacy pre-flight gates, invoke,
269
+ * render. The shared bridge invoke path keeps the policy gate
270
+ * identical across eras — there is no way to reach a leaf here that
271
+ * the legacy path would have blocked. Results carry no cache hints.
272
+ */
273
+ private async handleToolsCall(
274
+ req: McpHttpRequest,
275
+ rpc: JsonRpcRequest,
276
+ meta: ModernRequestMeta,
277
+ ): Promise<McpHttpResponse> {
278
+ // V7 — Mcp-Name agreement, run against a pre-decode peek of
279
+ // params.name so a header failure is reported even when the rest
280
+ // of params is unparseable.
281
+ const peek = rawToolCallName(rpc.params);
282
+ const nameErr = this.validateNameHeader(req, peek);
283
+ if (nameErr) return this.writeModernError(rpc, nameErr);
284
+
285
+ const params = (rpc.params ?? {}) as {
286
+ name?: unknown;
287
+ arguments?: Record<string, unknown>;
288
+ };
289
+ const name = typeof params.name === 'string' ? params.name : '';
290
+
291
+ // V9 — per-method params. Unreachable through a conforming
292
+ // request now that V7 requires a present, non-empty, matching
293
+ // name; kept as a defensive internal check for any future caller
294
+ // that bypasses the V7 gate.
295
+ if (name === '') {
296
+ return writeError(
297
+ rpc.id,
298
+ { code: MCP_ERR_INVALID_PARAMS, message: 'missing tool name' },
299
+ 200,
300
+ );
301
+ }
302
+
303
+ const leaf = resolveLeaf(this.bridge, name);
304
+ if (leaf === undefined || !isExposed(leaf)) {
305
+ return writeError(
306
+ rpc.id,
307
+ { code: MCP_ERR_INVALID_PARAMS, message: `unknown tool: ${name}` },
308
+ 200,
309
+ );
310
+ }
311
+
312
+ // Pre-flight gates, mirroring legacy exactly.
313
+ if (leaf.class?.authRequired && !headerValue(req, 'authorization')) {
314
+ return this.writeCallError(rpc, 'authentication required', 401);
315
+ }
316
+ // Confirmation gate. With a mounted key this is the MRTR
317
+ // elicitation loop, which falls back to the header gate for
318
+ // clients that did not declare form elicitation; without a key it
319
+ // IS the header gate, for everyone. Either way the decision is a
320
+ // pre-flight refusal or an interim prompt, stamped with the modern
321
+ // envelope like every other result on this path.
322
+ const gated = this.confirmationGate(req, leaf, rpc.params);
323
+ if (gated !== undefined) {
324
+ return writeResult(
325
+ rpc.id,
326
+ this.stampResultEnvelope(gated.result),
327
+ gated.status,
328
+ );
329
+ }
330
+
331
+ try {
332
+ const res = await this.bridge.invoke({
333
+ path: [...leaf.path],
334
+ flags: params.arguments,
335
+ meta: {
336
+ surface: SURFACE_MCP,
337
+ requestedAt: new Date(),
338
+ extra: modernInvocationExtra(meta),
339
+ },
340
+ });
341
+ const out = renderCallResult(res);
342
+ if (res.data !== undefined && res.data !== null) {
343
+ out.structuredContent = res.data;
344
+ }
345
+ return writeResult(rpc.id, this.stampResultEnvelope(out), 200);
346
+ } catch (err) {
347
+ if (
348
+ err instanceof UnknownCommandError ||
349
+ err instanceof SurfaceNotEnabledError
350
+ ) {
351
+ return writeError(
352
+ rpc.id,
353
+ { code: MCP_ERR_INVALID_PARAMS, message: `unknown tool: ${name}` },
354
+ 200,
355
+ );
356
+ }
357
+ // DestructiveBlockedError and every other invoke failure are
358
+ // complete isError results at HTTP 200, as on legacy.
359
+ return this.writeCallError(rpc, errorMessage(err), 200);
360
+ }
361
+ }
362
+
363
+ /**
364
+ * Selects and runs the confirmation strategy for one `tools/call`.
365
+ * Returns `undefined` to proceed with the invocation.
366
+ *
367
+ * A leaf that does not require confirmation is never gated. A mount
368
+ * without a `confirmationKey` has no state to MAC, so the header gate
369
+ * applies to every client — this is the byte-for-byte preservation
370
+ * path, identical to what the legacy handler does.
371
+ */
372
+ private confirmationGate(
373
+ req: McpHttpRequest,
374
+ leaf: Leaf,
375
+ params: unknown,
376
+ ): McpConfirmDecision | undefined {
377
+ if (!leaf.class?.requiresConfirmation) return undefined;
378
+ if (this.confirmGate === undefined) return headerConfirmationGate(req);
379
+ return this.confirmGate.evaluate(req, leaf, params);
380
+ }
381
+
382
+ /** V6: Mcp-Method header presence + agreement with the body method. */
383
+ private validateMethodHeader(
384
+ req: McpHttpRequest,
385
+ rpc: JsonRpcRequest,
386
+ ): CheckError | undefined {
387
+ const hdr = singleHeaderValue(req, HEADER_MCP_METHOD);
388
+ if (!hdr.ok) {
389
+ return {
390
+ code: MCP_ERR_HEADER_MISMATCH,
391
+ msg: `${HEADER_MCP_METHOD} header sent with conflicting duplicate values`,
392
+ status: 400,
393
+ };
394
+ }
395
+ if (hdr.value === '') {
396
+ return {
397
+ code: MCP_ERR_HEADER_MISMATCH,
398
+ msg: `missing ${HEADER_MCP_METHOD} header`,
399
+ status: 400,
400
+ };
401
+ }
402
+ if (hdr.value !== rpc.method) {
403
+ return {
404
+ code: MCP_ERR_HEADER_MISMATCH,
405
+ msg:
406
+ `${HEADER_MCP_METHOD} header ${JSON.stringify(hdr.value)} ` +
407
+ `does not match body method ${JSON.stringify(rpc.method)}`,
408
+ status: 400,
409
+ };
410
+ }
411
+ return undefined;
412
+ }
413
+
414
+ /**
415
+ * V7: on tools/call the Mcp-Name header MUST be present, non-empty
416
+ * after Base64-sentinel decoding, and byte-equal to params.name,
417
+ * which MUST itself be present. Any violation is a header failure
418
+ * (-32020 @ 400), decided ahead of any body-shape check: headers
419
+ * are the routing signal gateways trust without parsing the body,
420
+ * so an empty or contradicted signal is malformed at the header
421
+ * layer.
422
+ */
423
+ private validateNameHeader(
424
+ req: McpHttpRequest,
425
+ peek: { name: string; present: boolean; isString: boolean },
426
+ ): CheckError | undefined {
427
+ const hdr = singleHeaderValue(req, HEADER_MCP_NAME);
428
+ if (!hdr.ok) {
429
+ return {
430
+ code: MCP_ERR_HEADER_MISMATCH,
431
+ msg: `${HEADER_MCP_NAME} header sent with conflicting duplicate values`,
432
+ status: 400,
433
+ };
434
+ }
435
+ if (hdr.value === '') {
436
+ return {
437
+ code: MCP_ERR_HEADER_MISMATCH,
438
+ msg: `missing ${HEADER_MCP_NAME} header`,
439
+ status: 400,
440
+ };
441
+ }
442
+ const decoded = decodeMcpSentinel(hdr.value);
443
+ if (decoded === undefined) {
444
+ return {
445
+ code: MCP_ERR_HEADER_MISMATCH,
446
+ msg: `${HEADER_MCP_NAME} header value is not valid base64-sentinel encoded`,
447
+ status: 400,
448
+ };
449
+ }
450
+ if (decoded === '') {
451
+ return {
452
+ code: MCP_ERR_HEADER_MISMATCH,
453
+ msg: `${HEADER_MCP_NAME} header decodes to an empty value`,
454
+ status: 400,
455
+ };
456
+ }
457
+ if (!peek.present) {
458
+ return {
459
+ code: MCP_ERR_HEADER_MISMATCH,
460
+ msg: `${HEADER_MCP_NAME} header present but body params.name is absent`,
461
+ status: 400,
462
+ };
463
+ }
464
+ if (!peek.isString) {
465
+ // params.name exists but is not a JSON string: V7 cannot
466
+ // evaluate agreement, so it defers to V9's params decode.
467
+ return undefined;
468
+ }
469
+ if (decoded !== peek.name) {
470
+ return {
471
+ code: MCP_ERR_HEADER_MISMATCH,
472
+ msg:
473
+ `${HEADER_MCP_NAME} header ${JSON.stringify(decoded)} ` +
474
+ `does not match body params.name ${JSON.stringify(peek.name)}`,
475
+ status: 400,
476
+ };
477
+ }
478
+ return undefined;
479
+ }
480
+
481
+ /**
482
+ * Adds the members every modern result envelope carries: resultType
483
+ * and a result-level _meta with serverInfo built from the mount's
484
+ * configured identity. A producer that already chose a resultType
485
+ * keeps it (the MRTR confirmation gate stamps "input_required").
486
+ */
487
+ stampResultEnvelope(m: Record<string, unknown>): Record<string, unknown> {
488
+ if (!('resultType' in m)) {
489
+ m.resultType = RESULT_TYPE_COMPLETE;
490
+ }
491
+ m._meta = {
492
+ [META_KEY_SERVER_INFO]: {
493
+ name: this.cfg.serverName,
494
+ version: this.cfg.serverVersion,
495
+ },
496
+ };
497
+ return m;
498
+ }
499
+
500
+ /**
501
+ * Adds ttlMs and cacheScope to a cacheable complete-result —
502
+ * server/discover and tools/list only; tools/call carries none.
503
+ * Defaults are ttlMs 0 (immediately stale: the leaf set can mutate
504
+ * at runtime and no list_changed notification exists) and
505
+ * cacheScope "private".
506
+ */
507
+ applyCacheHints(m: Record<string, unknown>): Record<string, unknown> {
508
+ m.ttlMs = this.cfg.cacheTtlMs;
509
+ m.cacheScope = this.cfg.cacheScope;
510
+ return m;
511
+ }
512
+
513
+ /** Opt-in Origin allowlist; a request without Origin is never refused. */
514
+ private originAllowed(req: McpHttpRequest): boolean {
515
+ if (this.cfg.originAllowlist.length === 0) return true;
516
+ const origin = headerValue(req, 'origin');
517
+ if (!origin) return true;
518
+ return this.cfg.originAllowlist.includes(origin);
519
+ }
520
+
521
+ /**
522
+ * Writes a modern JSON-RPC error. When the rejected request's
523
+ * method is "initialize" the message additionally names the
524
+ * supported versions: a legacy client has no fall-forward
525
+ * mechanism, so the version list in the error text is its only
526
+ * recovery hint.
527
+ */
528
+ private writeModernError(
529
+ rpc: JsonRpcRequest,
530
+ e: CheckError,
531
+ ): McpHttpResponse {
532
+ let msg = e.msg;
533
+ if (rpc.method === 'initialize') {
534
+ msg += `; supported protocol versions: ${MCP_SPEC_2026_07_28}`;
535
+ }
536
+ return writeError(
537
+ rpc.id,
538
+ { code: e.code, message: msg, data: e.data },
539
+ e.status,
540
+ );
541
+ }
542
+
543
+ /** An isError tools/call result with the modern envelope stamped on. */
544
+ private writeCallError(
545
+ rpc: JsonRpcRequest,
546
+ msg: string,
547
+ status: number,
548
+ ): McpHttpResponse {
549
+ return writeResult(
550
+ rpc.id,
551
+ this.stampResultEnvelope(errorResultBlock(msg)),
552
+ status,
553
+ );
554
+ }
555
+ }
556
+
557
+ /**
558
+ * Reduces all occurrences of a header to one value for comparison
559
+ * against the body. Sent once, or several times with byte-identical
560
+ * values (benign proxy duplication), resolves to that value. Sent
561
+ * several times with differing values is a validation failure in its
562
+ * own right — conflicting duplicates are exactly the
563
+ * multiple-sources-of-truth hazard header/body validation closes — so
564
+ * ok=false and the caller rejects without comparing anything.
565
+ */
566
+ export function singleHeaderValue(
567
+ req: McpHttpRequest,
568
+ name: string,
569
+ ): { value: string; ok: boolean } {
570
+ const vals = headerValues(req, name);
571
+ if (vals.length === 0) return { value: '', ok: true };
572
+ if (vals.length === 1) return { value: vals[0], ok: true };
573
+ for (const v of vals.slice(1)) {
574
+ if (v !== vals[0]) return { value: '', ok: false };
575
+ }
576
+ return { value: vals[0], ok: true };
577
+ }
578
+
579
+ /**
580
+ * V2's id rule: a JSON string, or a JSON number with no fractional
581
+ * part. Base JSON-RPC also allows null, but this revision forbids it;
582
+ * boolean, object, and array ids are rejected the same way.
583
+ */
584
+ export function validModernRequestId(id: RawJSON): boolean {
585
+ const raw = id.raw.trim();
586
+ if (raw === 'null') return false;
587
+ let parsed: unknown;
588
+ try {
589
+ parsed = JSON.parse(raw);
590
+ } catch {
591
+ return false;
592
+ }
593
+ if (typeof parsed === 'string') return true;
594
+ if (typeof parsed === 'number') return Number.isInteger(parsed);
595
+ return false;
596
+ }
597
+
598
+ /**
599
+ * V3: decodes the reserved params._meta keys. protocolVersion and
600
+ * clientCapabilities are required; clientInfo is optional. A missing
601
+ * or non-object params/_meta fails the same way as missing keys.
602
+ */
603
+ export function parseModernMeta(
604
+ params: unknown,
605
+ ): { meta: ModernRequestMeta } | { error: CheckError } {
606
+ const fail = (msg: string): { error: CheckError } => ({
607
+ error: { code: MCP_ERR_INVALID_PARAMS, msg, status: 400 },
608
+ });
609
+
610
+ if (params === undefined || params === null || typeof params !== 'object') {
611
+ return fail('missing required params._meta');
612
+ }
613
+ const metaRaw = (params as Record<string, unknown>)._meta;
614
+ if (metaRaw === undefined || metaRaw === null || typeof metaRaw !== 'object' || Array.isArray(metaRaw)) {
615
+ return fail('missing required params._meta');
616
+ }
617
+ const metaObj = metaRaw as Record<string, unknown>;
618
+ if (!(META_KEY_PROTOCOL_VERSION in metaObj)) {
619
+ return fail(`missing required _meta key: ${META_KEY_PROTOCOL_VERSION}`);
620
+ }
621
+ if (!(META_KEY_CLIENT_CAPABILITIES in metaObj)) {
622
+ return fail(`missing required _meta key: ${META_KEY_CLIENT_CAPABILITIES}`);
623
+ }
624
+
625
+ const verRaw = metaObj[META_KEY_PROTOCOL_VERSION];
626
+ const meta: ModernRequestMeta = {
627
+ version: typeof verRaw === 'string' ? verRaw : '',
628
+ versionIsText: typeof verRaw === 'string',
629
+ versionRaw: verRaw,
630
+ hasClientInfo: false,
631
+ };
632
+
633
+ // clientInfo only feeds audit metadata; a value that is not an
634
+ // object is treated as absent rather than rejected, since V3 does
635
+ // not require the key at all.
636
+ const ci = metaObj[META_KEY_CLIENT_INFO];
637
+ if (ci !== undefined && ci !== null && typeof ci === 'object' && !Array.isArray(ci)) {
638
+ const obj = ci as Record<string, unknown>;
639
+ meta.hasClientInfo = true;
640
+ meta.clientName = typeof obj.name === 'string' ? obj.name : '';
641
+ meta.clientVersion = typeof obj.version === 'string' ? obj.version : '';
642
+ }
643
+ return { meta };
644
+ }
645
+
646
+ /**
647
+ * Peeks params.name out of a tools/call body without requiring the
648
+ * rest of params to decode, so V7 can run independently of whatever
649
+ * else is wrong with the body. `present` reports whether params is an
650
+ * object carrying a "name" key at all; `isString` distinguishes a
651
+ * non-string value, which V7 defers to V9 rather than treating as
652
+ * absent.
653
+ */
654
+ export function rawToolCallName(params: unknown): {
655
+ name: string;
656
+ present: boolean;
657
+ isString: boolean;
658
+ } {
659
+ if (params === undefined || params === null || typeof params !== 'object' || Array.isArray(params)) {
660
+ return { name: '', present: false, isString: false };
661
+ }
662
+ const obj = params as Record<string, unknown>;
663
+ if (!('name' in obj)) return { name: '', present: false, isString: false };
664
+ const v = obj.name;
665
+ if (typeof v !== 'string') return { name: '', present: true, isString: false };
666
+ return { name: v, present: true, isString: true };
667
+ }
668
+
669
+ /**
670
+ * Decodes a header value that may carry the Base64 sentinel encoding.
671
+ * A value that is not sentinel-wrapped is returned unchanged.
672
+ * A wrapped value that fails to decode returns undefined so the
673
+ * caller fails closed: the spec requires decoding before comparing,
674
+ * and a malformed encoding can never legitimately match the body.
675
+ * A value that merely looks like the sentinel is always treated as
676
+ * encoded, per spec.
677
+ */
678
+ export function decodeMcpSentinel(v: string): string | undefined {
679
+ if (!v.startsWith(SENTINEL_PREFIX) || !v.endsWith(SENTINEL_SUFFIX)) {
680
+ return v;
681
+ }
682
+ const inner = v.slice(SENTINEL_PREFIX.length, v.length - SENTINEL_SUFFIX.length);
683
+ // Reject anything that is not strict, canonical standard base64:
684
+ // Go's base64.StdEncoding.DecodeString errors on bad padding and
685
+ // non-alphabet bytes, whereas Buffer.from is lenient.
686
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(inner) || inner.length % 4 !== 0) {
687
+ return undefined;
688
+ }
689
+ const buf = Buffer.from(inner, 'base64');
690
+ if (buf.toString('base64') !== inner) return undefined;
691
+ return buf.toString('utf8');
692
+ }
693
+
694
+ /**
695
+ * The Meta.extra audit bag for a modern invocation: the spec version
696
+ * always, and the client identity when the request carried clientInfo.
697
+ */
698
+ export function modernInvocationExtra(
699
+ meta: ModernRequestMeta,
700
+ ): Record<string, string> {
701
+ const extra: Record<string, string> = {
702
+ mcp_spec_version: MCP_SPEC_2026_07_28,
703
+ };
704
+ if (meta.hasClientInfo) {
705
+ extra.mcp_client_name = meta.clientName ?? '';
706
+ extra.mcp_client_version = meta.clientVersion ?? '';
707
+ }
708
+ return extra;
709
+ }
710
+
711
+ /**
712
+ * Renders a decoded JSON value the way Go's %v verb does, used in the
713
+ * V4 mismatch message where the _meta value may be of any JSON type.
714
+ */
715
+ function goFormatValue(v: unknown): string {
716
+ if (v === null || v === undefined) return '<nil>';
717
+ if (typeof v === 'string') return v;
718
+ if (typeof v === 'boolean') return v ? 'true' : 'false';
719
+ if (typeof v === 'number') return String(v);
720
+ return JSON.stringify(v);
721
+ }
722
+
723
+ export { DestructiveBlockedError };