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