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

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 (293) hide show
  1. package/CHANGELOG.md +275 -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-3FIKGFKI.js +54 -0
  19. package/dist/chunk-4FMALWYB.js +669 -0
  20. package/dist/chunk-4GPCWBBA.js +143 -0
  21. package/dist/chunk-4UE5TCMQ.js +104 -0
  22. package/dist/chunk-65VPWMPV.js +1134 -0
  23. package/dist/chunk-6HFAEZ52.js +29 -0
  24. package/dist/chunk-6SVOHNIC.js +17 -0
  25. package/dist/chunk-BDNNPRX6.js +41 -0
  26. package/dist/chunk-BRNEKPWX.js +37 -0
  27. package/dist/chunk-BXJ2J27B.js +219 -0
  28. package/dist/chunk-CSJWB6D3.js +151 -0
  29. package/dist/chunk-CXBZTONY.js +65 -0
  30. package/dist/chunk-EE4M2UOF.js +818 -0
  31. package/dist/chunk-GFRAYYRD.js +817 -0
  32. package/dist/chunk-IVQHLI56.js +1890 -0
  33. package/dist/chunk-IZ6Q4SE3.js +178 -0
  34. package/dist/chunk-JKMQSAJP.js +174 -0
  35. package/dist/chunk-K7E34Q3A.js +1445 -0
  36. package/dist/chunk-KVG7YCTS.js +115 -0
  37. package/dist/chunk-L23O2FFE.js +51 -0
  38. package/dist/chunk-MFVUENZR.js +1549 -0
  39. package/dist/chunk-ML7D5DWY.js +263 -0
  40. package/dist/chunk-MQXYDYRD.js +968 -0
  41. package/dist/chunk-POR5L2DG.js +247 -0
  42. package/dist/chunk-QJVSKKRQ.js +369 -0
  43. package/dist/chunk-QQQYCWSC.js +240 -0
  44. package/dist/chunk-R5U7XKVJ.js +16 -0
  45. package/dist/chunk-RYKLVOVK.js +309 -0
  46. package/dist/chunk-SNVGDYX7.js +187 -0
  47. package/dist/chunk-T6OZMPPV.js +68 -0
  48. package/dist/chunk-UKZIAQA7.js +26 -0
  49. package/dist/chunk-VGOA5Y7S.js +251 -0
  50. package/dist/chunk-VWGP4NVJ.js +513 -0
  51. package/dist/chunk-WBVO43HU.js +355 -0
  52. package/dist/chunk-WUOAQVOA.js +86 -0
  53. package/dist/chunk-XJTRY453.js +868 -0
  54. package/dist/chunk-YOBAUCVN.js +583 -0
  55. package/dist/cli-RSRk1M36.d.ts +707 -0
  56. package/dist/cli.d.ts +7 -309
  57. package/dist/cli.js +125 -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-CGE5yLBj.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 +185 -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 +135 -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-C3RWGwRi.d.ts +125 -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.root.conformance.test.ts +166 -0
  150. package/src/cli.test.ts +95 -1
  151. package/src/cli.ts +234 -25
  152. package/src/completion-scripts.ts +16 -0
  153. package/src/completion-values.test.ts +76 -16
  154. package/src/completion-values.ts +170 -66
  155. package/src/completion.conformance.test.ts +298 -0
  156. package/src/completion.test.ts +268 -145
  157. package/src/completion.ts +772 -121
  158. package/src/compliance.test.ts +196 -2
  159. package/src/compliance.ts +440 -20
  160. package/src/config-merge.test.ts +425 -0
  161. package/src/config.test.ts +228 -1
  162. package/src/config.ts +429 -16
  163. package/src/delegation.test.ts +299 -0
  164. package/src/delegation.ts +807 -0
  165. package/src/gen/crud_pb.ts +7 -7
  166. package/src/id/README.md +38 -0
  167. package/src/id/contract.test.ts +1 -1
  168. package/src/id/index.test.ts +1 -1
  169. package/src/id/index.ts +3 -2
  170. package/src/index.test.ts +71 -0
  171. package/src/index.ts +46 -0
  172. package/src/llm-anthropic.conformance.test.ts +1135 -0
  173. package/src/llm-anthropic.test.ts +152 -0
  174. package/src/llm-anthropic.ts +940 -0
  175. package/src/llm-choice-hermetic.test.ts +335 -0
  176. package/src/llm-config.test.ts +232 -0
  177. package/src/llm-config.ts +106 -0
  178. package/src/llm-endpoint.ts +254 -0
  179. package/src/llm-error.ts +17 -0
  180. package/src/llm-errors.ts +152 -0
  181. package/src/llm-file.ts +126 -0
  182. package/src/llm-http.ts +317 -0
  183. package/src/llm-keys.ts +167 -0
  184. package/src/llm-media.conformance.test.ts +87 -0
  185. package/src/llm-media.test.ts +279 -0
  186. package/src/llm-media.ts +322 -0
  187. package/src/llm-openai.conformance.test.ts +407 -0
  188. package/src/llm-openai.test.ts +510 -0
  189. package/src/llm-openai.ts +708 -0
  190. package/src/llm-payload.ts +155 -0
  191. package/src/llm-quote.ts +46 -0
  192. package/src/llm-routellm.conformance.test.ts +44 -0
  193. package/src/llm-toolnames.conformance.test.ts +112 -0
  194. package/src/llm-toolnames.test.ts +132 -0
  195. package/src/llm-toolnames.ts +298 -0
  196. package/src/llm-uri.ts +99 -0
  197. package/src/llm.test.ts +43 -15
  198. package/src/llm.toolcall.test.ts +175 -0
  199. package/src/llm.ts +602 -190
  200. package/src/log.parity.test.ts +105 -0
  201. package/src/log.test.ts +270 -1
  202. package/src/log.ts +228 -49
  203. package/src/mcp/README.md +63 -0
  204. package/src/mcp/args-separator.test.ts +164 -0
  205. package/src/mcp/args.test.ts +223 -0
  206. package/src/mcp/args.ts +160 -0
  207. package/src/mcp/audit.test.ts +520 -0
  208. package/src/mcp/audit.ts +70 -0
  209. package/src/mcp/bridge.test.ts +250 -0
  210. package/src/mcp/bridge.ts +286 -0
  211. package/src/mcp/conformance.test.ts +357 -0
  212. package/src/mcp/dispatch.ts +359 -0
  213. package/src/mcp/identity.test.ts +166 -0
  214. package/src/mcp/identity.ts +72 -0
  215. package/src/mcp/index.ts +176 -0
  216. package/src/mcp/legacy-notify.test.ts +59 -0
  217. package/src/mcp/legacy.ts +367 -0
  218. package/src/mcp/mcp.test.ts +707 -0
  219. package/src/mcp/modern-confirm.test.ts +520 -0
  220. package/src/mcp/modern-confirm.ts +484 -0
  221. package/src/mcp/modern.ts +788 -0
  222. package/src/mcp/stdio.test.ts +313 -0
  223. package/src/mcp/stdio.ts +254 -0
  224. package/src/mcp/tasks.ts +82 -0
  225. package/src/mcp/testtree.ts +250 -0
  226. package/src/mcp/toolname.test.ts +147 -0
  227. package/src/mcp/types.ts +689 -0
  228. package/src/netpolicy.test.ts +280 -0
  229. package/src/netpolicy.ts +256 -0
  230. package/src/output/README.md +46 -0
  231. package/src/output/builtins.ts +5 -5
  232. package/src/output/dispatch.ts +10 -2
  233. package/src/output/error.ts +459 -0
  234. package/src/output/formatter.ts +29 -5
  235. package/src/output/formatters/README.md +50 -0
  236. package/src/output/formatters/csv.ts +48 -12
  237. package/src/output/formatters/json.ts +4 -25
  238. package/src/output/formatters/project.ts +34 -0
  239. package/src/output/formatters/table.ts +8 -6
  240. package/src/output/formatters/text.ts +7 -3
  241. package/src/output/formatters/yaml.ts +5 -22
  242. package/src/output/projection.test.ts +298 -0
  243. package/src/output/projection.ts +33 -59
  244. package/src/output/template.ts +11 -21
  245. package/src/output.surface.test.ts +41 -0
  246. package/src/output.ts +64 -3
  247. package/src/plan.ts +89 -0
  248. package/src/policy.ts +472 -0
  249. package/src/published-types.test.ts +133 -0
  250. package/src/routellm.test.ts +209 -28
  251. package/src/routellm.toolcall.test.ts +521 -0
  252. package/src/routellm.ts +213 -177
  253. package/src/router/README.md +44 -0
  254. package/src/router/server.test.ts +41 -0
  255. package/src/router/server.ts +11 -0
  256. package/src/safety.test.ts +19 -9
  257. package/src/scope-defaults.json +29 -29
  258. package/src/serve.test.ts +1257 -0
  259. package/src/serve.ts +1665 -0
  260. package/src/sideeffect.ts +105 -0
  261. package/src/telemetry/README.md +48 -0
  262. package/src/telemetry/client.test.ts +31 -0
  263. package/src/telemetry/client.ts +12 -6
  264. package/src/telemetry/offline.test.ts +64 -0
  265. package/src/toolspec-internal.ts +279 -0
  266. package/src/toolspec-manifest.test.ts +167 -0
  267. package/src/toolspec-manifest.ts +415 -0
  268. package/src/toolspec-spec-schemas.ts +12 -0
  269. package/src/toolspec-spec.test.ts +273 -0
  270. package/src/toolspec-spec.ts +458 -0
  271. package/src/toolspec.from-command.test.ts +350 -0
  272. package/src/toolspec.test.ts +2 -2
  273. package/src/toolspec.ts +222 -0
  274. package/src/triton/README.md +34 -0
  275. package/src/tui/README.md +42 -0
  276. package/src/tui/parity.test.ts +120 -31
  277. package/src/tui/parity.ts +58 -7
  278. package/src/upgrade.test.ts +291 -0
  279. package/src/upgrade.ts +116 -7
  280. package/src/wizard.test.ts +7 -7
  281. package/test/llm/conformance-helpers.ts +100 -0
  282. package/test/output/csv.test.ts +164 -0
  283. package/test/output/dispatch.test.ts +1 -2
  284. package/test/output/error.test.ts +277 -0
  285. package/test/output/smoke-capture.ts +2 -2
  286. package/test/output/smoke.test.ts +2 -2
  287. package/test/output/taxonomy-contract.test.ts +148 -0
  288. package/test/setup-env.ts +16 -0
  289. package/test/toolspec/fixture.ts +79 -0
  290. package/tsconfig.json +3 -1
  291. package/tsconfig.test.json +10 -0
  292. package/vitest.config.ts +9 -0
  293. package/src/tui/parity.json +0 -74
