@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.
Files changed (285) hide show
  1. package/CHANGELOG.md +251 -0
  2. package/LICENSE +1 -1
  3. package/LICENSE-cobra.txt +174 -0
  4. package/NOTICE +15 -0
  5. package/README.md +55 -259
  6. package/dist/aim-DZHwwiIc.d.ts +139 -0
  7. package/dist/aim.d.ts +1 -116
  8. package/dist/aim.js +13 -414
  9. package/dist/alias-D9_qFlyP.d.ts +174 -0
  10. package/dist/alias.d.ts +2 -73
  11. package/dist/alias.js +27 -207
  12. package/dist/api-DAexsu2H.d.ts +77 -0
  13. package/dist/api.d.ts +1 -62
  14. package/dist/api.js +10 -164
  15. package/dist/auth-2-jfgiHn.d.ts +34 -0
  16. package/dist/auth.d.ts +1 -26
  17. package/dist/auth.js +6 -40
  18. package/dist/chunk-2JV3A7OP.js +1894 -0
  19. package/dist/chunk-3FIKGFKI.js +54 -0
  20. package/dist/chunk-4UE5TCMQ.js +104 -0
  21. package/dist/chunk-6HFAEZ52.js +29 -0
  22. package/dist/chunk-6SVOHNIC.js +17 -0
  23. package/dist/chunk-72XZWQX7.js +504 -0
  24. package/dist/chunk-ABQSE7AI.js +513 -0
  25. package/dist/chunk-BDNNPRX6.js +41 -0
  26. package/dist/chunk-BLS2OBIQ.js +263 -0
  27. package/dist/chunk-BRNEKPWX.js +37 -0
  28. package/dist/chunk-CSJWB6D3.js +151 -0
  29. package/dist/chunk-GGWJRWWA.js +309 -0
  30. package/dist/chunk-GHPJJV5L.js +613 -0
  31. package/dist/chunk-IXVQ62NZ.js +334 -0
  32. package/dist/chunk-JKMQSAJP.js +174 -0
  33. package/dist/chunk-JZ22ZUFA.js +1131 -0
  34. package/dist/chunk-K7VCKJ27.js +814 -0
  35. package/dist/chunk-KVG7YCTS.js +115 -0
  36. package/dist/chunk-L23O2FFE.js +51 -0
  37. package/dist/chunk-MQXYDYRD.js +968 -0
  38. package/dist/chunk-MUIQVU6E.js +251 -0
  39. package/dist/chunk-NLMS7HGP.js +178 -0
  40. package/dist/chunk-POR5L2DG.js +247 -0
  41. package/dist/chunk-PSFYJGDG.js +1445 -0
  42. package/dist/chunk-QJVSKKRQ.js +369 -0
  43. package/dist/chunk-QPUCXQXT.js +67 -0
  44. package/dist/chunk-QQQYCWSC.js +240 -0
  45. package/dist/chunk-R5U7XKVJ.js +16 -0
  46. package/dist/chunk-SNVGDYX7.js +187 -0
  47. package/dist/chunk-T46YPHKN.js +669 -0
  48. package/dist/chunk-UKZIAQA7.js +26 -0
  49. package/dist/chunk-WBVO43HU.js +355 -0
  50. package/dist/chunk-WUOAQVOA.js +86 -0
  51. package/dist/chunk-WWUKGJB5.js +90 -0
  52. package/dist/chunk-XJTRY453.js +868 -0
  53. package/dist/chunk-YGYQUFGY.js +219 -0
  54. package/dist/chunk-YOBAUCVN.js +583 -0
  55. package/dist/cli-C5B5tnpA.d.ts +400 -0
  56. package/dist/cli.d.ts +7 -309
  57. package/dist/cli.js +70 -945
  58. package/dist/completion-csVun6SP.d.ts +112 -0
  59. package/dist/completion-values-By-mnjNt.d.ts +142 -0
  60. package/dist/completion-values.d.ts +1 -0
  61. package/dist/completion-values.js +29 -0
  62. package/dist/completion.d.ts +3 -0
  63. package/dist/completion.js +34 -0
  64. package/dist/compliance-AxFf-uMy.d.ts +60 -0
  65. package/dist/compliance.d.ts +1 -0
  66. package/dist/compliance.js +17 -0
  67. package/dist/config-CaK60ByQ.d.ts +241 -0
  68. package/dist/config.d.ts +1 -97
  69. package/dist/config.js +8 -78
  70. package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
  71. package/dist/errcorrect.d.ts +1 -37
  72. package/dist/errcorrect.js +8 -68
  73. package/dist/error-Do8Qji43.d.ts +231 -0
  74. package/dist/id/index.d.ts +2 -83
  75. package/dist/id/index.js +14 -65
  76. package/dist/index-BKJZClJx.d.ts +1486 -0
  77. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  78. package/dist/index-DCe1boBz.d.ts +328 -0
  79. package/dist/index-VLDcI5NF.d.ts +95 -0
  80. package/dist/index.d.ts +37 -0
  81. package/dist/index.js +132 -0
  82. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  83. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  84. package/dist/llm-anthropic.d.ts +2 -0
  85. package/dist/llm-anthropic.js +13 -0
  86. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  87. package/dist/llm-openai.d.ts +2 -0
  88. package/dist/llm-openai.js +19 -0
  89. package/dist/llm.d.ts +1 -188
  90. package/dist/llm.js +101 -356
  91. package/dist/log-CkaxMX3U.d.ts +115 -0
  92. package/dist/log.d.ts +2 -0
  93. package/dist/log.js +14 -0
  94. package/dist/mcp/index.d.ts +4 -0
  95. package/dist/mcp/index.js +184 -0
  96. package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
  97. package/dist/netpolicy.d.ts +1 -0
  98. package/dist/netpolicy.js +25 -0
  99. package/dist/output-CjZWmL8s.d.ts +420 -0
  100. package/dist/output.d.ts +3 -213
  101. package/dist/output.js +137 -447
  102. package/dist/parity-CvMuYcVI.d.ts +61 -0
  103. package/dist/progress-CAzyxeWl.d.ts +38 -0
  104. package/dist/progress.d.ts +1 -30
  105. package/dist/progress.js +6 -55
  106. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  107. package/dist/provenance.d.ts +1 -24
  108. package/dist/provenance.js +6 -31
  109. package/dist/routellm-B0nv59mH.d.ts +111 -0
  110. package/dist/routellm.d.ts +2 -64
  111. package/dist/routellm.js +13 -255
  112. package/dist/rpc-D31Lg0Kc.d.ts +32 -0
  113. package/dist/rpc.d.ts +2 -25
  114. package/dist/rpc.js +4 -98
  115. package/dist/safety-CUaYEjZc.d.ts +30 -0
  116. package/dist/safety.d.ts +1 -24
  117. package/dist/safety.js +6 -43
  118. package/dist/scope-BrhYB4ij.d.ts +141 -0
  119. package/dist/scope.d.ts +1 -121
  120. package/dist/scope.js +20 -377
  121. package/dist/serve-D8yWMrTc.d.ts +646 -0
  122. package/dist/serve.d.ts +3 -0
  123. package/dist/serve.js +75 -0
  124. package/dist/sqlstore.js +6 -39
  125. package/dist/stream-CrjeCp0M.d.ts +44 -0
  126. package/dist/stream.d.ts +1 -35
  127. package/dist/stream.js +8 -51
  128. package/dist/telemetry/index.d.ts +1 -315
  129. package/dist/telemetry/index.js +26 -599
  130. package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
  131. package/dist/toolspec.d.ts +2 -0
  132. package/dist/toolspec.js +37 -0
  133. package/dist/tui/index.d.ts +6 -298
  134. package/dist/tui/index.js +17 -381
  135. package/dist/upgrade-p_zh3pvV.d.ts +102 -0
  136. package/dist/upgrade.d.ts +1 -95
  137. package/dist/upgrade.js +6 -114
  138. package/dist/xdg-DB7Shoib.d.ts +179 -0
  139. package/dist/xdg.d.ts +1 -169
  140. package/dist/xdg.js +14 -128
  141. package/package.json +192 -24
  142. package/src/README.md +15 -0
  143. package/src/alias.conformance.test.ts +250 -0
  144. package/src/alias.test.ts +206 -2
  145. package/src/alias.ts +196 -21
  146. package/src/cli.help-command.test.ts +105 -0
  147. package/src/cli.offline.test.ts +93 -0
  148. package/src/cli.parity.test.ts +192 -0
  149. package/src/cli.test.ts +95 -1
  150. package/src/cli.ts +195 -25
  151. package/src/completion-scripts.ts +16 -0
  152. package/src/completion-values.test.ts +76 -16
  153. package/src/completion-values.ts +170 -66
  154. package/src/completion.conformance.test.ts +297 -0
  155. package/src/completion.test.ts +256 -145
  156. package/src/completion.ts +767 -121
  157. package/src/compliance.test.ts +196 -2
  158. package/src/compliance.ts +440 -20
  159. package/src/config-merge.test.ts +425 -0
  160. package/src/config.test.ts +228 -1
  161. package/src/config.ts +429 -16
  162. package/src/gen/crud_pb.ts +7 -7
  163. package/src/id/README.md +38 -0
  164. package/src/id/contract.test.ts +1 -1
  165. package/src/id/index.test.ts +1 -1
  166. package/src/id/index.ts +3 -2
  167. package/src/index.test.ts +71 -0
  168. package/src/index.ts +46 -0
  169. package/src/llm-anthropic.conformance.test.ts +1135 -0
  170. package/src/llm-anthropic.test.ts +152 -0
  171. package/src/llm-anthropic.ts +940 -0
  172. package/src/llm-choice-hermetic.test.ts +335 -0
  173. package/src/llm-config.test.ts +232 -0
  174. package/src/llm-config.ts +106 -0
  175. package/src/llm-endpoint.ts +254 -0
  176. package/src/llm-error.ts +17 -0
  177. package/src/llm-errors.ts +152 -0
  178. package/src/llm-file.ts +126 -0
  179. package/src/llm-http.ts +317 -0
  180. package/src/llm-keys.ts +167 -0
  181. package/src/llm-media.conformance.test.ts +87 -0
  182. package/src/llm-media.test.ts +279 -0
  183. package/src/llm-media.ts +322 -0
  184. package/src/llm-openai.conformance.test.ts +407 -0
  185. package/src/llm-openai.test.ts +510 -0
  186. package/src/llm-openai.ts +708 -0
  187. package/src/llm-payload.ts +155 -0
  188. package/src/llm-quote.ts +46 -0
  189. package/src/llm-routellm.conformance.test.ts +44 -0
  190. package/src/llm-toolnames.conformance.test.ts +112 -0
  191. package/src/llm-toolnames.test.ts +132 -0
  192. package/src/llm-toolnames.ts +298 -0
  193. package/src/llm-uri.ts +99 -0
  194. package/src/llm.test.ts +43 -15
  195. package/src/llm.toolcall.test.ts +175 -0
  196. package/src/llm.ts +602 -190
  197. package/src/log.parity.test.ts +105 -0
  198. package/src/log.test.ts +270 -1
  199. package/src/log.ts +228 -49
  200. package/src/mcp/README.md +63 -0
  201. package/src/mcp/args-separator.test.ts +164 -0
  202. package/src/mcp/args.test.ts +223 -0
  203. package/src/mcp/args.ts +160 -0
  204. package/src/mcp/audit.test.ts +520 -0
  205. package/src/mcp/audit.ts +70 -0
  206. package/src/mcp/bridge.test.ts +222 -0
  207. package/src/mcp/bridge.ts +291 -0
  208. package/src/mcp/conformance.test.ts +357 -0
  209. package/src/mcp/dispatch.ts +359 -0
  210. package/src/mcp/identity.test.ts +166 -0
  211. package/src/mcp/identity.ts +72 -0
  212. package/src/mcp/index.ts +176 -0
  213. package/src/mcp/legacy-notify.test.ts +59 -0
  214. package/src/mcp/legacy.ts +367 -0
  215. package/src/mcp/mcp.test.ts +707 -0
  216. package/src/mcp/modern-confirm.test.ts +520 -0
  217. package/src/mcp/modern-confirm.ts +484 -0
  218. package/src/mcp/modern.ts +788 -0
  219. package/src/mcp/stdio.test.ts +313 -0
  220. package/src/mcp/stdio.ts +254 -0
  221. package/src/mcp/tasks.ts +82 -0
  222. package/src/mcp/testtree.ts +250 -0
  223. package/src/mcp/toolname.test.ts +147 -0
  224. package/src/mcp/types.ts +689 -0
  225. package/src/netpolicy.test.ts +280 -0
  226. package/src/netpolicy.ts +256 -0
  227. package/src/output/README.md +46 -0
  228. package/src/output/builtins.ts +5 -5
  229. package/src/output/dispatch.ts +10 -2
  230. package/src/output/error.ts +459 -0
  231. package/src/output/formatter.ts +29 -5
  232. package/src/output/formatters/README.md +50 -0
  233. package/src/output/formatters/csv.ts +48 -12
  234. package/src/output/formatters/json.ts +4 -25
  235. package/src/output/formatters/project.ts +34 -0
  236. package/src/output/formatters/table.ts +8 -6
  237. package/src/output/formatters/text.ts +7 -3
  238. package/src/output/formatters/yaml.ts +5 -22
  239. package/src/output/projection.test.ts +298 -0
  240. package/src/output/projection.ts +33 -59
  241. package/src/output/template.ts +11 -21
  242. package/src/output.surface.test.ts +41 -0
  243. package/src/output.ts +64 -3
  244. package/src/published-types.test.ts +133 -0
  245. package/src/routellm.test.ts +209 -28
  246. package/src/routellm.toolcall.test.ts +521 -0
  247. package/src/routellm.ts +213 -177
  248. package/src/router/README.md +44 -0
  249. package/src/router/server.test.ts +41 -0
  250. package/src/router/server.ts +11 -0
  251. package/src/safety.test.ts +19 -9
  252. package/src/scope-defaults.json +29 -29
  253. package/src/serve.test.ts +1257 -0
  254. package/src/serve.ts +1665 -0
  255. package/src/telemetry/README.md +48 -0
  256. package/src/telemetry/client.test.ts +31 -0
  257. package/src/telemetry/client.ts +12 -6
  258. package/src/telemetry/offline.test.ts +64 -0
  259. package/src/toolspec-internal.ts +279 -0
  260. package/src/toolspec-manifest.test.ts +167 -0
  261. package/src/toolspec-manifest.ts +410 -0
  262. package/src/toolspec-spec-schemas.ts +12 -0
  263. package/src/toolspec-spec.test.ts +273 -0
  264. package/src/toolspec-spec.ts +458 -0
  265. package/src/toolspec.from-command.test.ts +350 -0
  266. package/src/toolspec.test.ts +2 -2
  267. package/src/toolspec.ts +222 -0
  268. package/src/triton/README.md +34 -0
  269. package/src/tui/README.md +42 -0
  270. package/src/tui/parity.test.ts +120 -31
  271. package/src/tui/parity.ts +58 -7
  272. package/src/wizard.test.ts +7 -7
  273. package/test/llm/conformance-helpers.ts +100 -0
  274. package/test/output/csv.test.ts +164 -0
  275. package/test/output/dispatch.test.ts +1 -2
  276. package/test/output/error.test.ts +277 -0
  277. package/test/output/smoke-capture.ts +2 -2
  278. package/test/output/smoke.test.ts +2 -2
  279. package/test/output/taxonomy-contract.test.ts +148 -0
  280. package/test/setup-env.ts +16 -0
  281. package/test/toolspec/fixture.ts +79 -0
  282. package/tsconfig.json +3 -1
  283. package/tsconfig.test.json +10 -0
  284. package/vitest.config.ts +9 -0
  285. package/src/tui/parity.json +0 -74
@@ -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
+ }