@hop-top/kit 0.5.0-alpha.0 → 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 +262 -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 -885
- 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 +18 -322
- 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 +236 -46
- 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 +142 -0
- package/src/tui/parity.ts +59 -13
- 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
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module mcp/dispatch
|
|
3
|
+
* @package @hop-top/kit
|
|
4
|
+
*
|
|
5
|
+
* Era detection + dispatch for the dual-spec MCP surface, plus the
|
|
6
|
+
* framework-free handler export.
|
|
7
|
+
*
|
|
8
|
+
* Hosting model (serve-mcp-from-any-sdk.md): this module exports a
|
|
9
|
+
* transport-agnostic request handler, not a server. Binding it to
|
|
10
|
+
* node:http, hono, express, fastify, or a Worker is the adopter's
|
|
11
|
+
* job — kit does not own the adopter's HTTP stack, and a pure
|
|
12
|
+
* request→response function is directly testable against the wire
|
|
13
|
+
* fixtures with no socket.
|
|
14
|
+
*
|
|
15
|
+
* Detection implements expose-cli-over-mcp.md's normative rules literally: the
|
|
16
|
+
* marker set M1-M4, the two deliberate non-markers, and the
|
|
17
|
+
* precedence chain D1-D4. It deliberately does NOT delegate to the
|
|
18
|
+
* v2 SDK's own `classifyInboundRequest`: that classifier treats a
|
|
19
|
+
* modern `MCP-Protocol-Version` header as a routing signal and
|
|
20
|
+
* routes `initialize`-plus-modern-envelope to the modern era, both
|
|
21
|
+
* of which contradict those rules (and the wire fixtures, which are the
|
|
22
|
+
* parity contract). The SDK is still the source of the protocol
|
|
23
|
+
* constants and error codes — see types.ts.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import {
|
|
27
|
+
MCP_ERR_INTERNAL,
|
|
28
|
+
META_KEY_PROTOCOL_VERSION,
|
|
29
|
+
HEADER_MCP_METHOD,
|
|
30
|
+
HEADER_MCP_NAME,
|
|
31
|
+
checkToolNameSeparator,
|
|
32
|
+
RawJSON,
|
|
33
|
+
resolveMcpConfig,
|
|
34
|
+
type McpBridge,
|
|
35
|
+
type McpMountOptions,
|
|
36
|
+
type ResolvedMcpConfig,
|
|
37
|
+
} from './types.js';
|
|
38
|
+
import {
|
|
39
|
+
headerValues,
|
|
40
|
+
LegacyMcpHandler,
|
|
41
|
+
parseErrorResponse,
|
|
42
|
+
writeError,
|
|
43
|
+
} from './legacy.js';
|
|
44
|
+
import { ModernMcpHandler } from './modern.js';
|
|
45
|
+
|
|
46
|
+
// --- normalized request / response --------------------------------------
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* A normalized inbound request: method, headers, and body bytes. A
|
|
50
|
+
* header may repeat, which the modern header checks treat as
|
|
51
|
+
* significant, so values may be an array.
|
|
52
|
+
*/
|
|
53
|
+
export interface McpHttpRequest {
|
|
54
|
+
/** HTTP method, e.g. "POST". */
|
|
55
|
+
method: string;
|
|
56
|
+
/** Header names are matched case-insensitively. */
|
|
57
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
58
|
+
/** Raw body bytes, exactly as received — never re-encoded. */
|
|
59
|
+
body?: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A normalized response: status, headers, and body bytes. */
|
|
63
|
+
export interface McpHttpResponse {
|
|
64
|
+
status: number;
|
|
65
|
+
headers: Record<string, string>;
|
|
66
|
+
body: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Builds a JSON response with the surface's standard content type. */
|
|
70
|
+
export function jsonResponse(status: number, body: string): McpHttpResponse {
|
|
71
|
+
return {
|
|
72
|
+
status,
|
|
73
|
+
headers: { 'Content-Type': 'application/json' },
|
|
74
|
+
body,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The 202 a modern notification receives: empty body, not processed. */
|
|
79
|
+
export function acceptedResponse(): McpHttpResponse {
|
|
80
|
+
return { status: 202, headers: {}, body: '' };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// --- parsed request -----------------------------------------------------
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* A decoded JSON-RPC request envelope. `id` is kept as a raw JSON
|
|
87
|
+
* fragment so it round-trips byte-for-byte (Go uses json.RawMessage
|
|
88
|
+
* for exactly this reason), and its absence is distinguishable from
|
|
89
|
+
* an explicit null.
|
|
90
|
+
*/
|
|
91
|
+
export interface JsonRpcRequest {
|
|
92
|
+
jsonrpc?: string;
|
|
93
|
+
id?: RawJSON;
|
|
94
|
+
method: string;
|
|
95
|
+
params?: unknown;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Which handler a request routes to. */
|
|
99
|
+
export type McpEra = 'legacy' | 'modern';
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The binding a dispatcher serves. `http` (Streamable HTTP) validates
|
|
103
|
+
* the 2026-07-28 routing headers against the body; `stdio` has no
|
|
104
|
+
* header layer, so the body is the only source of truth.
|
|
105
|
+
*/
|
|
106
|
+
export type McpTransport = 'http' | 'stdio';
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Implements per-request era detection, precedence D1-D4.
|
|
110
|
+
* Never fails — it only classifies an already-parsed request; D1
|
|
111
|
+
* (parse) is the caller's responsibility.
|
|
112
|
+
*
|
|
113
|
+
* Markers:
|
|
114
|
+
* M1 — Mcp-Method header present
|
|
115
|
+
* M2 — Mcp-Name header present
|
|
116
|
+
* M3 — params._meta contains the reserved protocolVersion key
|
|
117
|
+
* (key presence only; the value is not inspected here)
|
|
118
|
+
* M4 — method == "server/discover"
|
|
119
|
+
*
|
|
120
|
+
* Deliberate non-markers, both of which are the subtle part and the
|
|
121
|
+
* most likely source of silent divergence:
|
|
122
|
+
* - Bare params._meta. 2024-11-05 clients legitimately send
|
|
123
|
+
* _meta.progressToken and OTel traceparent; only the reserved
|
|
124
|
+
* protocolVersion key signals modern.
|
|
125
|
+
* - The MCP-Protocol-Version header, at any value. It predates
|
|
126
|
+
* 2026-07-28, so clients that negotiated down to legacy send it
|
|
127
|
+
* on every subsequent request; treating it as a modern signal
|
|
128
|
+
* would serve their handshake and then brick the session.
|
|
129
|
+
*/
|
|
130
|
+
export function detectMcpEra(
|
|
131
|
+
req: McpHttpRequest,
|
|
132
|
+
rpc: JsonRpcRequest,
|
|
133
|
+
): McpEra {
|
|
134
|
+
// D2 — initialize is legacy, unconditionally, even when modern
|
|
135
|
+
// markers are present. The spec's dual-era rule says initialize
|
|
136
|
+
// selects legacy semantics; a confused client gets a working legacy
|
|
137
|
+
// handshake, the most recoverable outcome.
|
|
138
|
+
if (rpc.method === 'initialize') return 'legacy';
|
|
139
|
+
|
|
140
|
+
// M4 — method == "server/discover".
|
|
141
|
+
if (rpc.method === 'server/discover') return 'modern';
|
|
142
|
+
|
|
143
|
+
// M1 / M2 — header presence.
|
|
144
|
+
if (headerValues(req, HEADER_MCP_METHOD).length > 0) return 'modern';
|
|
145
|
+
if (headerValues(req, HEADER_MCP_NAME).length > 0) return 'modern';
|
|
146
|
+
|
|
147
|
+
// M3 — params._meta carries the reserved protocolVersion key.
|
|
148
|
+
if (hasModernMetaMarker(rpc.params)) return 'modern';
|
|
149
|
+
|
|
150
|
+
// D4 — no markers: legacy. This is the byte-for-byte preservation
|
|
151
|
+
// path: every request a legacy client can send takes today's exact
|
|
152
|
+
// code path.
|
|
153
|
+
return 'legacy';
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* M3: whether params._meta carries the reserved protocolVersion key.
|
|
158
|
+
* Only key presence is tested; the value is never inspected at
|
|
159
|
+
* detection time. Malformed or non-object params/_meta are treated as
|
|
160
|
+
* "no marker" — detection never fails, and shape errors are the
|
|
161
|
+
* handlers' business.
|
|
162
|
+
*/
|
|
163
|
+
export function hasModernMetaMarker(params: unknown): boolean {
|
|
164
|
+
if (params === null || typeof params !== 'object' || Array.isArray(params)) {
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
const meta = (params as Record<string, unknown>)._meta;
|
|
168
|
+
if (meta === null || typeof meta !== 'object' || Array.isArray(meta)) {
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
return META_KEY_PROTOCOL_VERSION in (meta as Record<string, unknown>);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// --- handler ------------------------------------------------------------
|
|
175
|
+
|
|
176
|
+
/** A framework-free MCP request handler. */
|
|
177
|
+
export type McpHandler = (
|
|
178
|
+
req: McpHttpRequest,
|
|
179
|
+
) => Promise<McpHttpResponse>;
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Where createMcpHandler records how to rebuild its dispatcher for
|
|
183
|
+
* another transport, so serveStdio can drive a handler's own bridge and
|
|
184
|
+
* mount options without fabricating HTTP headers.
|
|
185
|
+
*/
|
|
186
|
+
export const MCP_DISPATCHER_FACTORY: unique symbol = Symbol.for(
|
|
187
|
+
'hop-top/kit/mcp/dispatcher-factory',
|
|
188
|
+
);
|
|
189
|
+
|
|
190
|
+
/** A handler built by createMcpHandler. */
|
|
191
|
+
interface FactoryHandler extends McpHandler {
|
|
192
|
+
[MCP_DISPATCHER_FACTORY]?: (transport: McpTransport) => McpDispatcher;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* The dispatcher factory createMcpHandler attached to `handler`, or
|
|
197
|
+
* undefined for a handler built some other way.
|
|
198
|
+
*/
|
|
199
|
+
export function dispatcherFactoryOf(
|
|
200
|
+
handler: McpHandler,
|
|
201
|
+
): ((transport: McpTransport) => McpDispatcher) | undefined {
|
|
202
|
+
return (handler as FactoryHandler)[MCP_DISPATCHER_FACTORY];
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Builds the MCP handler for a bridge. Mirrors Go's
|
|
207
|
+
* `MountMCP(bridge, router, opts...)`, minus the router: the caller
|
|
208
|
+
* binds the returned function to whatever HTTP stack it uses.
|
|
209
|
+
*
|
|
210
|
+
* Defaults match Go exactly: both eras enabled, path "/mcp", empty
|
|
211
|
+
* origin allowlist, cache hints ttlMs=0 / cacheScope="private".
|
|
212
|
+
* The two mount-time errors are reproduced rather than absorbed —
|
|
213
|
+
* an explicit empty spec-version set, and a negative ttl or
|
|
214
|
+
* unrecognized cache scope, both throw here.
|
|
215
|
+
*/
|
|
216
|
+
export function createMcpHandler(
|
|
217
|
+
bridge: McpBridge,
|
|
218
|
+
opts: McpMountOptions = {},
|
|
219
|
+
): McpHandler {
|
|
220
|
+
const cfg = resolveMcpConfig(opts);
|
|
221
|
+
const dispatcher = new McpDispatcher(bridge, cfg);
|
|
222
|
+
const handler: FactoryHandler = (req) => dispatcher.handle(req);
|
|
223
|
+
handler[MCP_DISPATCHER_FACTORY] = (transport) =>
|
|
224
|
+
new McpDispatcher(bridge, cfg, transport);
|
|
225
|
+
return handler;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** The resolved mount config for a handler, for adopters that need it. */
|
|
229
|
+
export function mcpMountConfig(
|
|
230
|
+
opts: McpMountOptions = {},
|
|
231
|
+
): ResolvedMcpConfig {
|
|
232
|
+
return resolveMcpConfig(opts);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Routes each request to exactly one era's handler. Holds no mutable
|
|
237
|
+
* per-request state; both handlers are safe to share concurrently.
|
|
238
|
+
*/
|
|
239
|
+
export class McpDispatcher {
|
|
240
|
+
private readonly legacy: LegacyMcpHandler;
|
|
241
|
+
private readonly modern: ModernMcpHandler;
|
|
242
|
+
|
|
243
|
+
constructor(
|
|
244
|
+
bridge: McpBridge,
|
|
245
|
+
private readonly cfg: ResolvedMcpConfig,
|
|
246
|
+
transport: McpTransport = 'http',
|
|
247
|
+
) {
|
|
248
|
+
checkToolNameSeparator(bridge.leaves(), cfg.toolNameSeparator);
|
|
249
|
+
this.legacy = new LegacyMcpHandler(bridge, cfg);
|
|
250
|
+
this.modern = new ModernMcpHandler(bridge, cfg, transport);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async handle(req: McpHttpRequest): Promise<McpHttpResponse> {
|
|
254
|
+
const verb = (req.method || 'POST').toUpperCase();
|
|
255
|
+
if (verb !== 'POST') {
|
|
256
|
+
// GET and DELETE answer 405 when the modern era is enabled
|
|
257
|
+
// (spec SHOULD for post-session servers). With only the legacy
|
|
258
|
+
// era mounted there is no such route at all, matching Go, where
|
|
259
|
+
// those verbs are simply never registered.
|
|
260
|
+
if (this.cfg.modernEnabled && (verb === 'GET' || verb === 'DELETE')) {
|
|
261
|
+
return methodNotAllowedResponse();
|
|
262
|
+
}
|
|
263
|
+
return methodNotAllowedResponse();
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// D1 — read and parse the body once. An unreadable body is
|
|
267
|
+
// -32603 @ 400; unparseable JSON is -32700 @ 400 — both
|
|
268
|
+
// byte-identical to the legacy responses, regardless of any
|
|
269
|
+
// headers present.
|
|
270
|
+
const body = req.body;
|
|
271
|
+
if (body === undefined) {
|
|
272
|
+
return writeError(
|
|
273
|
+
undefined,
|
|
274
|
+
{
|
|
275
|
+
code: MCP_ERR_INTERNAL,
|
|
276
|
+
message: 'read request body: unexpected EOF',
|
|
277
|
+
},
|
|
278
|
+
400,
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
let rpc: JsonRpcRequest;
|
|
283
|
+
try {
|
|
284
|
+
rpc = parseJsonRpcRequest(body);
|
|
285
|
+
} catch {
|
|
286
|
+
return parseErrorResponse(body);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
return this.dispatch(req, rpc);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Routes one already-parsed request to its era's handler (D2-D4).
|
|
294
|
+
* The transport-neutral core behind `handle`; stdio calls it directly
|
|
295
|
+
* after doing its own framing and parsing.
|
|
296
|
+
*/
|
|
297
|
+
dispatch(req: McpHttpRequest, rpc: JsonRpcRequest): Promise<McpHttpResponse> {
|
|
298
|
+
// Modern-only mounts route everything to the modern handler and
|
|
299
|
+
// handle it per the normal V1-V9 order — no special-casing of
|
|
300
|
+
// initialize anywhere, since D2 exists to hand a confused client
|
|
301
|
+
// to a legacy handler that is not mounted here.
|
|
302
|
+
if (this.cfg.modernEnabled && !this.cfg.legacyEnabled) {
|
|
303
|
+
return this.modern.serve(req, rpc);
|
|
304
|
+
}
|
|
305
|
+
// Legacy-only mounts ignore markers exactly as the pre-dual-spec
|
|
306
|
+
// surface did.
|
|
307
|
+
if (this.cfg.legacyEnabled && !this.cfg.modernEnabled) {
|
|
308
|
+
return this.legacy.serve(req, rpc);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
switch (detectMcpEra(req, rpc)) {
|
|
312
|
+
case 'modern':
|
|
313
|
+
return this.modern.serve(req, rpc);
|
|
314
|
+
default:
|
|
315
|
+
return this.legacy.serve(req, rpc);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** The 405 GET/DELETE answer at the mount path. */
|
|
321
|
+
export function methodNotAllowedResponse(): McpHttpResponse {
|
|
322
|
+
return jsonResponse(
|
|
323
|
+
405,
|
|
324
|
+
'{"jsonrpc":"2.0","error":{"code":-32600,"message":"method not allowed"}}\n',
|
|
325
|
+
);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Parses one JSON-RPC request, preserving the `id` as raw bytes.
|
|
330
|
+
* Throws on unparseable JSON so the caller can render D1's -32700.
|
|
331
|
+
*/
|
|
332
|
+
export function parseJsonRpcRequest(body: string): JsonRpcRequest {
|
|
333
|
+
const decoded: unknown = JSON.parse(body);
|
|
334
|
+
if (decoded === null || typeof decoded !== 'object' || Array.isArray(decoded)) {
|
|
335
|
+
// Go decodes a non-object body into its request struct and fails,
|
|
336
|
+
// which surfaces as a parse error at the same place.
|
|
337
|
+
throw new SyntaxError('not a JSON-RPC object');
|
|
338
|
+
}
|
|
339
|
+
const obj = decoded as Record<string, unknown>;
|
|
340
|
+
const out: JsonRpcRequest = {
|
|
341
|
+
method: typeof obj.method === 'string' ? obj.method : '',
|
|
342
|
+
};
|
|
343
|
+
if (typeof obj.jsonrpc === 'string') out.jsonrpc = obj.jsonrpc;
|
|
344
|
+
if ('id' in obj) out.id = new RawJSON(rawIdBytes(body, obj.id));
|
|
345
|
+
if ('params' in obj) out.params = obj.params;
|
|
346
|
+
return out;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Re-serializes the request id. The id shapes JSON-RPC permits
|
|
351
|
+
* (string, number, null) all round-trip identically through
|
|
352
|
+
* JSON.stringify, which is what Go's json.RawMessage echo produces
|
|
353
|
+
* for the same inputs. `_body` is accepted so a future
|
|
354
|
+
* exactness-sensitive change (e.g. preserving a number's original
|
|
355
|
+
* literal spelling) has the source text to work from.
|
|
356
|
+
*/
|
|
357
|
+
function rawIdBytes(_body: string, id: unknown): string {
|
|
358
|
+
return JSON.stringify(id) ?? 'null';
|
|
359
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The kit/auth-required gate on both eras: only the mount's verifier
|
|
3
|
+
* establishes a caller. An Authorization header is presence, not
|
|
4
|
+
* verification, and a caller or scopes the request claims never
|
|
5
|
+
* become identity.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { describe, expect, it } from 'vitest';
|
|
9
|
+
|
|
10
|
+
import { createMcpHandler, type McpHttpRequest } from './dispatch.js';
|
|
11
|
+
import { headerValue } from './legacy.js';
|
|
12
|
+
import { legacyLockBridge, modernLockBridge } from './testtree.js';
|
|
13
|
+
import type {
|
|
14
|
+
Invocation,
|
|
15
|
+
McpBridge,
|
|
16
|
+
McpMountOptions,
|
|
17
|
+
McpVerifier,
|
|
18
|
+
} from './types.js';
|
|
19
|
+
|
|
20
|
+
const MODERN_META = {
|
|
21
|
+
'io.modelcontextprotocol/clientCapabilities': {},
|
|
22
|
+
'io.modelcontextprotocol/protocolVersion': '2026-07-28',
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** A bridge that records every invocation it runs. */
|
|
26
|
+
function recording(inner: McpBridge): { bridge: McpBridge; calls: Invocation[] } {
|
|
27
|
+
const calls: Invocation[] = [];
|
|
28
|
+
return {
|
|
29
|
+
calls,
|
|
30
|
+
bridge: {
|
|
31
|
+
leaves: () => inner.leaves(),
|
|
32
|
+
invoke(inv) {
|
|
33
|
+
calls.push(inv);
|
|
34
|
+
return inner.invoke(inv);
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Accepts exactly `Bearer good` as alice in acme with two scopes. */
|
|
41
|
+
const verifyGood: McpVerifier = (req) =>
|
|
42
|
+
headerValue(req, 'authorization') === 'Bearer good'
|
|
43
|
+
? { caller: 'alice', tenant: 'acme', scopes: ['read', 'write'] }
|
|
44
|
+
: null;
|
|
45
|
+
|
|
46
|
+
type Era = 'legacy' | 'modern';
|
|
47
|
+
|
|
48
|
+
function call(
|
|
49
|
+
era: Era,
|
|
50
|
+
name: string,
|
|
51
|
+
headers: Record<string, string> = {},
|
|
52
|
+
extraParams: Record<string, unknown> = {},
|
|
53
|
+
): McpHttpRequest {
|
|
54
|
+
if (era === 'legacy') {
|
|
55
|
+
return {
|
|
56
|
+
method: 'POST',
|
|
57
|
+
headers,
|
|
58
|
+
body: JSON.stringify({
|
|
59
|
+
jsonrpc: '2.0',
|
|
60
|
+
id: 1,
|
|
61
|
+
method: 'tools/call',
|
|
62
|
+
params: { name, ...extraParams },
|
|
63
|
+
}),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
const { _meta: claimed, ...rest } = extraParams as { _meta?: object };
|
|
67
|
+
return {
|
|
68
|
+
method: 'POST',
|
|
69
|
+
headers: {
|
|
70
|
+
'MCP-Protocol-Version': '2026-07-28',
|
|
71
|
+
'Mcp-Method': 'tools/call',
|
|
72
|
+
'Mcp-Name': name,
|
|
73
|
+
...headers,
|
|
74
|
+
},
|
|
75
|
+
body: JSON.stringify({
|
|
76
|
+
jsonrpc: '2.0',
|
|
77
|
+
id: 1,
|
|
78
|
+
method: 'tools/call',
|
|
79
|
+
params: { name, ...rest, _meta: { ...MODERN_META, ...(claimed ?? {}) } },
|
|
80
|
+
}),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function mount(era: Era, opts: McpMountOptions = {}) {
|
|
85
|
+
const rec = recording(era === 'legacy' ? legacyLockBridge() : modernLockBridge());
|
|
86
|
+
return { handler: createMcpHandler(rec.bridge, opts), calls: rec.calls };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const CLAIMS = { caller: 'admin', tenant: 'root', scopes: ['admin'] };
|
|
90
|
+
|
|
91
|
+
for (const era of ['legacy', 'modern'] as const) {
|
|
92
|
+
describe(`${era} tools/call auth gate`, () => {
|
|
93
|
+
it('refuses an auth-required leaf on a bare Authorization header', async () => {
|
|
94
|
+
const { handler, calls } = mount(era);
|
|
95
|
+
const res = await handler(
|
|
96
|
+
call(era, 'secret', { Authorization: 'Bearer anything' }, { _meta: CLAIMS }),
|
|
97
|
+
);
|
|
98
|
+
expect(res.status).toBe(401);
|
|
99
|
+
expect(res.headers['WWW-Authenticate']).toBe('Bearer');
|
|
100
|
+
expect(res.body).toContain('"text":"authentication required"');
|
|
101
|
+
expect(res.body).toContain('"isError":true');
|
|
102
|
+
expect(calls).toHaveLength(0);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('refuses when the verifier refuses the credential', async () => {
|
|
106
|
+
const { handler, calls } = mount(era, { verifier: verifyGood });
|
|
107
|
+
const res = await handler(call(era, 'secret', { Authorization: 'Bearer bad' }));
|
|
108
|
+
expect(res.status).toBe(401);
|
|
109
|
+
expect(res.headers['WWW-Authenticate']).toBe('Bearer');
|
|
110
|
+
expect(calls).toHaveLength(0);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it('refuses when the verifier throws', async () => {
|
|
114
|
+
const { handler, calls } = mount(era, {
|
|
115
|
+
verifier: () => {
|
|
116
|
+
throw new Error('verifier down');
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
const res = await handler(call(era, 'secret', { Authorization: 'Bearer good' }));
|
|
120
|
+
expect(res.status).toBe(401);
|
|
121
|
+
expect(calls).toHaveLength(0);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('admits once the verifier establishes the caller, async included', async () => {
|
|
125
|
+
const { handler, calls } = mount(era, {
|
|
126
|
+
verifier: async (req) => verifyGood(req),
|
|
127
|
+
});
|
|
128
|
+
const res = await handler(
|
|
129
|
+
call(era, 'secret', { Authorization: 'Bearer good' }, { _meta: CLAIMS }),
|
|
130
|
+
);
|
|
131
|
+
expect(res.status).toBe(200);
|
|
132
|
+
expect(res.body).toContain('"isError":false');
|
|
133
|
+
expect(calls).toHaveLength(1);
|
|
134
|
+
const meta = calls[0].meta;
|
|
135
|
+
expect(meta.established).toBe('verified');
|
|
136
|
+
expect(meta.caller).toBe('alice');
|
|
137
|
+
expect(meta.tenant).toBe('acme');
|
|
138
|
+
expect(meta.extra?.scopes).toBe('read,write');
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it('never takes identity from the request on an open leaf', async () => {
|
|
142
|
+
const { handler, calls } = mount(era);
|
|
143
|
+
const res = await handler(
|
|
144
|
+
call(era, 'ping', { Authorization: 'Bearer good' }, {
|
|
145
|
+
_meta: CLAIMS,
|
|
146
|
+
arguments: {},
|
|
147
|
+
}),
|
|
148
|
+
);
|
|
149
|
+
expect(res.status).toBe(200);
|
|
150
|
+
expect(calls).toHaveLength(1);
|
|
151
|
+
const meta = calls[0].meta;
|
|
152
|
+
expect(meta.established).toBeUndefined();
|
|
153
|
+
expect(meta.caller).toBeUndefined();
|
|
154
|
+
expect(meta.tenant).toBeUndefined();
|
|
155
|
+
expect(meta.extra?.scopes).toBeUndefined();
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it('runs an open leaf unestablished when the verifier refuses', async () => {
|
|
159
|
+
const { handler, calls } = mount(era, { verifier: verifyGood });
|
|
160
|
+
const res = await handler(call(era, 'ping', { Authorization: 'Bearer bad' }));
|
|
161
|
+
expect(res.status).toBe(200);
|
|
162
|
+
expect(calls[0].meta.established).toBeUndefined();
|
|
163
|
+
expect(calls[0].meta.caller).toBeUndefined();
|
|
164
|
+
});
|
|
165
|
+
});
|
|
166
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module mcp/identity
|
|
3
|
+
* @package @hop-top/kit
|
|
4
|
+
*
|
|
5
|
+
* Who is calling, as both eras' `tools/call` gate reads it. The only
|
|
6
|
+
* source of identity is the mount's verifier: an `Authorization`
|
|
7
|
+
* header is presence, not verification, and a caller or scopes the
|
|
8
|
+
* request claims never become identity. Mirrors the Go surfaces,
|
|
9
|
+
* where only an established `Meta` admits a `kit/auth-required` leaf.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { McpHttpRequest } from './dispatch.js';
|
|
13
|
+
import {
|
|
14
|
+
SURFACE_MCP,
|
|
15
|
+
type InvocationMeta,
|
|
16
|
+
type McpIdentity,
|
|
17
|
+
type McpVerifier,
|
|
18
|
+
} from './types.js';
|
|
19
|
+
|
|
20
|
+
/** The key the verifier's scopes are recorded under in `InvocationMeta.extra`. */
|
|
21
|
+
export const SCOPES_EXTRA_KEY = 'scopes';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Runs the mount's verifier over `req`. Returns the identity it
|
|
25
|
+
* established, or `undefined` when there is no verifier, it refused
|
|
26
|
+
* (`null`/`undefined`), returned something that is not an object, or
|
|
27
|
+
* threw: every failure fails closed.
|
|
28
|
+
*/
|
|
29
|
+
export async function establishCaller(
|
|
30
|
+
verifier: McpVerifier | undefined,
|
|
31
|
+
req: McpHttpRequest,
|
|
32
|
+
): Promise<McpIdentity | undefined> {
|
|
33
|
+
if (verifier === undefined) return undefined;
|
|
34
|
+
let ident: McpIdentity | null | undefined;
|
|
35
|
+
try {
|
|
36
|
+
ident = await verifier(req);
|
|
37
|
+
} catch {
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
if (ident === null || typeof ident !== 'object') return undefined;
|
|
41
|
+
return ident;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Builds one `tools/call` invocation's meta: the MCP surface, the
|
|
46
|
+
* request time, the audit `extra` the era supplies, and the identity
|
|
47
|
+
* the verifier established — caller, tenant, `established`, and the
|
|
48
|
+
* comma-joined `scopes` extra entry. Nothing from `ident` is set when
|
|
49
|
+
* it is `undefined`, and nothing here reads the request.
|
|
50
|
+
*/
|
|
51
|
+
export function invocationMeta(
|
|
52
|
+
ident: McpIdentity | undefined,
|
|
53
|
+
extra?: Record<string, string>,
|
|
54
|
+
): InvocationMeta {
|
|
55
|
+
const meta: InvocationMeta = { surface: SURFACE_MCP, requestedAt: new Date() };
|
|
56
|
+
const bag: Record<string, string> = { ...(extra ?? {}) };
|
|
57
|
+
delete bag[SCOPES_EXTRA_KEY];
|
|
58
|
+
if (ident !== undefined) {
|
|
59
|
+
meta.established = 'verified';
|
|
60
|
+
if (typeof ident.caller === 'string' && ident.caller !== '') {
|
|
61
|
+
meta.caller = ident.caller;
|
|
62
|
+
}
|
|
63
|
+
if (typeof ident.tenant === 'string' && ident.tenant !== '') {
|
|
64
|
+
meta.tenant = ident.tenant;
|
|
65
|
+
}
|
|
66
|
+
if (Array.isArray(ident.scopes) && ident.scopes.length > 0) {
|
|
67
|
+
bag[SCOPES_EXTRA_KEY] = ident.scopes.join(',');
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (Object.keys(bag).length > 0) meta.extra = bag;
|
|
71
|
+
return meta;
|
|
72
|
+
}
|