@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,1894 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+ var _chunkSNVGDYX7js = require('./chunk-SNVGDYX7.js');
5
+
6
+
7
+ var _chunkR5U7XKVJjs = require('./chunk-R5U7XKVJ.js');
8
+
9
+ // src/mcp/index.ts
10
+ var mcp_exports = {};
11
+ _chunkR5U7XKVJjs.__export.call(void 0, mcp_exports, {
12
+ DEFAULT_MCP_PATH: () => DEFAULT_MCP_PATH,
13
+ DEFAULT_MCP_SERVER_NAME: () => DEFAULT_MCP_SERVER_NAME,
14
+ DEFAULT_MCP_SERVER_VERSION: () => DEFAULT_MCP_SERVER_VERSION,
15
+ DEFAULT_TOOL_NAME_SEPARATOR: () => DEFAULT_TOOL_NAME_SEPARATOR,
16
+ DestructiveBlockedError: () => DestructiveBlockedError,
17
+ ElicitationConfirmGate: () => ElicitationConfirmGate,
18
+ HEADER_MCP_METHOD: () => HEADER_MCP_METHOD,
19
+ HEADER_MCP_NAME: () => HEADER_MCP_NAME,
20
+ HEADER_MCP_PROTOCOL_VERSION: () => HEADER_MCP_PROTOCOL_VERSION,
21
+ LegacyMcpHandler: () => LegacyMcpHandler,
22
+ MCP_ARGS_PROPERTY: () => MCP_ARGS_PROPERTY,
23
+ MCP_AUDIT_AUTH_REFUSED: () => MCP_AUDIT_AUTH_REFUSED,
24
+ MCP_AUDIT_CONFIRMATION_DECLINED: () => MCP_AUDIT_CONFIRMATION_DECLINED,
25
+ MCP_AUDIT_CONFIRMATION_REQUIRED: () => MCP_AUDIT_CONFIRMATION_REQUIRED,
26
+ MCP_AUDIT_CONFIRMATION_STATE_REJECTED: () => MCP_AUDIT_CONFIRMATION_STATE_REJECTED,
27
+ MCP_AUDIT_DESTRUCTIVE_BLOCKED: () => MCP_AUDIT_DESTRUCTIVE_BLOCKED,
28
+ MCP_AUTH_CHALLENGE: () => MCP_AUTH_CHALLENGE,
29
+ MCP_CONFIRM_KEY: () => MCP_CONFIRM_KEY,
30
+ MCP_CONFIRM_REJECTION_STATE: () => MCP_CONFIRM_REJECTION_STATE,
31
+ MCP_CONFIRM_STATE_TTL_SECONDS: () => MCP_CONFIRM_STATE_TTL_SECONDS,
32
+ MCP_CONFIRM_STATE_VERSION: () => MCP_CONFIRM_STATE_VERSION,
33
+ MCP_ERR_HEADER_MISMATCH: () => MCP_ERR_HEADER_MISMATCH,
34
+ MCP_ERR_INTERNAL: () => MCP_ERR_INTERNAL,
35
+ MCP_ERR_INVALID_PARAMS: () => MCP_ERR_INVALID_PARAMS,
36
+ MCP_ERR_INVALID_REQUEST: () => MCP_ERR_INVALID_REQUEST,
37
+ MCP_ERR_METHOD_NOT_FOUND: () => MCP_ERR_METHOD_NOT_FOUND,
38
+ MCP_ERR_MISSING_CLIENT_CAPABILITY: () => MCP_ERR_MISSING_CLIENT_CAPABILITY,
39
+ MCP_ERR_PARSE: () => MCP_ERR_PARSE,
40
+ MCP_ERR_UNSUPPORTED_VERSION: () => MCP_ERR_UNSUPPORTED_VERSION,
41
+ MCP_SPEC_2024_11_05: () => MCP_SPEC_2024_11_05,
42
+ MCP_SPEC_2026_07_28: () => MCP_SPEC_2026_07_28,
43
+ META_KEY_CLIENT_CAPABILITIES: () => META_KEY_CLIENT_CAPABILITIES,
44
+ META_KEY_CLIENT_INFO: () => META_KEY_CLIENT_INFO,
45
+ META_KEY_PROTOCOL_VERSION: () => META_KEY_PROTOCOL_VERSION,
46
+ META_KEY_SERVER_INFO: () => META_KEY_SERVER_INFO,
47
+ McpDispatcher: () => McpDispatcher,
48
+ ModernMcpHandler: () => ModernMcpHandler,
49
+ RESULT_TYPE_COMPLETE: () => RESULT_TYPE_COMPLETE,
50
+ RESULT_TYPE_INPUT_REQUIRED: () => RESULT_TYPE_INPUT_REQUIRED,
51
+ RawJSON: () => RawJSON,
52
+ SCOPES_EXTRA_KEY: () => SCOPES_EXTRA_KEY,
53
+ SURFACE_CLI: () => SURFACE_CLI,
54
+ SURFACE_LIB: () => SURFACE_LIB,
55
+ SURFACE_MCP: () => SURFACE_MCP,
56
+ SurfaceNotEnabledError: () => SurfaceNotEnabledError,
57
+ TASKS_EXTENSION: () => TASKS_EXTENSION,
58
+ TASKS_SUPPORTED: () => TASKS_SUPPORTED,
59
+ TASK_METHODS: () => TASK_METHODS,
60
+ UnknownCommandError: () => UnknownCommandError,
61
+ auditRefusal: () => auditRefusal,
62
+ buildToolEnvelope: () => buildToolEnvelope,
63
+ canonicalJSONStringify: () => canonicalJSONStringify,
64
+ clientSupportsFormElicitation: () => clientSupportsFormElicitation,
65
+ commanderBridge: () => commanderBridge,
66
+ createMcpHandler: () => createMcpHandler,
67
+ decodeMcpSentinel: () => decodeMcpSentinel,
68
+ defaultPolicy: () => defaultPolicy,
69
+ detectMcpEra: () => detectMcpEra,
70
+ discoverCapabilities: () => discoverCapabilities,
71
+ encodeEnvelope: () => encodeEnvelope,
72
+ errorResultBlock: () => errorResultBlock,
73
+ establishCaller: () => establishCaller,
74
+ hasModernMetaMarker: () => hasModernMetaMarker,
75
+ headerConfirmationGate: () => headerConfirmationGate,
76
+ invocationMeta: () => invocationMeta,
77
+ isTaskMethod: () => isTaskMethod,
78
+ mcpArgsPublished: () => mcpArgsPublished,
79
+ mcpConfirmArgsDigest: () => mcpConfirmArgsDigest,
80
+ mcpConfirmPrincipal: () => mcpConfirmPrincipal,
81
+ mcpInputSchema: () => mcpInputSchema,
82
+ mcpMountConfig: () => mcpMountConfig,
83
+ mcpSplitArguments: () => mcpSplitArguments,
84
+ mcpToolDescription: () => mcpToolDescription,
85
+ methodNotAllowedResponse: () => methodNotAllowedResponse,
86
+ mintMcpConfirmState: () => mintMcpConfirmState,
87
+ modernInvocationExtra: () => modernInvocationExtra,
88
+ parseJsonRpcRequest: () => parseJsonRpcRequest,
89
+ parseMcpConfirmRetry: () => parseMcpConfirmRetry,
90
+ parseModernMeta: () => parseModernMeta,
91
+ pathFromToolName: () => pathFromToolName,
92
+ policyAllowed: () => policyAllowed,
93
+ rawToolCallName: () => rawToolCallName,
94
+ renderCallResult: () => renderCallResult,
95
+ resolveMcpConfig: () => resolveMcpConfig,
96
+ serveStdio: () => serveStdio,
97
+ singleHeaderValue: () => singleHeaderValue,
98
+ toolName: () => toolName,
99
+ validModernRequestId: () => validModernRequestId,
100
+ verifyMcpConfirmState: () => verifyMcpConfirmState
101
+ });
102
+
103
+ // src/mcp/types.ts
104
+
105
+
106
+
107
+
108
+
109
+
110
+ var _server = require('@modelcontextprotocol/server');
111
+
112
+ // src/mcp/args.ts
113
+ var MCP_ARGS_PROPERTY = "args";
114
+ var NOTE_ARGS_FLAG_TAKEN = 'Takes positional arguments that cannot be passed over MCP: its --args flag holds the "args" property.';
115
+ function mcpArgsPublished(leaf) {
116
+ if (!leaf.args || leaf.args.length === 0) return false;
117
+ return !Object.prototype.hasOwnProperty.call(
118
+ _nullishCoalesce(leaf.properties, () => ( {})),
119
+ MCP_ARGS_PROPERTY
120
+ );
121
+ }
122
+ function mcpToolDescription(leaf) {
123
+ const desc = leaf.description;
124
+ if (!leaf.args || leaf.args.length === 0 || mcpArgsPublished(leaf)) {
125
+ return desc;
126
+ }
127
+ return desc === "" ? NOTE_ARGS_FLAG_TAKEN : `${desc} ${NOTE_ARGS_FLAG_TAKEN}`;
128
+ }
129
+ function mcpInputSchema(leaf) {
130
+ const properties = { ..._nullishCoalesce(leaf.properties, () => ( {})) };
131
+ const required = [..._nullishCoalesce(leaf.required, () => ( []))];
132
+ if (mcpArgsPublished(leaf)) {
133
+ const declared = _nullishCoalesce(leaf.args, () => ( []));
134
+ const prop = {
135
+ type: "array",
136
+ items: { type: "string" },
137
+ description: argsDescription(declared)
138
+ };
139
+ const n = requiredCount(declared);
140
+ if (n > 0) {
141
+ prop.minItems = n;
142
+ required.push(MCP_ARGS_PROPERTY);
143
+ }
144
+ properties[MCP_ARGS_PROPERTY] = prop;
145
+ }
146
+ const schema = { type: "object", properties };
147
+ if (required.length > 0) schema.required = required;
148
+ return schema;
149
+ }
150
+ function mcpSplitArguments(leaf, args) {
151
+ if (!mcpArgsPublished(leaf)) return { flags: args };
152
+ const declared = _nullishCoalesce(leaf.args, () => ( []));
153
+ const src = _nullishCoalesce(args, () => ( {}));
154
+ if (!Object.prototype.hasOwnProperty.call(src, MCP_ARGS_PROPERTY)) {
155
+ return _nullishCoalesce(requireArgs(declared, []), () => ( { flags: args }));
156
+ }
157
+ const flags = {};
158
+ for (const [k, v] of Object.entries(src)) {
159
+ if (k !== MCP_ARGS_PROPERTY) flags[k] = v;
160
+ }
161
+ const raw = src[MCP_ARGS_PROPERTY];
162
+ if (raw !== null && !Array.isArray(raw)) {
163
+ return { error: '"args" must be an array of strings' };
164
+ }
165
+ const list = _nullishCoalesce(raw, () => ( []));
166
+ if (!list.every((v) => typeof v === "string")) {
167
+ return { error: '"args" must be an array of strings' };
168
+ }
169
+ const positional = list;
170
+ const missing = requireArgs(declared, positional);
171
+ if (missing) return missing;
172
+ return {
173
+ flags: Object.keys(flags).length > 0 ? flags : void 0,
174
+ args: positional
175
+ };
176
+ }
177
+ function requireArgs(declared, supplied) {
178
+ if (supplied.length < requiredCount(declared)) {
179
+ return {
180
+ error: `missing required argument: ${_nullishCoalesce(_optionalChain([declared, 'access', _ => _[supplied.length], 'optionalAccess', _2 => _2.name]), () => ( ""))}`
181
+ };
182
+ }
183
+ return void 0;
184
+ }
185
+ function requiredCount(declared) {
186
+ return declared.filter((a) => a.required).length;
187
+ }
188
+ function argsDescription(declared) {
189
+ const names = declared.map((a) => a.required ? a.name : `${a.name}?`);
190
+ return `Positional arguments in order: ${names.join(", ")}`;
191
+ }
192
+
193
+ // src/mcp/types.ts
194
+ var META_KEY_PROTOCOL_VERSION = _server.PROTOCOL_VERSION_META_KEY;
195
+ var META_KEY_CLIENT_INFO = _server.CLIENT_INFO_META_KEY;
196
+ var META_KEY_CLIENT_CAPABILITIES = _server.CLIENT_CAPABILITIES_META_KEY;
197
+ var META_KEY_SERVER_INFO = _server.SERVER_INFO_META_KEY;
198
+ var HEADER_MCP_PROTOCOL_VERSION = "MCP-Protocol-Version";
199
+ var HEADER_MCP_METHOD = "Mcp-Method";
200
+ var HEADER_MCP_NAME = "Mcp-Name";
201
+ var MCP_ERR_PARSE = _server.ProtocolErrorCode.ParseError;
202
+ var MCP_ERR_INVALID_REQUEST = _server.ProtocolErrorCode.InvalidRequest;
203
+ var MCP_ERR_METHOD_NOT_FOUND = _server.ProtocolErrorCode.MethodNotFound;
204
+ var MCP_ERR_INVALID_PARAMS = _server.ProtocolErrorCode.InvalidParams;
205
+ var MCP_ERR_INTERNAL = _server.ProtocolErrorCode.InternalError;
206
+ var MCP_ERR_HEADER_MISMATCH = -32020;
207
+ var MCP_ERR_MISSING_CLIENT_CAPABILITY = _server.ProtocolErrorCode.MissingRequiredClientCapability;
208
+ var MCP_ERR_UNSUPPORTED_VERSION = _server.ProtocolErrorCode.UnsupportedProtocolVersion;
209
+ var MCP_SPEC_2024_11_05 = "2024-11-05";
210
+ var MCP_SPEC_2026_07_28 = "2026-07-28";
211
+ var RESULT_TYPE_COMPLETE = "complete";
212
+ var RESULT_TYPE_INPUT_REQUIRED = "input_required";
213
+ var DEFAULT_MCP_SERVER_NAME = "cmdsurface";
214
+ var DEFAULT_MCP_SERVER_VERSION = "0.0.0";
215
+ var DEFAULT_MCP_PATH = "/mcp";
216
+ var DEFAULT_TOOL_NAME_SEPARATOR = ".";
217
+ var SURFACE_CLI = "cli";
218
+ var SURFACE_LIB = "lib";
219
+ var SURFACE_MCP = "mcp";
220
+ function defaultPolicy() {
221
+ return {
222
+ allowDestructiveOn: [],
223
+ defaultEnabled: [SURFACE_CLI, SURFACE_LIB, SURFACE_MCP]
224
+ };
225
+ }
226
+ function policyAllowed(p, cls, s) {
227
+ if (s === SURFACE_CLI || s === SURFACE_LIB) return true;
228
+ if (!cls.destructive) return true;
229
+ return (_nullishCoalesce(p.allowDestructiveOn, () => ( []))).includes(s);
230
+ }
231
+ var DestructiveBlockedError = class extends Error {
232
+ constructor(pathLabel, surface) {
233
+ super(
234
+ `cmdsurface: destructive command blocked on this surface: ${pathLabel} on ${surface}`
235
+ );
236
+ this.name = "DestructiveBlockedError";
237
+ }
238
+ };
239
+ var UnknownCommandError = class extends Error {
240
+ constructor(message = "unknown command") {
241
+ super(message);
242
+ this.name = "UnknownCommandError";
243
+ }
244
+ };
245
+ var SurfaceNotEnabledError = class extends Error {
246
+ constructor(message = "surface not enabled") {
247
+ super(message);
248
+ this.name = "SurfaceNotEnabledError";
249
+ }
250
+ };
251
+ var MCP_AUTH_CHALLENGE = "Bearer";
252
+ function resolveMcpConfig(opts = {}) {
253
+ let legacyEnabled = true;
254
+ let modernEnabled = true;
255
+ if (opts.specVersions !== void 0) {
256
+ if (opts.specVersions.length === 0) {
257
+ throw new Error(
258
+ "cmdsurface: specVersions: at least one spec version required"
259
+ );
260
+ }
261
+ legacyEnabled = false;
262
+ modernEnabled = false;
263
+ for (const v of opts.specVersions) {
264
+ if (v === MCP_SPEC_2024_11_05) legacyEnabled = true;
265
+ else if (v === MCP_SPEC_2026_07_28) modernEnabled = true;
266
+ else {
267
+ throw new Error(
268
+ `cmdsurface: specVersions: unrecognized version "${v}"`
269
+ );
270
+ }
271
+ }
272
+ }
273
+ let cacheTtlMs = 0;
274
+ let cacheScope = "private";
275
+ if (opts.cacheHints !== void 0) {
276
+ const ttl = _nullishCoalesce(opts.cacheHints.ttlMs, () => ( 0));
277
+ if (ttl < 0) {
278
+ throw new Error("cmdsurface: cacheHints: negative ttl");
279
+ }
280
+ cacheTtlMs = Math.trunc(ttl);
281
+ const scope = _nullishCoalesce(opts.cacheHints.cacheScope, () => ( "private"));
282
+ if (scope !== "public" && scope !== "private") {
283
+ throw new Error(
284
+ `cmdsurface: cacheHints: unknown cache scope ${String(scope)}`
285
+ );
286
+ }
287
+ cacheScope = scope;
288
+ }
289
+ let confirmationKey;
290
+ if (opts.confirmationKey !== void 0) {
291
+ const key = typeof opts.confirmationKey === "string" ? new TextEncoder().encode(opts.confirmationKey) : opts.confirmationKey;
292
+ if (key.length === 0) {
293
+ throw new Error("cmdsurface: confirmationKey: empty key");
294
+ }
295
+ confirmationKey = key;
296
+ }
297
+ const toolNameSeparator = _nullishCoalesce(opts.toolNameSeparator, () => ( DEFAULT_TOOL_NAME_SEPARATOR));
298
+ if (toolNameSeparator === "") {
299
+ throw new Error("cmdsurface: toolNameSeparator: empty separator");
300
+ }
301
+ return {
302
+ path: _nullishCoalesce(opts.path, () => ( DEFAULT_MCP_PATH)),
303
+ serverName: _nullishCoalesce(_optionalChain([opts, 'access', _3 => _3.serverInfo, 'optionalAccess', _4 => _4.name]), () => ( DEFAULT_MCP_SERVER_NAME)),
304
+ serverVersion: _nullishCoalesce(_optionalChain([opts, 'access', _5 => _5.serverInfo, 'optionalAccess', _6 => _6.version]), () => ( DEFAULT_MCP_SERVER_VERSION)),
305
+ legacyEnabled,
306
+ modernEnabled,
307
+ cacheTtlMs,
308
+ cacheScope,
309
+ originAllowlist: _nullishCoalesce(opts.originAllowlist, () => ( [])),
310
+ confirmationKey,
311
+ policy: _nullishCoalesce(opts.policy, () => ( defaultPolicy())),
312
+ verifier: opts.verifier,
313
+ toolNameSeparator,
314
+ audit: opts.audit
315
+ };
316
+ }
317
+ function toolName(path, separator = DEFAULT_TOOL_NAME_SEPARATOR) {
318
+ return path.join(separator);
319
+ }
320
+ function pathFromToolName(name, separator = DEFAULT_TOOL_NAME_SEPARATOR) {
321
+ if (name === "") return [];
322
+ return name.split(separator);
323
+ }
324
+ function checkToolNameSeparator(leaves, separator) {
325
+ if (separator === DEFAULT_TOOL_NAME_SEPARATOR) return;
326
+ for (const leaf of leaves) {
327
+ for (const seg of leaf.path) {
328
+ if (seg.includes(separator)) {
329
+ throw new Error(
330
+ `cmdsurface: toolNameSeparator: command ${JSON.stringify(seg)} in ${JSON.stringify(leaf.path.join(" "))} contains separator ${JSON.stringify(separator)}`
331
+ );
332
+ }
333
+ }
334
+ }
335
+ }
336
+ function buildToolEnvelope(leaf, separator = DEFAULT_TOOL_NAME_SEPARATOR) {
337
+ return {
338
+ name: toolName(leaf.path, separator),
339
+ description: mcpToolDescription(leaf),
340
+ inputSchema: mcpInputSchema(leaf)
341
+ };
342
+ }
343
+ function renderCallResult(res) {
344
+ const content = [
345
+ { type: "text", text: res.stdout }
346
+ ];
347
+ if (res.stderr) {
348
+ content.push({ type: "text", text: `[stderr] ${res.stderr}` });
349
+ }
350
+ if (res.data !== void 0 && res.data !== null) {
351
+ content.push({ type: "text", text: canonicalJSONStringify(res.data) });
352
+ }
353
+ return { content, isError: res.exitCode !== 0 };
354
+ }
355
+ function errorResultBlock(msg) {
356
+ return {
357
+ content: [{ type: "text", text: msg }],
358
+ isError: true
359
+ };
360
+ }
361
+ var RawJSON = class {
362
+ constructor(raw) {
363
+ this.raw = raw;
364
+ }
365
+ };
366
+ function canonicalJSONStringify(value) {
367
+ if (value instanceof RawJSON) return value.raw;
368
+ if (value === null || typeof value !== "object") {
369
+ return JSON.stringify(value);
370
+ }
371
+ if (Array.isArray(value)) {
372
+ return `[${value.map(canonicalJSONStringify).join(",")}]`;
373
+ }
374
+ const src = value;
375
+ const parts = [];
376
+ for (const key of Object.keys(src).sort()) {
377
+ const v = src[key];
378
+ if (v === void 0) continue;
379
+ parts.push(`${JSON.stringify(key)}:${canonicalJSONStringify(v)}`);
380
+ }
381
+ return `{${parts.join(",")}}`;
382
+ }
383
+ function encodeEnvelope(env) {
384
+ const parts = ['"jsonrpc":"2.0"'];
385
+ if (env.id !== void 0) {
386
+ parts.push(`"id":${env.id.raw}`);
387
+ }
388
+ if (env.error !== void 0) {
389
+ const errParts = [
390
+ `"code":${JSON.stringify(env.error.code)}`,
391
+ `"message":${JSON.stringify(env.error.message)}`
392
+ ];
393
+ if (env.error.data !== void 0) {
394
+ errParts.push(`"data":${canonicalJSONStringify(env.error.data)}`);
395
+ }
396
+ parts.push(`"error":{${errParts.join(",")}}`);
397
+ } else if (env.result !== void 0) {
398
+ parts.push(`"result":${canonicalJSONStringify(env.result)}`);
399
+ }
400
+ return `{${parts.join(",")}}
401
+ `;
402
+ }
403
+
404
+ // src/mcp/identity.ts
405
+ var SCOPES_EXTRA_KEY = "scopes";
406
+ async function establishCaller(verifier, req) {
407
+ if (verifier === void 0) return void 0;
408
+ let ident;
409
+ try {
410
+ ident = await verifier(req);
411
+ } catch (e2) {
412
+ return void 0;
413
+ }
414
+ if (ident === null || typeof ident !== "object") return void 0;
415
+ return ident;
416
+ }
417
+ function invocationMeta(ident, extra) {
418
+ const meta = { surface: SURFACE_MCP, requestedAt: /* @__PURE__ */ new Date() };
419
+ const bag = { ..._nullishCoalesce(extra, () => ( {})) };
420
+ delete bag[SCOPES_EXTRA_KEY];
421
+ if (ident !== void 0) {
422
+ meta.established = "verified";
423
+ if (typeof ident.caller === "string" && ident.caller !== "") {
424
+ meta.caller = ident.caller;
425
+ }
426
+ if (typeof ident.tenant === "string" && ident.tenant !== "") {
427
+ meta.tenant = ident.tenant;
428
+ }
429
+ if (Array.isArray(ident.scopes) && ident.scopes.length > 0) {
430
+ bag[SCOPES_EXTRA_KEY] = ident.scopes.join(",");
431
+ }
432
+ }
433
+ if (Object.keys(bag).length > 0) meta.extra = bag;
434
+ return meta;
435
+ }
436
+
437
+ // src/mcp/audit.ts
438
+ var MCP_AUDIT_AUTH_REFUSED = "cmdsurface: authentication refused";
439
+ var MCP_AUDIT_CONFIRMATION_REQUIRED = "mcpsdk: confirmation required";
440
+ var MCP_AUDIT_CONFIRMATION_DECLINED = "mcpsdk: confirmation declined";
441
+ var MCP_AUDIT_CONFIRMATION_STATE_REJECTED = "mcpsdk: confirmation requestState failed verification";
442
+ var MCP_AUDIT_DESTRUCTIVE_BLOCKED = "cmdsurface: destructive command blocked on this surface";
443
+ var MCP_CONFIRM_REJECTION_STATE = "request_state_verification_failed";
444
+ function auditRefusal(hook, path, specVersion, error, extra) {
445
+ if (hook === void 0) return;
446
+ const record = {
447
+ path: [...path],
448
+ surface: "mcp",
449
+ requestedAt: /* @__PURE__ */ new Date(),
450
+ specVersion,
451
+ error,
452
+ extra: { mcp_spec_version: specVersion, ..._nullishCoalesce(extra, () => ( {})) }
453
+ };
454
+ try {
455
+ hook(record);
456
+ } catch (e3) {
457
+ }
458
+ }
459
+
460
+ // src/mcp/legacy.ts
461
+ function writeResult(id, result, status) {
462
+ return jsonResponse(status, encodeEnvelope({ id, result }));
463
+ }
464
+ function writeError(id, error, status) {
465
+ return jsonResponse(status, encodeEnvelope({ id, error }));
466
+ }
467
+ function parseErrorResponse(body) {
468
+ return writeError(
469
+ void 0,
470
+ { code: MCP_ERR_PARSE, message: `parse error: ${goJSONParseMessage(body)}` },
471
+ 400
472
+ );
473
+ }
474
+ function goJSONParseMessage(body) {
475
+ const trimmed = body.replace(/^[\s]*/, "");
476
+ if (trimmed.startsWith("{")) {
477
+ const rest = trimmed.slice(1).replace(/^[\s]*/, "");
478
+ const ch2 = rest[0];
479
+ if (ch2 !== void 0 && ch2 !== '"' && ch2 !== "}") {
480
+ return `invalid character '${ch2}' looking for beginning of object key string`;
481
+ }
482
+ }
483
+ const ch = trimmed[0];
484
+ if (ch !== void 0) {
485
+ return `invalid character '${ch}' looking for beginning of value`;
486
+ }
487
+ return "unexpected end of JSON input";
488
+ }
489
+ var LegacyMcpHandler = class {
490
+ constructor(bridge, cfg) {
491
+ this.bridge = bridge;
492
+ this.cfg = cfg;
493
+ }
494
+ /**
495
+ * Routes one already-parsed JSON-RPC request by method. An unknown
496
+ * method returns -32601 at HTTP 200 — today's behavior, preserved
497
+ * deliberately (the modern handler uses 404 instead; the asymmetry
498
+ * is required by byte-for-byte preservation).
499
+ */
500
+ async serve(req, rpc) {
501
+ if (rpc.jsonrpc !== void 0 && rpc.jsonrpc !== "2.0") {
502
+ return writeError(
503
+ rpc.id,
504
+ { code: MCP_ERR_INVALID_REQUEST, message: "invalid jsonrpc version" },
505
+ 400
506
+ );
507
+ }
508
+ if (rpc.id === void 0) {
509
+ return acceptedResponse();
510
+ }
511
+ switch (rpc.method) {
512
+ case "initialize":
513
+ return this.handleInitialize(rpc);
514
+ case "ping":
515
+ return writeResult(rpc.id, {}, 200);
516
+ case "tools/list":
517
+ return this.handleToolsList(rpc);
518
+ case "tools/call":
519
+ return this.handleToolsCall(req, rpc);
520
+ default:
521
+ return writeError(
522
+ rpc.id,
523
+ {
524
+ code: MCP_ERR_METHOD_NOT_FOUND,
525
+ message: `method not found: ${rpc.method}`
526
+ },
527
+ 200
528
+ );
529
+ }
530
+ }
531
+ /** The minimal initialize response: version, capabilities, identity. */
532
+ handleInitialize(rpc) {
533
+ return writeResult(
534
+ rpc.id,
535
+ {
536
+ protocolVersion: MCP_SPEC_2024_11_05,
537
+ capabilities: { tools: {} },
538
+ serverInfo: {
539
+ name: this.cfg.serverName,
540
+ version: this.cfg.serverVersion
541
+ }
542
+ },
543
+ 200
544
+ );
545
+ }
546
+ /** One tool envelope per leaf exposed on the MCP surface. */
547
+ handleToolsList(rpc) {
548
+ return writeResult(rpc.id, { tools: this.exposedTools() }, 200);
549
+ }
550
+ exposedTools() {
551
+ const tools = [];
552
+ for (const leaf of this.bridge.leaves()) {
553
+ if (!isExposed(leaf)) continue;
554
+ tools.push(buildToolEnvelope(leaf, this.cfg.toolNameSeparator));
555
+ }
556
+ return tools;
557
+ }
558
+ /**
559
+ * Resolves the leaf, applies the pre-flight auth + confirmation
560
+ * gates, and dispatches through the bridge. Unknown / not-enabled
561
+ * tools are JSON-RPC errors; every other failure (bridge errors,
562
+ * destructive blocks, non-zero exit codes) is an isError result.
563
+ */
564
+ async handleToolsCall(req, rpc) {
565
+ const params = _nullishCoalesce(rpc.params, () => ( {}));
566
+ const name = typeof params.name === "string" ? params.name : "";
567
+ if (name === "") {
568
+ return writeError(
569
+ rpc.id,
570
+ { code: MCP_ERR_INVALID_PARAMS, message: "missing tool name" },
571
+ 200
572
+ );
573
+ }
574
+ const leaf = resolveLeaf(this.bridge, name, this.cfg.toolNameSeparator);
575
+ if (leaf === void 0 || !isExposed(leaf)) {
576
+ return writeError(
577
+ rpc.id,
578
+ { code: MCP_ERR_INVALID_PARAMS, message: `unknown tool: ${name}` },
579
+ 200
580
+ );
581
+ }
582
+ const ident = await establishCaller(this.cfg.verifier, req);
583
+ if (_optionalChain([leaf, 'access', _7 => _7.class, 'optionalAccess', _8 => _8.authRequired]) && ident === void 0) {
584
+ this.audit(leaf, MCP_AUDIT_AUTH_REFUSED);
585
+ return unauthenticated(
586
+ writeResult(rpc.id, errorResultBlock("authentication required"), 401)
587
+ );
588
+ }
589
+ const split = mcpSplitArguments(leaf, params.arguments);
590
+ if (split.error !== void 0) {
591
+ return writeResult(rpc.id, errorResultBlock(split.error), 200);
592
+ }
593
+ if (_optionalChain([leaf, 'access', _9 => _9.class, 'optionalAccess', _10 => _10.requiresConfirmation]) && !headerValue(req, "x-confirm-token")) {
594
+ this.audit(leaf, MCP_AUDIT_CONFIRMATION_REQUIRED);
595
+ return writeResult(
596
+ rpc.id,
597
+ errorResultBlock("confirmation required"),
598
+ 428
599
+ );
600
+ }
601
+ try {
602
+ const res = await this.bridge.invoke({
603
+ path: [...leaf.path],
604
+ ...split.args !== void 0 ? { args: split.args } : {},
605
+ flags: split.flags,
606
+ meta: invocationMeta(ident)
607
+ });
608
+ return writeResult(rpc.id, renderCallResult(res), 200);
609
+ } catch (err) {
610
+ if (err instanceof UnknownCommandError || err instanceof SurfaceNotEnabledError) {
611
+ return writeError(
612
+ rpc.id,
613
+ { code: MCP_ERR_INVALID_PARAMS, message: `unknown tool: ${name}` },
614
+ 200
615
+ );
616
+ }
617
+ if (err instanceof DestructiveBlockedError) {
618
+ this.audit(leaf, MCP_AUDIT_DESTRUCTIVE_BLOCKED);
619
+ }
620
+ return writeResult(
621
+ rpc.id,
622
+ errorResultBlock(errorMessage(err)),
623
+ 200
624
+ );
625
+ }
626
+ }
627
+ /** Emits one 2024-11-05 refusal record to the mount's audit hook. */
628
+ audit(leaf, error) {
629
+ auditRefusal(this.cfg.audit, leaf.path, MCP_SPEC_2024_11_05, error);
630
+ }
631
+ };
632
+ function unauthenticated(res) {
633
+ return {
634
+ ...res,
635
+ headers: { ...res.headers, "WWW-Authenticate": MCP_AUTH_CHALLENGE }
636
+ };
637
+ }
638
+ function isExposed(leaf) {
639
+ return _optionalChain([leaf, 'access', _11 => _11.enabled, 'optionalAccess', _12 => _12[SURFACE_MCP]]) !== false;
640
+ }
641
+ function resolveLeaf(bridge, name, separator) {
642
+ const path = pathFromToolName(name, separator);
643
+ if (path.length === 0) return void 0;
644
+ return bridge.leaves().find(
645
+ (l) => l.path.length === path.length && l.path.every((seg, i) => seg === path[i])
646
+ );
647
+ }
648
+ function headerValue(req, name) {
649
+ const vals = headerValues(req, name);
650
+ return vals.length > 0 ? vals[0] : void 0;
651
+ }
652
+ function headerValues(req, name) {
653
+ const want = name.toLowerCase();
654
+ const out = [];
655
+ for (const [k, v] of Object.entries(_nullishCoalesce(req.headers, () => ( {})))) {
656
+ if (k.toLowerCase() !== want) continue;
657
+ if (Array.isArray(v)) out.push(...v);
658
+ else if (v !== void 0) out.push(v);
659
+ }
660
+ return out;
661
+ }
662
+ function errorMessage(err) {
663
+ if (err instanceof Error) return err.message;
664
+ return String(err);
665
+ }
666
+
667
+ // src/mcp/tasks.ts
668
+ var TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
669
+ var TASK_METHODS = [
670
+ "tasks/get",
671
+ "tasks/update",
672
+ "tasks/list",
673
+ "tasks/result",
674
+ "tasks/cancel"
675
+ ];
676
+ function isTaskMethod(method) {
677
+ return TASK_METHODS.includes(method);
678
+ }
679
+ var TASKS_SUPPORTED = false;
680
+ function taskMethodNotFound(method) {
681
+ return {
682
+ code: MCP_ERR_METHOD_NOT_FOUND,
683
+ msg: `method not found: ${method}`,
684
+ status: 404
685
+ };
686
+ }
687
+ function discoverCapabilities() {
688
+ return { tools: {} };
689
+ }
690
+
691
+ // src/mcp/modern-confirm.ts
692
+ var _crypto = require('crypto');
693
+ var MCP_CONFIRM_KEY = "confirm";
694
+ var MCP_CONFIRM_STATE_TTL_SECONDS = 5 * 60;
695
+ var MCP_CONFIRM_STATE_VERSION = "v1";
696
+ var MAC_DOMAIN = `cmdsurface-mcp-confirm-${MCP_CONFIRM_STATE_VERSION}`;
697
+ var ElicitationConfirmGate = class {
698
+ /**
699
+ * `toolNameSeparator` names the tool in the confirmation prompt, as
700
+ * the mount's `toolNameSeparator` option does in tools/list. `audit`
701
+ * is the mount's refusal hook: it receives the gate's three refusals
702
+ * (confirmation required, declined, state rejected).
703
+ */
704
+ constructor(key, toolNameSeparator, audit) {
705
+ this.toolNameSeparator = toolNameSeparator;
706
+ this.audit = audit;
707
+ /**
708
+ * In-memory records of rejected states, kept beside the mount's
709
+ * `audit` hook for callers holding the gate directly.
710
+ */
711
+ this.rejections = [];
712
+ if (key.length === 0) {
713
+ throw new Error("cmdsurface: confirmationKey: empty key");
714
+ }
715
+ this.key = Buffer.from(key);
716
+ }
717
+ /**
718
+ * Runs the gate for one `tools/call`. Returns `undefined` to proceed
719
+ * with the invocation, or the refusal / interim result plus its HTTP
720
+ * status. The caller stamps the modern envelope onto whatever is
721
+ * returned.
722
+ */
723
+ evaluate(req, leaf, params) {
724
+ if (!_optionalChain([leaf, 'access', _13 => _13.class, 'optionalAccess', _14 => _14.requiresConfirmation])) return void 0;
725
+ if (!clientSupportsFormElicitation(params)) {
726
+ const refused = headerConfirmationGate(req);
727
+ if (refused !== void 0) {
728
+ this.emit(leaf, MCP_AUDIT_CONFIRMATION_REQUIRED);
729
+ }
730
+ return refused;
731
+ }
732
+ const binding = {
733
+ tool: leaf.path.join(" "),
734
+ argsDigest: mcpConfirmArgsDigest(params),
735
+ principal: mcpConfirmPrincipal(req)
736
+ };
737
+ const retry = parseMcpConfirmRetry(params);
738
+ if (retry.state === "") {
739
+ return { result: this.inputRequired(leaf, binding), status: 200 };
740
+ }
741
+ const status = verifyMcpConfirmState(
742
+ this.key,
743
+ retry.state,
744
+ binding,
745
+ nowSeconds()
746
+ );
747
+ if (status === "invalid") {
748
+ this.auditRejection(leaf);
749
+ return { result: this.inputRequired(leaf, binding), status: 200 };
750
+ }
751
+ if (status === "expired") {
752
+ return { result: this.inputRequired(leaf, binding), status: 200 };
753
+ }
754
+ if (retry.action === "accept") return void 0;
755
+ if (retry.action === "decline" || retry.action === "cancel") {
756
+ this.emit(leaf, MCP_AUDIT_CONFIRMATION_DECLINED);
757
+ return { result: errorResultBlock("confirmation declined"), status: 200 };
758
+ }
759
+ return { result: this.inputRequired(leaf, binding), status: 200 };
760
+ }
761
+ /**
762
+ * Builds the `input_required` result envelope for one confirmation
763
+ * prompt: the reserved "confirm" `elicitation/create` form request
764
+ * plus freshly minted `requestState` (satisfying the spec MUST of
765
+ * carrying at least one of `inputRequests` / `requestState` — this
766
+ * flow always carries both). The caller stamps the envelope (_meta
767
+ * serverInfo; `resultType` stays "input_required") and writes it at
768
+ * HTTP 200. Interim `input_required` results are never cacheable: no
769
+ * `ttlMs` / `cacheScope` members, ever.
770
+ */
771
+ inputRequired(leaf, binding) {
772
+ const expiry = nowSeconds() + MCP_CONFIRM_STATE_TTL_SECONDS;
773
+ return {
774
+ resultType: RESULT_TYPE_INPUT_REQUIRED,
775
+ inputRequests: {
776
+ [MCP_CONFIRM_KEY]: {
777
+ method: "elicitation/create",
778
+ params: {
779
+ mode: "form",
780
+ message: `Approve execution of ${JSON.stringify(toolName(leaf.path, this.toolNameSeparator))}?`,
781
+ // No form fields: the approval rides the elicit action
782
+ // (accept / decline / cancel), so the requested schema is
783
+ // the empty object.
784
+ requestedSchema: { type: "object", properties: {} }
785
+ }
786
+ }
787
+ },
788
+ requestState: mintMcpConfirmState(this.key, binding, expiry)
789
+ };
790
+ }
791
+ /**
792
+ * Records a failed `requestState` verification as a
793
+ * security-relevant audit event: in memory on `rejections`, and on
794
+ * the mount's audit hook with the `mcp_confirm_rejection` extra Go's
795
+ * surfaces attach. Best-effort by the same contract: recording never
796
+ * affects the response.
797
+ */
798
+ auditRejection(leaf) {
799
+ this.rejections.push({
800
+ path: leaf.path.join(" "),
801
+ mcpConfirmRejection: MCP_CONFIRM_REJECTION_STATE
802
+ });
803
+ this.emit(leaf, MCP_AUDIT_CONFIRMATION_STATE_REJECTED, {
804
+ mcp_confirm_rejection: MCP_CONFIRM_REJECTION_STATE
805
+ });
806
+ }
807
+ /** Emits one 2026-07-28 refusal record to the mount's audit hook. */
808
+ emit(leaf, error, extra) {
809
+ auditRefusal(this.audit, leaf.path, MCP_SPEC_2026_07_28, error, extra);
810
+ }
811
+ };
812
+ function headerConfirmationGate(req) {
813
+ if (headerValue(req, "x-confirm-token")) return void 0;
814
+ return { result: errorResultBlock("confirmation required"), status: 428 };
815
+ }
816
+ function clientSupportsFormElicitation(params) {
817
+ const meta = plainObject(_optionalChain([plainObject, 'call', _15 => _15(params), 'optionalAccess', _16 => _16._meta]));
818
+ if (meta === void 0) return false;
819
+ const caps = plainObject(meta[META_KEY_CLIENT_CAPABILITIES]);
820
+ if (caps === void 0) return false;
821
+ const modes = plainObject(caps.elicitation);
822
+ if (modes === void 0) return false;
823
+ if (Object.keys(modes).length === 0) return true;
824
+ return "form" in modes;
825
+ }
826
+ function parseMcpConfirmRetry(params) {
827
+ const obj = plainObject(params);
828
+ if (obj === void 0) return { state: "", action: "" };
829
+ const state = typeof obj.requestState === "string" ? obj.requestState : "";
830
+ let action = "";
831
+ const entry = plainObject(_optionalChain([plainObject, 'call', _17 => _17(obj.inputResponses), 'optionalAccess', _18 => _18[MCP_CONFIRM_KEY]]));
832
+ if (entry !== void 0 && typeof entry.action === "string") {
833
+ action = entry.action;
834
+ }
835
+ return { state, action };
836
+ }
837
+ function mcpConfirmPrincipal(req) {
838
+ const auth = headerValue(req, "authorization");
839
+ if (!auth) return "";
840
+ return _crypto.createHash.call(void 0, "sha256").update(auth, "utf8").digest("hex");
841
+ }
842
+ function mcpConfirmArgsDigest(params) {
843
+ const args = _nullishCoalesce(plainObject(_optionalChain([plainObject, 'call', _19 => _19(params), 'optionalAccess', _20 => _20.arguments])), () => ( null));
844
+ const canonical = canonicalJSONStringify(args);
845
+ return _crypto.createHash.call(void 0, "sha256").update(canonical, "utf8").digest("hex");
846
+ }
847
+ function mcpConfirmStateMac(key, binding, expiry) {
848
+ const mac = _crypto.createHmac.call(void 0, "sha256", key);
849
+ for (const part of [
850
+ MAC_DOMAIN,
851
+ String(expiry),
852
+ binding.tool,
853
+ binding.argsDigest,
854
+ binding.principal
855
+ ]) {
856
+ mac.update(`${Buffer.byteLength(part, "utf8")}:${part}`, "utf8");
857
+ }
858
+ return mac.digest();
859
+ }
860
+ function mintMcpConfirmState(key, binding, expiry) {
861
+ const mac = mcpConfirmStateMac(Buffer.from(key), binding, expiry);
862
+ return `${MCP_CONFIRM_STATE_VERSION}.${expiry}.${mac.toString("base64url")}`;
863
+ }
864
+ function verifyMcpConfirmState(key, state, binding, now) {
865
+ const parts = state.split(".");
866
+ if (parts.length !== 3 || parts[0] !== MCP_CONFIRM_STATE_VERSION) {
867
+ return "invalid";
868
+ }
869
+ if (!/^-?\d+$/.test(parts[1])) return "invalid";
870
+ const expiry = Number(parts[1]);
871
+ if (!Number.isSafeInteger(expiry)) return "invalid";
872
+ const tag = decodeBase64Url(parts[2]);
873
+ if (tag === void 0) return "invalid";
874
+ const want = mcpConfirmStateMac(Buffer.from(key), binding, expiry);
875
+ if (tag.length !== want.length || !_crypto.timingSafeEqual.call(void 0, tag, want)) {
876
+ return "invalid";
877
+ }
878
+ if (expiry < now) return "expired";
879
+ return "valid";
880
+ }
881
+ function decodeBase64Url(s) {
882
+ if (!/^[A-Za-z0-9_-]*$/.test(s)) return void 0;
883
+ const buf = Buffer.from(s, "base64url");
884
+ if (buf.toString("base64url") !== s) return void 0;
885
+ return buf;
886
+ }
887
+ function nowSeconds() {
888
+ return Math.floor(Date.now() / 1e3);
889
+ }
890
+ function plainObject(v) {
891
+ if (v === null || v === void 0 || typeof v !== "object") return void 0;
892
+ if (Array.isArray(v)) return void 0;
893
+ return v;
894
+ }
895
+
896
+ // src/mcp/modern.ts
897
+ var SENTINEL_PREFIX = "=?base64?";
898
+ var SENTINEL_SUFFIX = "?=";
899
+ var ModernMcpHandler = class {
900
+ /**
901
+ * `transport` selects the binding. Streamable HTTP mirrors the method,
902
+ * tool name and protocol version into headers and requires them to
903
+ * agree with the body (V4, V6, V7). stdio has no header layer — the
904
+ * body is the only source of truth — so those three checks do not
905
+ * apply there; every other check runs unchanged.
906
+ */
907
+ constructor(bridge, cfg, transport = "http") {
908
+ this.bridge = bridge;
909
+ this.cfg = cfg;
910
+ this.transport = transport;
911
+ if (cfg.confirmationKey !== void 0) {
912
+ this.confirmGate = new ElicitationConfirmGate(
913
+ cfg.confirmationKey,
914
+ cfg.toolNameSeparator,
915
+ cfg.audit
916
+ );
917
+ }
918
+ }
919
+ /**
920
+ * The modern entry point. The validation chain runs in the guide's
921
+ * order V1-V9; the first failure responds and stops. HTTP status is
922
+ * 400/404 only where the spec mandates it — application-level
923
+ * JSON-RPC errors ride HTTP 200, matching legacy's convention.
924
+ */
925
+ async serve(req, rpc) {
926
+ if (!this.originAllowed(req)) {
927
+ return this.writeModernError(rpc, {
928
+ code: MCP_ERR_INVALID_REQUEST,
929
+ msg: "origin not allowed",
930
+ status: 403
931
+ });
932
+ }
933
+ if (rpc.jsonrpc !== void 0 && rpc.jsonrpc !== "2.0") {
934
+ return this.writeModernError(rpc, {
935
+ code: MCP_ERR_INVALID_REQUEST,
936
+ msg: "invalid jsonrpc version",
937
+ status: 400
938
+ });
939
+ }
940
+ if (rpc.id === void 0) {
941
+ return acceptedResponse();
942
+ }
943
+ if (!validModernRequestId(rpc.id)) {
944
+ return this.writeModernError(rpc, {
945
+ code: MCP_ERR_INVALID_REQUEST,
946
+ msg: `invalid request id: must be a string or integer, got ${rpc.id.raw}`,
947
+ status: 400
948
+ });
949
+ }
950
+ const parsed = parseModernMeta(rpc.params);
951
+ if ("error" in parsed) {
952
+ return this.writeModernError(rpc, parsed.error);
953
+ }
954
+ const meta = parsed.meta;
955
+ if (this.transport === "http") {
956
+ const versionErr = this.validateVersionHeader(req, meta);
957
+ if (versionErr) return this.writeModernError(rpc, versionErr);
958
+ }
959
+ if (meta.version !== MCP_SPEC_2026_07_28) {
960
+ return this.writeModernError(rpc, {
961
+ code: MCP_ERR_UNSUPPORTED_VERSION,
962
+ msg: `unsupported protocol version: ${meta.version}`,
963
+ status: 400,
964
+ data: {
965
+ supported: [MCP_SPEC_2026_07_28],
966
+ requested: meta.versionRaw
967
+ }
968
+ });
969
+ }
970
+ if (this.transport === "http") {
971
+ const methodErr = this.validateMethodHeader(req, rpc);
972
+ if (methodErr) return this.writeModernError(rpc, methodErr);
973
+ }
974
+ switch (rpc.method) {
975
+ case "server/discover":
976
+ return this.handleDiscover(rpc);
977
+ case "tools/list":
978
+ return this.handleToolsList(rpc);
979
+ case "tools/call":
980
+ return this.handleToolsCall(req, rpc, meta);
981
+ default:
982
+ if (isTaskMethod(rpc.method)) {
983
+ return this.writeModernError(rpc, taskMethodNotFound(rpc.method));
984
+ }
985
+ return this.writeModernError(rpc, {
986
+ code: MCP_ERR_METHOD_NOT_FOUND,
987
+ msg: `method not found: ${rpc.method}`,
988
+ status: 404
989
+ });
990
+ }
991
+ }
992
+ /** V4: MCP-Protocol-Version header present and equal to _meta's. */
993
+ validateVersionHeader(req, meta) {
994
+ const proto = singleHeaderValue(req, HEADER_MCP_PROTOCOL_VERSION);
995
+ if (!proto.ok) {
996
+ return {
997
+ code: MCP_ERR_HEADER_MISMATCH,
998
+ msg: `${HEADER_MCP_PROTOCOL_VERSION} header sent with conflicting duplicate values`,
999
+ status: 400
1000
+ };
1001
+ }
1002
+ if (proto.value === "") {
1003
+ return {
1004
+ code: MCP_ERR_HEADER_MISMATCH,
1005
+ msg: `missing ${HEADER_MCP_PROTOCOL_VERSION} header`,
1006
+ status: 400
1007
+ };
1008
+ }
1009
+ if (!meta.versionIsText || proto.value !== meta.version) {
1010
+ return {
1011
+ code: MCP_ERR_HEADER_MISMATCH,
1012
+ msg: `${HEADER_MCP_PROTOCOL_VERSION} header ${JSON.stringify(proto.value)} does not match _meta protocolVersion ${goFormatValue(meta.versionRaw)}`,
1013
+ status: 400
1014
+ };
1015
+ }
1016
+ return void 0;
1017
+ }
1018
+ /**
1019
+ * server/discover — the mandatory modern discovery method. Carries
1020
+ * no listChanged flag (notifications unimplemented), no extensions
1021
+ * map (none supported, which is what makes tasks/* method-not-found),
1022
+ * and no instructions.
1023
+ */
1024
+ handleDiscover(rpc) {
1025
+ const res = {
1026
+ supportedVersions: [MCP_SPEC_2026_07_28],
1027
+ capabilities: { tools: {} }
1028
+ };
1029
+ this.applyCacheHints(res);
1030
+ this.stampResultEnvelope(res);
1031
+ return writeResult(rpc.id, res, 200);
1032
+ }
1033
+ /**
1034
+ * Modern tools/list: the same tool envelopes the legacy handler
1035
+ * emits (so schema drift between eras cannot happen), wrapped in
1036
+ * the modern complete-result envelope with cache hints. Pagination
1037
+ * is not implemented — a cursor param is ignored, no nextCursor.
1038
+ */
1039
+ handleToolsList(rpc) {
1040
+ const tools = [];
1041
+ for (const leaf of this.bridge.leaves()) {
1042
+ if (!isExposed(leaf)) continue;
1043
+ tools.push(buildToolEnvelope(leaf, this.cfg.toolNameSeparator));
1044
+ }
1045
+ const res = { tools };
1046
+ this.applyCacheHints(res);
1047
+ this.stampResultEnvelope(res);
1048
+ return writeResult(rpc.id, res, 200);
1049
+ }
1050
+ /**
1051
+ * Modern tools/call: V7, V9, the legacy pre-flight gates, invoke,
1052
+ * render. The shared bridge invoke path keeps the policy gate
1053
+ * identical across eras — there is no way to reach a leaf here that
1054
+ * the legacy path would have blocked. Results carry no cache hints.
1055
+ */
1056
+ async handleToolsCall(req, rpc, meta) {
1057
+ if (this.transport === "http") {
1058
+ const peek = rawToolCallName(rpc.params);
1059
+ const nameErr = this.validateNameHeader(req, peek);
1060
+ if (nameErr) return this.writeModernError(rpc, nameErr);
1061
+ }
1062
+ const params = _nullishCoalesce(rpc.params, () => ( {}));
1063
+ const name = typeof params.name === "string" ? params.name : "";
1064
+ if (name === "") {
1065
+ return writeError(
1066
+ rpc.id,
1067
+ { code: MCP_ERR_INVALID_PARAMS, message: "missing tool name" },
1068
+ 200
1069
+ );
1070
+ }
1071
+ const leaf = resolveLeaf(this.bridge, name, this.cfg.toolNameSeparator);
1072
+ if (leaf === void 0 || !isExposed(leaf)) {
1073
+ return writeError(
1074
+ rpc.id,
1075
+ { code: MCP_ERR_INVALID_PARAMS, message: `unknown tool: ${name}` },
1076
+ 200
1077
+ );
1078
+ }
1079
+ const ident = await establishCaller(this.cfg.verifier, req);
1080
+ if (_optionalChain([leaf, 'access', _21 => _21.class, 'optionalAccess', _22 => _22.authRequired]) && ident === void 0) {
1081
+ this.audit(leaf, MCP_AUDIT_AUTH_REFUSED);
1082
+ return unauthenticated(
1083
+ this.writeCallError(rpc, "authentication required", 401)
1084
+ );
1085
+ }
1086
+ const split = mcpSplitArguments(leaf, params.arguments);
1087
+ if (split.error !== void 0) {
1088
+ return this.writeCallError(rpc, split.error, 200);
1089
+ }
1090
+ const gated = this.confirmationGate(req, leaf, rpc.params);
1091
+ if (gated !== void 0) {
1092
+ return writeResult(
1093
+ rpc.id,
1094
+ this.stampResultEnvelope(gated.result),
1095
+ gated.status
1096
+ );
1097
+ }
1098
+ try {
1099
+ const res = await this.bridge.invoke({
1100
+ path: [...leaf.path],
1101
+ ...split.args !== void 0 ? { args: split.args } : {},
1102
+ flags: split.flags,
1103
+ meta: invocationMeta(ident, modernInvocationExtra(meta))
1104
+ });
1105
+ const out = renderCallResult(res);
1106
+ if (res.data !== void 0 && res.data !== null) {
1107
+ out.structuredContent = res.data;
1108
+ }
1109
+ return writeResult(rpc.id, this.stampResultEnvelope(out), 200);
1110
+ } catch (err) {
1111
+ if (err instanceof UnknownCommandError || err instanceof SurfaceNotEnabledError) {
1112
+ return writeError(
1113
+ rpc.id,
1114
+ { code: MCP_ERR_INVALID_PARAMS, message: `unknown tool: ${name}` },
1115
+ 200
1116
+ );
1117
+ }
1118
+ if (err instanceof DestructiveBlockedError) {
1119
+ this.audit(leaf, MCP_AUDIT_DESTRUCTIVE_BLOCKED);
1120
+ }
1121
+ return this.writeCallError(rpc, errorMessage(err), 200);
1122
+ }
1123
+ }
1124
+ /** Emits one 2026-07-28 refusal record to the mount's audit hook. */
1125
+ audit(leaf, error) {
1126
+ auditRefusal(this.cfg.audit, leaf.path, MCP_SPEC_2026_07_28, error);
1127
+ }
1128
+ /**
1129
+ * Selects and runs the confirmation strategy for one `tools/call`.
1130
+ * Returns `undefined` to proceed with the invocation.
1131
+ *
1132
+ * A leaf that does not require confirmation is never gated. A mount
1133
+ * without a `confirmationKey` has no state to MAC, so the header gate
1134
+ * applies to every client — this is the byte-for-byte preservation
1135
+ * path, identical to what the legacy handler does.
1136
+ */
1137
+ confirmationGate(req, leaf, params) {
1138
+ if (!_optionalChain([leaf, 'access', _23 => _23.class, 'optionalAccess', _24 => _24.requiresConfirmation])) return void 0;
1139
+ if (this.confirmGate === void 0) {
1140
+ const refused = headerConfirmationGate(req);
1141
+ if (refused !== void 0) {
1142
+ this.audit(leaf, MCP_AUDIT_CONFIRMATION_REQUIRED);
1143
+ }
1144
+ return refused;
1145
+ }
1146
+ return this.confirmGate.evaluate(req, leaf, params);
1147
+ }
1148
+ /** V6: Mcp-Method header presence + agreement with the body method. */
1149
+ validateMethodHeader(req, rpc) {
1150
+ const hdr = singleHeaderValue(req, HEADER_MCP_METHOD);
1151
+ if (!hdr.ok) {
1152
+ return {
1153
+ code: MCP_ERR_HEADER_MISMATCH,
1154
+ msg: `${HEADER_MCP_METHOD} header sent with conflicting duplicate values`,
1155
+ status: 400
1156
+ };
1157
+ }
1158
+ if (hdr.value === "") {
1159
+ return {
1160
+ code: MCP_ERR_HEADER_MISMATCH,
1161
+ msg: `missing ${HEADER_MCP_METHOD} header`,
1162
+ status: 400
1163
+ };
1164
+ }
1165
+ if (hdr.value !== rpc.method) {
1166
+ return {
1167
+ code: MCP_ERR_HEADER_MISMATCH,
1168
+ msg: `${HEADER_MCP_METHOD} header ${JSON.stringify(hdr.value)} does not match body method ${JSON.stringify(rpc.method)}`,
1169
+ status: 400
1170
+ };
1171
+ }
1172
+ return void 0;
1173
+ }
1174
+ /**
1175
+ * V7: on tools/call the Mcp-Name header MUST be present, non-empty
1176
+ * after Base64-sentinel decoding, and byte-equal to params.name,
1177
+ * which MUST itself be present. Any violation is a header failure
1178
+ * (-32020 @ 400), decided ahead of any body-shape check: headers
1179
+ * are the routing signal gateways trust without parsing the body,
1180
+ * so an empty or contradicted signal is malformed at the header
1181
+ * layer.
1182
+ */
1183
+ validateNameHeader(req, peek) {
1184
+ const hdr = singleHeaderValue(req, HEADER_MCP_NAME);
1185
+ if (!hdr.ok) {
1186
+ return {
1187
+ code: MCP_ERR_HEADER_MISMATCH,
1188
+ msg: `${HEADER_MCP_NAME} header sent with conflicting duplicate values`,
1189
+ status: 400
1190
+ };
1191
+ }
1192
+ if (hdr.value === "") {
1193
+ return {
1194
+ code: MCP_ERR_HEADER_MISMATCH,
1195
+ msg: `missing ${HEADER_MCP_NAME} header`,
1196
+ status: 400
1197
+ };
1198
+ }
1199
+ const decoded = decodeMcpSentinel(hdr.value);
1200
+ if (decoded === void 0) {
1201
+ return {
1202
+ code: MCP_ERR_HEADER_MISMATCH,
1203
+ msg: `${HEADER_MCP_NAME} header value is not valid base64-sentinel encoded`,
1204
+ status: 400
1205
+ };
1206
+ }
1207
+ if (decoded === "") {
1208
+ return {
1209
+ code: MCP_ERR_HEADER_MISMATCH,
1210
+ msg: `${HEADER_MCP_NAME} header decodes to an empty value`,
1211
+ status: 400
1212
+ };
1213
+ }
1214
+ if (!peek.present) {
1215
+ return {
1216
+ code: MCP_ERR_HEADER_MISMATCH,
1217
+ msg: `${HEADER_MCP_NAME} header present but body params.name is absent`,
1218
+ status: 400
1219
+ };
1220
+ }
1221
+ if (!peek.isString) {
1222
+ return void 0;
1223
+ }
1224
+ if (decoded !== peek.name) {
1225
+ return {
1226
+ code: MCP_ERR_HEADER_MISMATCH,
1227
+ msg: `${HEADER_MCP_NAME} header ${JSON.stringify(decoded)} does not match body params.name ${JSON.stringify(peek.name)}`,
1228
+ status: 400
1229
+ };
1230
+ }
1231
+ return void 0;
1232
+ }
1233
+ /**
1234
+ * Adds the members every modern result envelope carries: resultType
1235
+ * and a result-level _meta with serverInfo built from the mount's
1236
+ * configured identity. A producer that already chose a resultType
1237
+ * keeps it (the MRTR confirmation gate stamps "input_required").
1238
+ */
1239
+ stampResultEnvelope(m) {
1240
+ if (!("resultType" in m)) {
1241
+ m.resultType = RESULT_TYPE_COMPLETE;
1242
+ }
1243
+ m._meta = {
1244
+ [META_KEY_SERVER_INFO]: {
1245
+ name: this.cfg.serverName,
1246
+ version: this.cfg.serverVersion
1247
+ }
1248
+ };
1249
+ return m;
1250
+ }
1251
+ /**
1252
+ * Adds ttlMs and cacheScope to a cacheable complete-result —
1253
+ * server/discover and tools/list only; tools/call carries none.
1254
+ * Defaults are ttlMs 0 (immediately stale: the leaf set can mutate
1255
+ * at runtime and no list_changed notification exists) and
1256
+ * cacheScope "private".
1257
+ */
1258
+ applyCacheHints(m) {
1259
+ m.ttlMs = this.cfg.cacheTtlMs;
1260
+ m.cacheScope = this.cfg.cacheScope;
1261
+ return m;
1262
+ }
1263
+ /** Opt-in Origin allowlist; a request without Origin is never refused. */
1264
+ originAllowed(req) {
1265
+ if (this.cfg.originAllowlist.length === 0) return true;
1266
+ const origin = headerValue(req, "origin");
1267
+ if (!origin) return true;
1268
+ return this.cfg.originAllowlist.includes(origin);
1269
+ }
1270
+ /**
1271
+ * Writes a modern JSON-RPC error. When the rejected request's
1272
+ * method is "initialize" the message additionally names the
1273
+ * supported versions: a legacy client has no fall-forward
1274
+ * mechanism, so the version list in the error text is its only
1275
+ * recovery hint.
1276
+ */
1277
+ writeModernError(rpc, e) {
1278
+ let msg = e.msg;
1279
+ if (rpc.method === "initialize") {
1280
+ msg += `; supported protocol versions: ${MCP_SPEC_2026_07_28}`;
1281
+ }
1282
+ return writeError(
1283
+ rpc.id,
1284
+ { code: e.code, message: msg, data: e.data },
1285
+ e.status
1286
+ );
1287
+ }
1288
+ /** An isError tools/call result with the modern envelope stamped on. */
1289
+ writeCallError(rpc, msg, status) {
1290
+ return writeResult(
1291
+ rpc.id,
1292
+ this.stampResultEnvelope(errorResultBlock(msg)),
1293
+ status
1294
+ );
1295
+ }
1296
+ };
1297
+ function singleHeaderValue(req, name) {
1298
+ const vals = headerValues(req, name);
1299
+ if (vals.length === 0) return { value: "", ok: true };
1300
+ if (vals.length === 1) return { value: vals[0], ok: true };
1301
+ for (const v of vals.slice(1)) {
1302
+ if (v !== vals[0]) return { value: "", ok: false };
1303
+ }
1304
+ return { value: vals[0], ok: true };
1305
+ }
1306
+ function validModernRequestId(id) {
1307
+ const raw = id.raw.trim();
1308
+ if (raw === "null") return false;
1309
+ let parsed;
1310
+ try {
1311
+ parsed = JSON.parse(raw);
1312
+ } catch (e4) {
1313
+ return false;
1314
+ }
1315
+ if (typeof parsed === "string") return true;
1316
+ if (typeof parsed === "number") return Number.isInteger(parsed);
1317
+ return false;
1318
+ }
1319
+ function parseModernMeta(params) {
1320
+ const fail = (msg) => ({
1321
+ error: { code: MCP_ERR_INVALID_PARAMS, msg, status: 400 }
1322
+ });
1323
+ if (params === void 0 || params === null || typeof params !== "object") {
1324
+ return fail("missing required params._meta");
1325
+ }
1326
+ const metaRaw = params._meta;
1327
+ if (metaRaw === void 0 || metaRaw === null || typeof metaRaw !== "object" || Array.isArray(metaRaw)) {
1328
+ return fail("missing required params._meta");
1329
+ }
1330
+ const metaObj = metaRaw;
1331
+ if (!(META_KEY_PROTOCOL_VERSION in metaObj)) {
1332
+ return fail(`missing required _meta key: ${META_KEY_PROTOCOL_VERSION}`);
1333
+ }
1334
+ if (!(META_KEY_CLIENT_CAPABILITIES in metaObj)) {
1335
+ return fail(`missing required _meta key: ${META_KEY_CLIENT_CAPABILITIES}`);
1336
+ }
1337
+ const verRaw = metaObj[META_KEY_PROTOCOL_VERSION];
1338
+ const meta = {
1339
+ version: typeof verRaw === "string" ? verRaw : "",
1340
+ versionIsText: typeof verRaw === "string",
1341
+ versionRaw: verRaw,
1342
+ hasClientInfo: false
1343
+ };
1344
+ const ci = metaObj[META_KEY_CLIENT_INFO];
1345
+ if (ci !== void 0 && ci !== null && typeof ci === "object" && !Array.isArray(ci)) {
1346
+ const obj = ci;
1347
+ meta.hasClientInfo = true;
1348
+ meta.clientName = typeof obj.name === "string" ? obj.name : "";
1349
+ meta.clientVersion = typeof obj.version === "string" ? obj.version : "";
1350
+ }
1351
+ return { meta };
1352
+ }
1353
+ function rawToolCallName(params) {
1354
+ if (params === void 0 || params === null || typeof params !== "object" || Array.isArray(params)) {
1355
+ return { name: "", present: false, isString: false };
1356
+ }
1357
+ const obj = params;
1358
+ if (!("name" in obj)) return { name: "", present: false, isString: false };
1359
+ const v = obj.name;
1360
+ if (typeof v !== "string") return { name: "", present: true, isString: false };
1361
+ return { name: v, present: true, isString: true };
1362
+ }
1363
+ function decodeMcpSentinel(v) {
1364
+ if (!v.startsWith(SENTINEL_PREFIX) || !v.endsWith(SENTINEL_SUFFIX)) {
1365
+ return v;
1366
+ }
1367
+ const inner = v.slice(SENTINEL_PREFIX.length, v.length - SENTINEL_SUFFIX.length);
1368
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(inner) || inner.length % 4 !== 0) {
1369
+ return void 0;
1370
+ }
1371
+ const buf = Buffer.from(inner, "base64");
1372
+ if (buf.toString("base64") !== inner) return void 0;
1373
+ return buf.toString("utf8");
1374
+ }
1375
+ function modernInvocationExtra(meta) {
1376
+ const extra = {
1377
+ mcp_spec_version: MCP_SPEC_2026_07_28
1378
+ };
1379
+ if (meta.hasClientInfo) {
1380
+ extra.mcp_client_name = _nullishCoalesce(meta.clientName, () => ( ""));
1381
+ extra.mcp_client_version = _nullishCoalesce(meta.clientVersion, () => ( ""));
1382
+ }
1383
+ return extra;
1384
+ }
1385
+ function goFormatValue(v) {
1386
+ if (v === null || v === void 0) return "<nil>";
1387
+ if (typeof v === "string") return v;
1388
+ if (typeof v === "boolean") return v ? "true" : "false";
1389
+ if (typeof v === "number") return String(v);
1390
+ return JSON.stringify(v);
1391
+ }
1392
+
1393
+ // src/mcp/dispatch.ts
1394
+ function jsonResponse(status, body) {
1395
+ return {
1396
+ status,
1397
+ headers: { "Content-Type": "application/json" },
1398
+ body
1399
+ };
1400
+ }
1401
+ function acceptedResponse() {
1402
+ return { status: 202, headers: {}, body: "" };
1403
+ }
1404
+ function detectMcpEra(req, rpc) {
1405
+ if (rpc.method === "initialize") return "legacy";
1406
+ if (rpc.method === "server/discover") return "modern";
1407
+ if (headerValues(req, HEADER_MCP_METHOD).length > 0) return "modern";
1408
+ if (headerValues(req, HEADER_MCP_NAME).length > 0) return "modern";
1409
+ if (hasModernMetaMarker(rpc.params)) return "modern";
1410
+ return "legacy";
1411
+ }
1412
+ function hasModernMetaMarker(params) {
1413
+ if (params === null || typeof params !== "object" || Array.isArray(params)) {
1414
+ return false;
1415
+ }
1416
+ const meta = params._meta;
1417
+ if (meta === null || typeof meta !== "object" || Array.isArray(meta)) {
1418
+ return false;
1419
+ }
1420
+ return META_KEY_PROTOCOL_VERSION in meta;
1421
+ }
1422
+ var MCP_DISPATCHER_FACTORY = /* @__PURE__ */ Symbol.for(
1423
+ "hop-top/kit/mcp/dispatcher-factory"
1424
+ );
1425
+ function dispatcherFactoryOf(handler) {
1426
+ return handler[MCP_DISPATCHER_FACTORY];
1427
+ }
1428
+ function createMcpHandler(bridge, opts = {}) {
1429
+ const cfg = resolveMcpConfig(opts);
1430
+ const dispatcher = new McpDispatcher(bridge, cfg);
1431
+ const handler = (req) => dispatcher.handle(req);
1432
+ handler[MCP_DISPATCHER_FACTORY] = (transport) => new McpDispatcher(bridge, cfg, transport);
1433
+ return handler;
1434
+ }
1435
+ function mcpMountConfig(opts = {}) {
1436
+ return resolveMcpConfig(opts);
1437
+ }
1438
+ var McpDispatcher = class {
1439
+ constructor(bridge, cfg, transport = "http") {
1440
+ this.cfg = cfg;
1441
+ checkToolNameSeparator(bridge.leaves(), cfg.toolNameSeparator);
1442
+ this.legacy = new LegacyMcpHandler(bridge, cfg);
1443
+ this.modern = new ModernMcpHandler(bridge, cfg, transport);
1444
+ }
1445
+ async handle(req) {
1446
+ const verb = (req.method || "POST").toUpperCase();
1447
+ if (verb !== "POST") {
1448
+ if (this.cfg.modernEnabled && (verb === "GET" || verb === "DELETE")) {
1449
+ return methodNotAllowedResponse();
1450
+ }
1451
+ return methodNotAllowedResponse();
1452
+ }
1453
+ const body = req.body;
1454
+ if (body === void 0) {
1455
+ return writeError(
1456
+ void 0,
1457
+ {
1458
+ code: MCP_ERR_INTERNAL,
1459
+ message: "read request body: unexpected EOF"
1460
+ },
1461
+ 400
1462
+ );
1463
+ }
1464
+ let rpc;
1465
+ try {
1466
+ rpc = parseJsonRpcRequest(body);
1467
+ } catch (e5) {
1468
+ return parseErrorResponse(body);
1469
+ }
1470
+ return this.dispatch(req, rpc);
1471
+ }
1472
+ /**
1473
+ * Routes one already-parsed request to its era's handler (D2-D4).
1474
+ * The transport-neutral core behind `handle`; stdio calls it directly
1475
+ * after doing its own framing and parsing.
1476
+ */
1477
+ dispatch(req, rpc) {
1478
+ if (this.cfg.modernEnabled && !this.cfg.legacyEnabled) {
1479
+ return this.modern.serve(req, rpc);
1480
+ }
1481
+ if (this.cfg.legacyEnabled && !this.cfg.modernEnabled) {
1482
+ return this.legacy.serve(req, rpc);
1483
+ }
1484
+ switch (detectMcpEra(req, rpc)) {
1485
+ case "modern":
1486
+ return this.modern.serve(req, rpc);
1487
+ default:
1488
+ return this.legacy.serve(req, rpc);
1489
+ }
1490
+ }
1491
+ };
1492
+ function methodNotAllowedResponse() {
1493
+ return jsonResponse(
1494
+ 405,
1495
+ '{"jsonrpc":"2.0","error":{"code":-32600,"message":"method not allowed"}}\n'
1496
+ );
1497
+ }
1498
+ function parseJsonRpcRequest(body) {
1499
+ const decoded = JSON.parse(body);
1500
+ if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded)) {
1501
+ throw new SyntaxError("not a JSON-RPC object");
1502
+ }
1503
+ const obj = decoded;
1504
+ const out = {
1505
+ method: typeof obj.method === "string" ? obj.method : ""
1506
+ };
1507
+ if (typeof obj.jsonrpc === "string") out.jsonrpc = obj.jsonrpc;
1508
+ if ("id" in obj) out.id = new RawJSON(rawIdBytes(body, obj.id));
1509
+ if ("params" in obj) out.params = obj.params;
1510
+ return out;
1511
+ }
1512
+ function rawIdBytes(_body, id) {
1513
+ return _nullishCoalesce(JSON.stringify(id), () => ( "null"));
1514
+ }
1515
+
1516
+ // src/mcp/stdio.ts
1517
+ var _readline = require('readline');
1518
+ function serveStdio(target, opts = {}) {
1519
+ const serve = resolveServe(target, opts.mount);
1520
+ const input = _nullishCoalesce(opts.input, () => ( process.stdin));
1521
+ const output = _nullishCoalesce(opts.output, () => ( process.stdout));
1522
+ const log = _nullishCoalesce(opts.log, () => ( process.stderr));
1523
+ const inFlight = /* @__PURE__ */ new Set();
1524
+ const write = (line) => {
1525
+ output.write(line.endsWith("\n") ? line : `${line}
1526
+ `);
1527
+ };
1528
+ const warn = (msg) => {
1529
+ log.write(`mcp stdio: ${msg}
1530
+ `);
1531
+ };
1532
+ const rl = _readline.createInterface.call(void 0, { input, crlfDelay: Infinity, terminal: false });
1533
+ rl.on("line", (line) => {
1534
+ const task = handleLine(line, serve, write, warn);
1535
+ if (task === void 0) return;
1536
+ inFlight.add(task);
1537
+ void task.finally(() => inFlight.delete(task));
1538
+ });
1539
+ const onInputError = (err) => {
1540
+ warn(`input error: ${errorMessage(err)}`);
1541
+ rl.close();
1542
+ };
1543
+ const onOutputError = (err) => {
1544
+ warn(`output error: ${errorMessage(err)}`);
1545
+ rl.close();
1546
+ };
1547
+ input.on("error", onInputError);
1548
+ output.on("error", onOutputError);
1549
+ const done = new Promise((resolve) => {
1550
+ rl.once("close", () => {
1551
+ void drain(inFlight).then(() => {
1552
+ input.off("error", onInputError);
1553
+ output.off("error", onOutputError);
1554
+ resolve();
1555
+ });
1556
+ });
1557
+ });
1558
+ return {
1559
+ done,
1560
+ close() {
1561
+ rl.close();
1562
+ return done;
1563
+ }
1564
+ };
1565
+ }
1566
+ function resolveServe(target, mount) {
1567
+ if (typeof target === "function") {
1568
+ if (mount !== void 0) {
1569
+ throw new TypeError(
1570
+ "serveStdio: mount options apply to a bridge; a handler carries its own"
1571
+ );
1572
+ }
1573
+ const factory = dispatcherFactoryOf(target);
1574
+ if (factory !== void 0) {
1575
+ const dispatcher2 = factory("stdio");
1576
+ return (req, rpc) => dispatcher2.dispatch(req, rpc);
1577
+ }
1578
+ return (req) => target(req);
1579
+ }
1580
+ const dispatcher = new McpDispatcher(target, resolveMcpConfig(_nullishCoalesce(mount, () => ( {}))), "stdio");
1581
+ return (req, rpc) => dispatcher.dispatch(req, rpc);
1582
+ }
1583
+ async function drain(inFlight) {
1584
+ while (inFlight.size > 0) {
1585
+ await Promise.allSettled([...inFlight]);
1586
+ }
1587
+ }
1588
+ function handleLine(line, serve, write, warn) {
1589
+ const text = line.trim();
1590
+ if (text === "") return void 0;
1591
+ let decoded;
1592
+ try {
1593
+ decoded = JSON.parse(text);
1594
+ } catch (e6) {
1595
+ write(errorLine(null, { code: MCP_ERR_PARSE, message: `parse error: ${goJSONParseMessage(text)}` }));
1596
+ return void 0;
1597
+ }
1598
+ if (Array.isArray(decoded)) {
1599
+ write(errorLine(null, {
1600
+ code: MCP_ERR_INVALID_REQUEST,
1601
+ message: "invalid request: batch requests are not supported"
1602
+ }));
1603
+ return void 0;
1604
+ }
1605
+ if (decoded === null || typeof decoded !== "object") {
1606
+ write(errorLine(null, {
1607
+ code: MCP_ERR_INVALID_REQUEST,
1608
+ message: "invalid request: not a JSON-RPC object"
1609
+ }));
1610
+ return void 0;
1611
+ }
1612
+ const obj = decoded;
1613
+ const rpc = parseJsonRpcRequest(text);
1614
+ const isNotification = rpc.id === void 0;
1615
+ if (typeof obj.method !== "string") {
1616
+ if ("result" in obj || "error" in obj) {
1617
+ warn("ignored a JSON-RPC response from the client");
1618
+ return void 0;
1619
+ }
1620
+ if (isNotification) return void 0;
1621
+ write(errorLine(rpc.id, {
1622
+ code: MCP_ERR_INVALID_REQUEST,
1623
+ message: "invalid request: missing method"
1624
+ }));
1625
+ return void 0;
1626
+ }
1627
+ const req = { method: "POST", body: text };
1628
+ return serve(req, rpc).then(
1629
+ (res) => {
1630
+ if (isNotification || res.body === "") return;
1631
+ write(res.body);
1632
+ },
1633
+ (err) => {
1634
+ warn(`${rpc.method}: ${errorMessage(err)}`);
1635
+ if (isNotification) return;
1636
+ write(errorLine(rpc.id, { code: MCP_ERR_INTERNAL, message: "internal error" }));
1637
+ }
1638
+ );
1639
+ }
1640
+ function errorLine(id, error) {
1641
+ return encodeEnvelope({ id: id === null ? new RawJSON("null") : id, error });
1642
+ }
1643
+
1644
+ // src/mcp/bridge.ts
1645
+ var ANN_SIDE_EFFECT = "kit/side-effect";
1646
+ var ANN_AUTH_REQUIRED = "kit/auth-required";
1647
+ var ANN_REQUIRES_CONFIRM = "kit/requires-confirmation";
1648
+ var ANN_PERMISSIONS = "kit/permissions";
1649
+ var ANN_EXIT_CODES = "kit/exit-codes";
1650
+ function commanderBridge(root, opts) {
1651
+ const policy = _nullishCoalesce(opts.policy, () => ( defaultPolicy()));
1652
+ const leaves = () => {
1653
+ const out = [];
1654
+ walkLeaves(root, [], (cmd, path) => {
1655
+ const leaf = {
1656
+ path,
1657
+ description: _nullishCoalesce(cmd.description(), () => ( "")),
1658
+ ...collectFlags(cmd),
1659
+ class: classify(cmd)
1660
+ };
1661
+ const args = _chunkSNVGDYX7js.declaredArgs.call(void 0, cmd);
1662
+ if (args.length > 0) leaf.args = args;
1663
+ const en = _optionalChain([opts, 'access', _25 => _25.enabled, 'optionalCall', _26 => _26(leaf)]);
1664
+ if (en) leaf.enabled = en;
1665
+ out.push(leaf);
1666
+ });
1667
+ return out;
1668
+ };
1669
+ return {
1670
+ leaves,
1671
+ async invoke(inv) {
1672
+ const target = leaves().find(
1673
+ (l) => l.path.length === inv.path.length && l.path.every((seg, i) => seg === inv.path[i])
1674
+ );
1675
+ if (target === void 0) {
1676
+ throw new UnknownCommandError(
1677
+ `unknown command: ${toolName(inv.path)}`
1678
+ );
1679
+ }
1680
+ if (_optionalChain([target, 'access', _27 => _27.enabled, 'optionalAccess', _28 => _28[inv.meta.surface]]) === false) {
1681
+ throw new SurfaceNotEnabledError(
1682
+ `surface not enabled: ${inv.meta.surface}`
1683
+ );
1684
+ }
1685
+ if (!policyAllowed(policy, _nullishCoalesce(target.class, () => ( {})), inv.meta.surface)) {
1686
+ throw new DestructiveBlockedError(
1687
+ target.path.join(" "),
1688
+ inv.meta.surface
1689
+ );
1690
+ }
1691
+ const cmd = findCommand(root, target.path);
1692
+ if (cmd === void 0) {
1693
+ throw new UnknownCommandError(
1694
+ `unknown command: ${toolName(inv.path)}`
1695
+ );
1696
+ }
1697
+ return opts.run(inv, cmd);
1698
+ }
1699
+ };
1700
+ }
1701
+ function classify(cmd) {
1702
+ const ann = _nullishCoalesce(cmd.annotations, () => ( {}));
1703
+ const cls = {};
1704
+ switch (ann[ANN_SIDE_EFFECT]) {
1705
+ case "destructive":
1706
+ case "destructive-local":
1707
+ case "destructive-shared":
1708
+ cls.destructive = true;
1709
+ break;
1710
+ default:
1711
+ break;
1712
+ }
1713
+ if (ann[ANN_AUTH_REQUIRED] === "true") cls.authRequired = true;
1714
+ if (ann[ANN_REQUIRES_CONFIRM] === "true") cls.requiresConfirmation = true;
1715
+ const perms = splitCSV(ann[ANN_PERMISSIONS]);
1716
+ if (perms) cls.permissions = perms;
1717
+ const codes = splitCSV(ann[ANN_EXIT_CODES]);
1718
+ if (codes) cls.exitCodes = codes;
1719
+ return cls;
1720
+ }
1721
+ function splitCSV(s) {
1722
+ if (!s) return void 0;
1723
+ const out = s.split(",").map((p) => p.trim()).filter((p) => p !== "");
1724
+ return out.length > 0 ? out : void 0;
1725
+ }
1726
+ function walkLeaves(cmd, path, visit) {
1727
+ const subs = cmd.commands;
1728
+ if (subs.length === 0) {
1729
+ if (path.length > 0) visit(cmd, path);
1730
+ return;
1731
+ }
1732
+ for (const sub of subs) {
1733
+ walkLeaves(sub, [...path, sub.name()], visit);
1734
+ }
1735
+ }
1736
+ function findCommand(root, path) {
1737
+ let cur = root;
1738
+ for (const seg of path) {
1739
+ const next = cur.commands.find((c) => c.name() === seg);
1740
+ if (next === void 0) return void 0;
1741
+ cur = next;
1742
+ }
1743
+ return cur;
1744
+ }
1745
+ function collectFlags(cmd) {
1746
+ const properties = {};
1747
+ const required = [];
1748
+ const seen = /* @__PURE__ */ new Set();
1749
+ for (const opt of cmd.options) {
1750
+ if (opt.hidden) continue;
1751
+ const name = optionName(opt);
1752
+ if (name === "" || seen.has(name)) continue;
1753
+ seen.add(name);
1754
+ properties[name] = flagProperty(opt);
1755
+ if (opt.mandatory) required.push(name);
1756
+ }
1757
+ return required.length > 0 ? { properties, required } : { properties };
1758
+ }
1759
+ function optionName(opt) {
1760
+ const long = opt.long;
1761
+ if (long) return long.replace(/^--/, "");
1762
+ return (_nullishCoalesce(opt.short, () => ( ""))).replace(/^-/, "");
1763
+ }
1764
+ function flagProperty(opt) {
1765
+ const type = optionJSONType(opt);
1766
+ const prop = {
1767
+ type,
1768
+ description: _nullishCoalesce(opt.description, () => ( ""))
1769
+ };
1770
+ const choices = opt.argChoices;
1771
+ if (type === "array") {
1772
+ prop.items = { type: "string" };
1773
+ if (choices && choices.length > 0) prop.items.enum = [...choices];
1774
+ } else if (type === "string" && choices && choices.length > 0) {
1775
+ prop.enum = [...choices];
1776
+ }
1777
+ if (defaultMatches(type, opt.defaultValue)) {
1778
+ prop.default = Array.isArray(opt.defaultValue) ? [...opt.defaultValue] : opt.defaultValue;
1779
+ }
1780
+ return prop;
1781
+ }
1782
+ function optionJSONType(opt) {
1783
+ if (opt.variadic) return "array";
1784
+ if (opt.parseArg !== void 0 && Array.isArray(opt.defaultValue)) {
1785
+ return "array";
1786
+ }
1787
+ if (_chunkSNVGDYX7js.takesNoValue.call(void 0, opt)) return "boolean";
1788
+ return "string";
1789
+ }
1790
+ function defaultMatches(type, value) {
1791
+ switch (type) {
1792
+ case "string":
1793
+ return typeof value === "string";
1794
+ case "boolean":
1795
+ return typeof value === "boolean";
1796
+ case "array":
1797
+ return Array.isArray(value) && value.every((v) => typeof v === "string");
1798
+ default:
1799
+ return false;
1800
+ }
1801
+ }
1802
+
1803
+
1804
+
1805
+
1806
+
1807
+
1808
+
1809
+
1810
+
1811
+
1812
+
1813
+
1814
+
1815
+
1816
+
1817
+
1818
+
1819
+
1820
+
1821
+
1822
+
1823
+
1824
+
1825
+
1826
+
1827
+
1828
+
1829
+
1830
+
1831
+
1832
+
1833
+
1834
+
1835
+
1836
+
1837
+
1838
+
1839
+
1840
+
1841
+
1842
+
1843
+
1844
+
1845
+
1846
+
1847
+
1848
+
1849
+
1850
+
1851
+
1852
+
1853
+
1854
+
1855
+
1856
+
1857
+
1858
+
1859
+
1860
+
1861
+
1862
+
1863
+
1864
+
1865
+
1866
+
1867
+
1868
+
1869
+
1870
+
1871
+
1872
+
1873
+
1874
+
1875
+
1876
+
1877
+
1878
+
1879
+
1880
+
1881
+
1882
+
1883
+
1884
+
1885
+
1886
+
1887
+
1888
+
1889
+
1890
+
1891
+
1892
+
1893
+
1894
+ exports.MCP_ARGS_PROPERTY = MCP_ARGS_PROPERTY; exports.mcpArgsPublished = mcpArgsPublished; exports.mcpToolDescription = mcpToolDescription; exports.mcpInputSchema = mcpInputSchema; exports.mcpSplitArguments = mcpSplitArguments; exports.META_KEY_PROTOCOL_VERSION = META_KEY_PROTOCOL_VERSION; exports.META_KEY_CLIENT_INFO = META_KEY_CLIENT_INFO; exports.META_KEY_CLIENT_CAPABILITIES = META_KEY_CLIENT_CAPABILITIES; exports.META_KEY_SERVER_INFO = META_KEY_SERVER_INFO; exports.HEADER_MCP_PROTOCOL_VERSION = HEADER_MCP_PROTOCOL_VERSION; exports.HEADER_MCP_METHOD = HEADER_MCP_METHOD; exports.HEADER_MCP_NAME = HEADER_MCP_NAME; exports.MCP_ERR_PARSE = MCP_ERR_PARSE; exports.MCP_ERR_INVALID_REQUEST = MCP_ERR_INVALID_REQUEST; exports.MCP_ERR_METHOD_NOT_FOUND = MCP_ERR_METHOD_NOT_FOUND; exports.MCP_ERR_INVALID_PARAMS = MCP_ERR_INVALID_PARAMS; exports.MCP_ERR_INTERNAL = MCP_ERR_INTERNAL; exports.MCP_ERR_HEADER_MISMATCH = MCP_ERR_HEADER_MISMATCH; exports.MCP_ERR_MISSING_CLIENT_CAPABILITY = MCP_ERR_MISSING_CLIENT_CAPABILITY; exports.MCP_ERR_UNSUPPORTED_VERSION = MCP_ERR_UNSUPPORTED_VERSION; exports.MCP_SPEC_2024_11_05 = MCP_SPEC_2024_11_05; exports.MCP_SPEC_2026_07_28 = MCP_SPEC_2026_07_28; exports.RESULT_TYPE_COMPLETE = RESULT_TYPE_COMPLETE; exports.RESULT_TYPE_INPUT_REQUIRED = RESULT_TYPE_INPUT_REQUIRED; exports.DEFAULT_MCP_SERVER_NAME = DEFAULT_MCP_SERVER_NAME; exports.DEFAULT_MCP_SERVER_VERSION = DEFAULT_MCP_SERVER_VERSION; exports.DEFAULT_MCP_PATH = DEFAULT_MCP_PATH; exports.DEFAULT_TOOL_NAME_SEPARATOR = DEFAULT_TOOL_NAME_SEPARATOR; exports.SURFACE_CLI = SURFACE_CLI; exports.SURFACE_LIB = SURFACE_LIB; exports.SURFACE_MCP = SURFACE_MCP; exports.defaultPolicy = defaultPolicy; exports.policyAllowed = policyAllowed; exports.DestructiveBlockedError = DestructiveBlockedError; exports.UnknownCommandError = UnknownCommandError; exports.SurfaceNotEnabledError = SurfaceNotEnabledError; exports.MCP_AUTH_CHALLENGE = MCP_AUTH_CHALLENGE; exports.resolveMcpConfig = resolveMcpConfig; exports.toolName = toolName; exports.pathFromToolName = pathFromToolName; exports.buildToolEnvelope = buildToolEnvelope; exports.renderCallResult = renderCallResult; exports.errorResultBlock = errorResultBlock; exports.RawJSON = RawJSON; exports.canonicalJSONStringify = canonicalJSONStringify; exports.encodeEnvelope = encodeEnvelope; exports.SCOPES_EXTRA_KEY = SCOPES_EXTRA_KEY; exports.establishCaller = establishCaller; exports.invocationMeta = invocationMeta; exports.MCP_AUDIT_AUTH_REFUSED = MCP_AUDIT_AUTH_REFUSED; exports.MCP_AUDIT_CONFIRMATION_REQUIRED = MCP_AUDIT_CONFIRMATION_REQUIRED; exports.MCP_AUDIT_CONFIRMATION_DECLINED = MCP_AUDIT_CONFIRMATION_DECLINED; exports.MCP_AUDIT_CONFIRMATION_STATE_REJECTED = MCP_AUDIT_CONFIRMATION_STATE_REJECTED; exports.MCP_AUDIT_DESTRUCTIVE_BLOCKED = MCP_AUDIT_DESTRUCTIVE_BLOCKED; exports.MCP_CONFIRM_REJECTION_STATE = MCP_CONFIRM_REJECTION_STATE; exports.auditRefusal = auditRefusal; exports.LegacyMcpHandler = LegacyMcpHandler; exports.TASKS_EXTENSION = TASKS_EXTENSION; exports.TASK_METHODS = TASK_METHODS; exports.isTaskMethod = isTaskMethod; exports.TASKS_SUPPORTED = TASKS_SUPPORTED; exports.discoverCapabilities = discoverCapabilities; exports.MCP_CONFIRM_KEY = MCP_CONFIRM_KEY; exports.MCP_CONFIRM_STATE_TTL_SECONDS = MCP_CONFIRM_STATE_TTL_SECONDS; exports.MCP_CONFIRM_STATE_VERSION = MCP_CONFIRM_STATE_VERSION; exports.ElicitationConfirmGate = ElicitationConfirmGate; exports.headerConfirmationGate = headerConfirmationGate; exports.clientSupportsFormElicitation = clientSupportsFormElicitation; exports.parseMcpConfirmRetry = parseMcpConfirmRetry; exports.mcpConfirmPrincipal = mcpConfirmPrincipal; exports.mcpConfirmArgsDigest = mcpConfirmArgsDigest; exports.mintMcpConfirmState = mintMcpConfirmState; exports.verifyMcpConfirmState = verifyMcpConfirmState; exports.ModernMcpHandler = ModernMcpHandler; exports.singleHeaderValue = singleHeaderValue; exports.validModernRequestId = validModernRequestId; exports.parseModernMeta = parseModernMeta; exports.rawToolCallName = rawToolCallName; exports.decodeMcpSentinel = decodeMcpSentinel; exports.modernInvocationExtra = modernInvocationExtra; exports.detectMcpEra = detectMcpEra; exports.hasModernMetaMarker = hasModernMetaMarker; exports.createMcpHandler = createMcpHandler; exports.mcpMountConfig = mcpMountConfig; exports.McpDispatcher = McpDispatcher; exports.methodNotAllowedResponse = methodNotAllowedResponse; exports.parseJsonRpcRequest = parseJsonRpcRequest; exports.serveStdio = serveStdio; exports.commanderBridge = commanderBridge; exports.mcp_exports = mcp_exports;