@@ -0,0 +1,176 @@
1
+ /**
2
+ * @module mcp
3
+ * @package @hop-top/kit
4
+ *
5
+ * Dual-spec MCP surface: one mount serving both 2024-11-05 (legacy
6
+ * handshake) and 2026-07-28 (stateless per-request envelope), with
7
+ * per-request era detection.
8
+ *
9
+ * The protocol layer comes from the official v2 SDK packages
10
+ * (`@modelcontextprotocol/core` + `@modelcontextprotocol/server`).
11
+ * The v1 package `@modelcontextprotocol/sdk` is legacy-era only and
12
+ * cannot serve 2026-07-28 — it is deliberately not a dependency.
13
+ *
14
+ * Usage:
15
+ *
16
+ * ```ts
17
+ * import { createMcpHandler } from '@hop-top/kit/mcp';
18
+ *
19
+ * const handler = createMcpHandler(bridge);
20
+ * const res = await handler({ method: 'POST', headers, body });
21
+ * ```
22
+ *
23
+ * The handler is framework-free: binding it to node:http, hono,
24
+ * express, fastify, or a Worker is the adopter's job. For a host that
25
+ * spawns the tool, `serveStdio(bridge)` (or `serveStdio(handler)`)
26
+ * serves the same surface over newline-delimited stdin/stdout.
27
+ */
28
+
29
+ export {
30
+ createMcpHandler,
31
+ detectMcpEra,
32
+ hasModernMetaMarker,
33
+ mcpMountConfig,
34
+ McpDispatcher,
35
+ methodNotAllowedResponse,
36
+ parseJsonRpcRequest,
37
+ type JsonRpcRequest,
38
+ type McpEra,
39
+ type McpHandler,
40
+ type McpHttpRequest,
41
+ type McpHttpResponse,
42
+ type McpTransport,
43
+ } from './dispatch.js';
44
+
45
+ export { LegacyMcpHandler } from './legacy.js';
46
+
47
+ export {
48
+ auditRefusal,
49
+ MCP_AUDIT_AUTH_REFUSED,
50
+ MCP_AUDIT_CONFIRMATION_DECLINED,
51
+ MCP_AUDIT_CONFIRMATION_REQUIRED,
52
+ MCP_AUDIT_CONFIRMATION_STATE_REJECTED,
53
+ MCP_AUDIT_DESTRUCTIVE_BLOCKED,
54
+ MCP_CONFIRM_REJECTION_STATE,
55
+ } from './audit.js';
56
+
57
+ export {
58
+ serveStdio,
59
+ type McpStdioOptions,
60
+ type McpStdioServer,
61
+ } from './stdio.js';
62
+
63
+ export {
64
+ decodeMcpSentinel,
65
+ ModernMcpHandler,
66
+ modernInvocationExtra,
67
+ parseModernMeta,
68
+ rawToolCallName,
69
+ singleHeaderValue,
70
+ validModernRequestId,
71
+ type ModernRequestMeta,
72
+ } from './modern.js';
73
+
74
+ export {
75
+ clientSupportsFormElicitation,
76
+ ElicitationConfirmGate,
77
+ headerConfirmationGate,
78
+ MCP_CONFIRM_KEY,
79
+ MCP_CONFIRM_STATE_TTL_SECONDS,
80
+ MCP_CONFIRM_STATE_VERSION,
81
+ mcpConfirmArgsDigest,
82
+ mcpConfirmPrincipal,
83
+ mintMcpConfirmState,
84
+ parseMcpConfirmRetry,
85
+ verifyMcpConfirmState,
86
+ type McpConfirmBinding,
87
+ type McpConfirmDecision,
88
+ type McpConfirmRejection,
89
+ type McpConfirmStateStatus,
90
+ } from './modern-confirm.js';
91
+
92
+ export {
93
+ discoverCapabilities,
94
+ isTaskMethod,
95
+ TASK_METHODS,
96
+ TASKS_EXTENSION,
97
+ TASKS_SUPPORTED,
98
+ type TaskMethod,
99
+ } from './tasks.js';
100
+
101
+ export {
102
+ buildToolEnvelope,
103
+ canonicalJSONStringify,
104
+ DEFAULT_MCP_PATH,
105
+ DEFAULT_MCP_SERVER_NAME,
106
+ DEFAULT_MCP_SERVER_VERSION,
107
+ DEFAULT_TOOL_NAME_SEPARATOR,
108
+ defaultPolicy,
109
+ DestructiveBlockedError,
110
+ encodeEnvelope,
111
+ errorResultBlock,
112
+ HEADER_MCP_METHOD,
113
+ HEADER_MCP_NAME,
114
+ HEADER_MCP_PROTOCOL_VERSION,
115
+ MCP_ERR_HEADER_MISMATCH,
116
+ MCP_ERR_INTERNAL,
117
+ MCP_ERR_INVALID_PARAMS,
118
+ MCP_ERR_INVALID_REQUEST,
119
+ MCP_ERR_METHOD_NOT_FOUND,
120
+ MCP_ERR_MISSING_CLIENT_CAPABILITY,
121
+ MCP_ERR_PARSE,
122
+ MCP_ERR_UNSUPPORTED_VERSION,
123
+ MCP_SPEC_2024_11_05,
124
+ MCP_SPEC_2026_07_28,
125
+ META_KEY_CLIENT_CAPABILITIES,
126
+ META_KEY_CLIENT_INFO,
127
+ META_KEY_PROTOCOL_VERSION,
128
+ META_KEY_SERVER_INFO,
129
+ MCP_AUTH_CHALLENGE,
130
+ pathFromToolName,
131
+ policyAllowed,
132
+ RawJSON,
133
+ renderCallResult,
134
+ resolveMcpConfig,
135
+ RESULT_TYPE_COMPLETE,
136
+ RESULT_TYPE_INPUT_REQUIRED,
137
+ SURFACE_CLI,
138
+ SURFACE_LIB,
139
+ SURFACE_MCP,
140
+ SurfaceNotEnabledError,
141
+ toolName,
142
+ UnknownCommandError,
143
+ type FlagSchema,
144
+ type Invocation,
145
+ type InvocationMeta,
146
+ type InvokeResult,
147
+ type JsonRpcErrorObject,
148
+ type Leaf,
149
+ type LeafArg,
150
+ type McpAuditHook,
151
+ type McpAuditRecord,
152
+ type McpBridge,
153
+ type McpCacheScope,
154
+ type McpEstablishment,
155
+ type McpIdentity,
156
+ type McpMountOptions,
157
+ type McpSpecVersion,
158
+ type McpVerifier,
159
+ type Policy,
160
+ type ResolvedMcpConfig,
161
+ type SafetyClass,
162
+ type Surface,
163
+ } from './types.js';
164
+
165
+ export { establishCaller, invocationMeta, SCOPES_EXTRA_KEY } from './identity.js';
166
+
167
+ export { commanderBridge, type CommanderBridgeOptions } from './bridge.js';
168
+
169
+ export {
170
+ MCP_ARGS_PROPERTY,
171
+ mcpArgsPublished,
172
+ mcpInputSchema,
173
+ mcpSplitArguments,
174
+ mcpToolDescription,
175
+ type McpSplitResult,
176
+ } from './args.js';
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Legacy-era notifications and ping.
3
+ *
4
+ * A message with no `id` member is a JSON-RPC notification, which must
5
+ * never be answered: the legacy path acknowledges it with HTTP 202 and
6
+ * an empty body and does not process it. `ping` (a 2024-11-05 utility)
7
+ * must be answered with an empty result. Both hold on the dual-era
8
+ * mount and on a legacy-only mount.
9
+ */
10
+
11
+ import { describe, expect, it } from 'vitest';
12
+
13
+ import { createMcpHandler } from './dispatch.js';
14
+ import { legacyLockBridge } from './testtree.js';
15
+ import type { McpBridge, McpMountOptions } from './types.js';
16
+
17
+ const MOUNTS: Record<string, McpMountOptions> = {
18
+ 'dual-era': {},
19
+ 'legacy-only': { specVersions: ['2024-11-05'] },
20
+ };
21
+
22
+ function countingBridge(): { bridge: McpBridge; calls: () => number } {
23
+ const inner = legacyLockBridge();
24
+ let n = 0;
25
+ const bridge: McpBridge = {
26
+ leaves: () => inner.leaves(),
27
+ invoke: (inv) => {
28
+ n++;
29
+ return inner.invoke(inv);
30
+ },
31
+ };
32
+ return { bridge, calls: () => n };
33
+ }
34
+
35
+ describe.each(Object.entries(MOUNTS))('legacy era (%s mount)', (_name, opts) => {
36
+ it.each([
37
+ '{"jsonrpc":"2.0","method":"notifications/initialized"}',
38
+ '{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":1}}',
39
+ '{"jsonrpc":"2.0","method":"tools/call","params":{"name":"ping"}}',
40
+ ])('does not answer the notification %s', async (body) => {
41
+ const { bridge, calls } = countingBridge();
42
+ const handler = createMcpHandler(bridge, opts);
43
+ const res = await handler({ method: 'POST', body });
44
+ expect(res.status).toBe(202);
45
+ expect(res.body).toBe('');
46
+ expect(calls()).toBe(0);
47
+ });
48
+
49
+ it.each([
50
+ ['{"jsonrpc":"2.0","id":7,"method":"ping"}', '{"jsonrpc":"2.0","id":7,"result":{}}\n'],
51
+ ['{"jsonrpc":"2.0","id":"p","method":"ping","params":{}}', '{"jsonrpc":"2.0","id":"p","result":{}}\n'],
52
+ ['{"jsonrpc":"2.0","id":null,"method":"ping"}', '{"jsonrpc":"2.0","id":null,"result":{}}\n'],
53
+ ])('answers ping %s with an empty result', async (body, want) => {
54
+ const handler = createMcpHandler(legacyLockBridge(), opts);
55
+ const res = await handler({ method: 'POST', body });
56
+ expect(res.status).toBe(200);
57
+ expect(res.body).toBe(want);
58
+ });
59
+ });
@@ -0,0 +1,367 @@
1
+ /**
2
+ * @module mcp/legacy
3
+ * @package @hop-top/kit
4
+ *
5
+ * The 2024-11-05 MCP handler: `initialize`, `ping`, `tools/list`,
6
+ * `tools/call`, plain JSON-RPC over one POST path, no sessions, no
7
+ * SSE.
8
+ *
9
+ * This module's wire output is byte-for-byte frozen. The dual-spec hard
10
+ * invariant is "2024-11-05 behavior is preserved byte-for-byte;
11
+ * additive only; no deprecation", and the three-way module split
12
+ * (legacy / modern / dispatch) exists precisely so a reviewer can
13
+ * confirm a modern-era change did not touch this file. Modern-era
14
+ * behavior belongs in modern.ts — never here. The refusal audit hook
15
+ * (mcp/audit) is the one deliberate addition: it observes the
16
+ * refusals this handler already makes and changes no byte of them.
17
+ */
18
+
19
+ import { mcpSplitArguments } from './args.js';
20
+ import {
21
+ errorResultBlock,
22
+ encodeEnvelope,
23
+ buildToolEnvelope,
24
+ MCP_AUTH_CHALLENGE,
25
+ MCP_ERR_INVALID_PARAMS,
26
+ MCP_ERR_INVALID_REQUEST,
27
+ MCP_ERR_METHOD_NOT_FOUND,
28
+ MCP_ERR_PARSE,
29
+ MCP_SPEC_2024_11_05,
30
+ pathFromToolName,
31
+ renderCallResult,
32
+ SURFACE_MCP,
33
+ type JsonRpcErrorObject,
34
+ type Leaf,
35
+ type McpBridge,
36
+ type RawJSON,
37
+ type ResolvedMcpConfig,
38
+ } from './types.js';
39
+ import {
40
+ DestructiveBlockedError,
41
+ SurfaceNotEnabledError,
42
+ UnknownCommandError,
43
+ } from './types.js';
44
+ import type { JsonRpcRequest, McpHttpRequest, McpHttpResponse } from './dispatch.js';
45
+ import { acceptedResponse, jsonResponse } from './dispatch.js';
46
+ import { establishCaller, invocationMeta } from './identity.js';
47
+ import {
48
+ auditRefusal,
49
+ MCP_AUDIT_AUTH_REFUSED,
50
+ MCP_AUDIT_CONFIRMATION_REQUIRED,
51
+ MCP_AUDIT_DESTRUCTIVE_BLOCKED,
52
+ } from './audit.js';
53
+
54
+ /** Writes a successful JSON-RPC envelope. */
55
+ export function writeResult(
56
+ id: RawJSON | undefined,
57
+ result: unknown,
58
+ status: number,
59
+ ): McpHttpResponse {
60
+ return jsonResponse(status, encodeEnvelope({ id, result }));
61
+ }
62
+
63
+ /** Writes a JSON-RPC error envelope. */
64
+ export function writeError(
65
+ id: RawJSON | undefined,
66
+ error: JsonRpcErrorObject,
67
+ status: number,
68
+ ): McpHttpResponse {
69
+ return jsonResponse(status, encodeEnvelope({ id, error }));
70
+ }
71
+
72
+ /**
73
+ * Renders the -32700 parse error exactly as Go does, including the
74
+ * encoding/json message text the fixtures pin. Go reports the offset
75
+ * of the first offending byte in the phrase "invalid character %q
76
+ * looking for beginning of object key string" when an object key is
77
+ * expected; other positions produce different wording. Only the
78
+ * shapes this surface can actually receive are modelled.
79
+ */
80
+ export function parseErrorResponse(body: string): McpHttpResponse {
81
+ return writeError(
82
+ undefined,
83
+ { code: MCP_ERR_PARSE, message: `parse error: ${goJSONParseMessage(body)}` },
84
+ 400,
85
+ );
86
+ }
87
+
88
+ /**
89
+ * Reproduces Go's encoding/json syntax-error text for a body this
90
+ * surface failed to parse. Go's decoder reports the first character
91
+ * that cannot begin the token it expects; for a top-level object
92
+ * whose first key is unquoted (the fixture case `{not json`) that is
93
+ * "invalid character 'n' looking for beginning of object key string".
94
+ */
95
+ export function goJSONParseMessage(body: string): string {
96
+ const trimmed = body.replace(/^[\s]*/, '');
97
+ if (trimmed.startsWith('{')) {
98
+ // Scan past the opening brace and any whitespace to the first
99
+ // character of what must be a quoted object key.
100
+ const rest = trimmed.slice(1).replace(/^[\s]*/, '');
101
+ const ch = rest[0];
102
+ if (ch !== undefined && ch !== '"' && ch !== '}') {
103
+ return `invalid character '${ch}' looking for beginning of object key string`;
104
+ }
105
+ }
106
+ const ch = trimmed[0];
107
+ if (ch !== undefined) {
108
+ return `invalid character '${ch}' looking for beginning of value`;
109
+ }
110
+ return 'unexpected end of JSON input';
111
+ }
112
+
113
+ /**
114
+ * The 2024-11-05 handler. Stateless across requests; holds only
115
+ * immutable mount configuration and the bridge.
116
+ */
117
+ export class LegacyMcpHandler {
118
+ constructor(
119
+ private readonly bridge: McpBridge,
120
+ private readonly cfg: ResolvedMcpConfig,
121
+ ) {}
122
+
123
+ /**
124
+ * Routes one already-parsed JSON-RPC request by method. An unknown
125
+ * method returns -32601 at HTTP 200 — today's behavior, preserved
126
+ * deliberately (the modern handler uses 404 instead; the asymmetry
127
+ * is required by byte-for-byte preservation).
128
+ */
129
+ async serve(
130
+ req: McpHttpRequest,
131
+ rpc: JsonRpcRequest,
132
+ ): Promise<McpHttpResponse> {
133
+ if (rpc.jsonrpc !== undefined && rpc.jsonrpc !== '2.0') {
134
+ return writeError(
135
+ rpc.id,
136
+ { code: MCP_ERR_INVALID_REQUEST, message: 'invalid jsonrpc version' },
137
+ 400,
138
+ );
139
+ }
140
+
141
+ // No id member: a notification. JSON-RPC 2.0 forbids any reply, so
142
+ // it is acknowledged with HTTP 202 and an empty body and is not
143
+ // processed — the modern handler's V2 answer. An explicit
144
+ // `"id": null` is a request and is answered.
145
+ if (rpc.id === undefined) {
146
+ return acceptedResponse();
147
+ }
148
+
149
+ switch (rpc.method) {
150
+ case 'initialize':
151
+ return this.handleInitialize(rpc);
152
+ case 'ping':
153
+ // 2024-11-05 utility: the receiver MUST answer with an empty
154
+ // result. Legacy era only; 2026-07-28 removed ping.
155
+ return writeResult(rpc.id, {}, 200);
156
+ case 'tools/list':
157
+ return this.handleToolsList(rpc);
158
+ case 'tools/call':
159
+ return this.handleToolsCall(req, rpc);
160
+ default:
161
+ return writeError(
162
+ rpc.id,
163
+ {
164
+ code: MCP_ERR_METHOD_NOT_FOUND,
165
+ message: `method not found: ${rpc.method}`,
166
+ },
167
+ 200,
168
+ );
169
+ }
170
+ }
171
+
172
+ /** The minimal initialize response: version, capabilities, identity. */
173
+ private handleInitialize(rpc: JsonRpcRequest): McpHttpResponse {
174
+ return writeResult(
175
+ rpc.id,
176
+ {
177
+ protocolVersion: MCP_SPEC_2024_11_05,
178
+ capabilities: { tools: {} },
179
+ serverInfo: {
180
+ name: this.cfg.serverName,
181
+ version: this.cfg.serverVersion,
182
+ },
183
+ },
184
+ 200,
185
+ );
186
+ }
187
+
188
+ /** One tool envelope per leaf exposed on the MCP surface. */
189
+ private handleToolsList(rpc: JsonRpcRequest): McpHttpResponse {
190
+ return writeResult(rpc.id, { tools: this.exposedTools() }, 200);
191
+ }
192
+
193
+ private exposedTools(): Array<Record<string, unknown>> {
194
+ const tools: Array<Record<string, unknown>> = [];
195
+ for (const leaf of this.bridge.leaves()) {
196
+ if (!isExposed(leaf)) continue;
197
+ tools.push(buildToolEnvelope(leaf, this.cfg.toolNameSeparator));
198
+ }
199
+ return tools;
200
+ }
201
+
202
+ /**
203
+ * Resolves the leaf, applies the pre-flight auth + confirmation
204
+ * gates, and dispatches through the bridge. Unknown / not-enabled
205
+ * tools are JSON-RPC errors; every other failure (bridge errors,
206
+ * destructive blocks, non-zero exit codes) is an isError result.
207
+ */
208
+ private async handleToolsCall(
209
+ req: McpHttpRequest,
210
+ rpc: JsonRpcRequest,
211
+ ): Promise<McpHttpResponse> {
212
+ const params = (rpc.params ?? {}) as {
213
+ name?: unknown;
214
+ arguments?: Record<string, unknown>;
215
+ };
216
+ const name = typeof params.name === 'string' ? params.name : '';
217
+ if (name === '') {
218
+ return writeError(
219
+ rpc.id,
220
+ { code: MCP_ERR_INVALID_PARAMS, message: 'missing tool name' },
221
+ 200,
222
+ );
223
+ }
224
+
225
+ const leaf = resolveLeaf(this.bridge, name, this.cfg.toolNameSeparator);
226
+ if (leaf === undefined || !isExposed(leaf)) {
227
+ return writeError(
228
+ rpc.id,
229
+ { code: MCP_ERR_INVALID_PARAMS, message: `unknown tool: ${name}` },
230
+ 200,
231
+ );
232
+ }
233
+
234
+ // Auth + confirmation gating, mirrored onto the result envelope so
235
+ // MCP-aware clients see isError while HTTP-only clients see the
236
+ // matching status code. Only the mount's verifier authenticates:
237
+ // a bare Authorization header does not.
238
+ const ident = await establishCaller(this.cfg.verifier, req);
239
+ if (leaf.class?.authRequired && ident === undefined) {
240
+ this.audit(leaf, MCP_AUDIT_AUTH_REFUSED);
241
+ return unauthenticated(
242
+ writeResult(rpc.id, errorResultBlock('authentication required'), 401),
243
+ );
244
+ }
245
+ // Arguments are checked before the confirmation gate: a person
246
+ // is never asked to approve a call that cannot run as sent.
247
+ const split = mcpSplitArguments(leaf, params.arguments);
248
+ if (split.error !== undefined) {
249
+ return writeResult(rpc.id, errorResultBlock(split.error), 200);
250
+ }
251
+ if (
252
+ leaf.class?.requiresConfirmation &&
253
+ !headerValue(req, 'x-confirm-token')
254
+ ) {
255
+ this.audit(leaf, MCP_AUDIT_CONFIRMATION_REQUIRED);
256
+ return writeResult(
257
+ rpc.id,
258
+ errorResultBlock('confirmation required'),
259
+ 428,
260
+ );
261
+ }
262
+
263
+ try {
264
+ const res = await this.bridge.invoke({
265
+ path: [...leaf.path],
266
+ ...(split.args !== undefined ? { args: split.args } : {}),
267
+ flags: split.flags,
268
+ meta: invocationMeta(ident),
269
+ });
270
+ return writeResult(rpc.id, renderCallResult(res), 200);
271
+ } catch (err) {
272
+ if (
273
+ err instanceof UnknownCommandError ||
274
+ err instanceof SurfaceNotEnabledError
275
+ ) {
276
+ return writeError(
277
+ rpc.id,
278
+ { code: MCP_ERR_INVALID_PARAMS, message: `unknown tool: ${name}` },
279
+ 200,
280
+ );
281
+ }
282
+ // DestructiveBlockedError and every other invoke failure render
283
+ // as an isError result at HTTP 200. Only the ceiling is a
284
+ // refusal the surface audits; a run that failed is the bridge's.
285
+ if (err instanceof DestructiveBlockedError) {
286
+ this.audit(leaf, MCP_AUDIT_DESTRUCTIVE_BLOCKED);
287
+ }
288
+ return writeResult(
289
+ rpc.id,
290
+ errorResultBlock(errorMessage(err)),
291
+ 200,
292
+ );
293
+ }
294
+ }
295
+
296
+ /** Emits one 2024-11-05 refusal record to the mount's audit hook. */
297
+ private audit(leaf: Leaf, error: string): void {
298
+ auditRefusal(this.cfg.audit, leaf.path, MCP_SPEC_2024_11_05, error);
299
+ }
300
+ }
301
+
302
+ /**
303
+ * Stamps the WWW-Authenticate challenge on a 401 refusal, as Go's
304
+ * api.WriteUnauthenticated does at the edge.
305
+ */
306
+ export function unauthenticated(res: McpHttpResponse): McpHttpResponse {
307
+ return {
308
+ ...res,
309
+ headers: { ...res.headers, 'WWW-Authenticate': MCP_AUTH_CHALLENGE },
310
+ };
311
+ }
312
+
313
+ /** Reports whether a leaf is exposed on the MCP surface. */
314
+ export function isExposed(leaf: Leaf): boolean {
315
+ // Absent `enabled` means the bridge applies its policy defaults,
316
+ // which include the MCP surface; an explicit false hides the leaf.
317
+ return leaf.enabled?.[SURFACE_MCP] !== false;
318
+ }
319
+
320
+ /** Resolves a tool name, split on `separator`, to a leaf, or undefined. */
321
+ export function resolveLeaf(
322
+ bridge: McpBridge,
323
+ name: string,
324
+ separator?: string,
325
+ ): Leaf | undefined {
326
+ const path = pathFromToolName(name, separator);
327
+ if (path.length === 0) return undefined;
328
+ return bridge
329
+ .leaves()
330
+ .find(
331
+ (l) =>
332
+ l.path.length === path.length &&
333
+ l.path.every((seg, i) => seg === path[i]),
334
+ );
335
+ }
336
+
337
+ /** Case-insensitive single header lookup. */
338
+ export function headerValue(
339
+ req: McpHttpRequest,
340
+ name: string,
341
+ ): string | undefined {
342
+ const vals = headerValues(req, name);
343
+ return vals.length > 0 ? vals[0] : undefined;
344
+ }
345
+
346
+ /** All values for a header name, matched case-insensitively. */
347
+ export function headerValues(
348
+ req: McpHttpRequest,
349
+ name: string,
350
+ ): string[] {
351
+ const want = name.toLowerCase();
352
+ const out: string[] = [];
353
+ for (const [k, v] of Object.entries(req.headers ?? {})) {
354
+ if (k.toLowerCase() !== want) continue;
355
+ if (Array.isArray(v)) out.push(...v);
356
+ else if (v !== undefined) out.push(v);
357
+ }
358
+ return out;
359
+ }
360
+
361
+ /** Extracts an error message the way Go's err.Error() renders it. */
362
+ export function errorMessage(err: unknown): string {
363
+ if (err instanceof Error) return err.message;
364
+ return String(err);
365
+ }
366
+
367
+ export { DestructiveBlockedError };