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