@hop-top/kit 0.5.0-alpha.3 → 0.5.0-alpha.4

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 (187) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/LICENSE +1 -1
  3. package/README.md +47 -575
  4. package/dist/{aim-CTp-kJW2.d.ts → aim-DZHwwiIc.d.ts} +1 -1
  5. package/dist/aim.d.ts +1 -1
  6. package/dist/aim.js +13 -414
  7. package/dist/{alias-dhhr08Ei.d.ts → alias-BOj0-VAr.d.ts} +1 -1
  8. package/dist/alias.d.ts +1 -1
  9. package/dist/alias.js +18 -206
  10. package/dist/{api-miiso81x.d.ts → api-DAexsu2H.d.ts} +1 -1
  11. package/dist/api.d.ts +1 -1
  12. package/dist/api.js +10 -164
  13. package/dist/auth.js +6 -40
  14. package/dist/chunk-3FIKGFKI.js +54 -0
  15. package/dist/chunk-4UE5TCMQ.js +104 -0
  16. package/dist/chunk-6HFAEZ52.js +29 -0
  17. package/dist/chunk-6SVOHNIC.js +17 -0
  18. package/dist/chunk-72XZWQX7.js +504 -0
  19. package/dist/chunk-ABQSE7AI.js +513 -0
  20. package/dist/chunk-BDNNPRX6.js +41 -0
  21. package/dist/chunk-BRNEKPWX.js +37 -0
  22. package/dist/chunk-CSJWB6D3.js +151 -0
  23. package/dist/chunk-GGWJRWWA.js +309 -0
  24. package/dist/chunk-IQXEISMC.js +142 -0
  25. package/dist/chunk-JTMPNXVQ.js +1491 -0
  26. package/dist/chunk-KVG7YCTS.js +115 -0
  27. package/dist/chunk-L23O2FFE.js +51 -0
  28. package/dist/chunk-MQXYDYRD.js +968 -0
  29. package/dist/chunk-MUIQVU6E.js +251 -0
  30. package/dist/chunk-POR5L2DG.js +247 -0
  31. package/dist/chunk-PSFYJGDG.js +1445 -0
  32. package/dist/chunk-QJVSKKRQ.js +369 -0
  33. package/dist/chunk-QPUCXQXT.js +67 -0
  34. package/dist/chunk-R5U7XKVJ.js +16 -0
  35. package/dist/chunk-S45UHXQF.js +182 -0
  36. package/dist/chunk-T46YPHKN.js +669 -0
  37. package/dist/chunk-UIOOOK6M.js +334 -0
  38. package/dist/chunk-UKZIAQA7.js +26 -0
  39. package/dist/chunk-WBVO43HU.js +355 -0
  40. package/dist/chunk-WTYDHXPW.js +574 -0
  41. package/dist/chunk-WUOAQVOA.js +86 -0
  42. package/dist/chunk-WWUKGJB5.js +90 -0
  43. package/dist/chunk-YGYQUFGY.js +219 -0
  44. package/dist/chunk-YOBAUCVN.js +583 -0
  45. package/dist/{cli-DLygZLi9.d.ts → cli-8rfITnv4.d.ts} +13 -4
  46. package/dist/cli.d.ts +4 -4
  47. package/dist/cli.js +50 -1057
  48. package/dist/{config-BUY7_W2n.d.ts → config-Bm9fBXch.d.ts} +35 -4
  49. package/dist/config.d.ts +1 -1
  50. package/dist/config.js +6 -78
  51. package/dist/errcorrect.js +8 -68
  52. package/dist/{error-DISJKeDu.d.ts → error-Do8Qji43.d.ts} +88 -1
  53. package/dist/id/index.d.ts +1 -1
  54. package/dist/id/index.js +14 -65
  55. package/dist/{index-MLrRDvEG.d.ts → index-B-pqGHhU.d.ts} +113 -19
  56. package/dist/{index-Bc5c7Ty5.d.ts → index-DEyjGoo2.d.ts} +1 -1
  57. package/dist/{index-QSffbLnj.d.ts → index-VLDcI5NF.d.ts} +3 -2
  58. package/dist/index.d.ts +18 -15
  59. package/dist/index.js +39 -6722
  60. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  61. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  62. package/dist/llm-anthropic.d.ts +2 -0
  63. package/dist/llm-anthropic.js +13 -0
  64. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  65. package/dist/llm-openai.d.ts +2 -0
  66. package/dist/llm-openai.js +19 -0
  67. package/dist/llm.d.ts +1 -1
  68. package/dist/llm.js +101 -356
  69. package/dist/mcp/index.d.ts +2 -1
  70. package/dist/mcp/index.js +155 -1453
  71. package/dist/{netpolicy-asvCfwi8.d.ts → netpolicy-Brx5XZUB.d.ts} +16 -3
  72. package/dist/netpolicy.d.ts +1 -1
  73. package/dist/netpolicy.js +25 -118
  74. package/dist/{output-4aXs91GY.d.ts → output-CjZWmL8s.d.ts} +28 -4
  75. package/dist/output.d.ts +2 -2
  76. package/dist/output.js +137 -971
  77. package/dist/progress.js +6 -55
  78. package/dist/provenance.js +6 -31
  79. package/dist/routellm-B0nv59mH.d.ts +111 -0
  80. package/dist/routellm.d.ts +2 -2
  81. package/dist/routellm.js +13 -255
  82. package/dist/{rpc-D5xLEf8V.d.ts → rpc-D31Lg0Kc.d.ts} +1 -1
  83. package/dist/rpc.d.ts +2 -2
  84. package/dist/rpc.js +4 -98
  85. package/dist/safety.js +6 -43
  86. package/dist/scope.js +20 -377
  87. package/dist/{serve-DE-jscpb.d.ts → serve-D8yWMrTc.d.ts} +2 -2
  88. package/dist/serve.d.ts +2 -2
  89. package/dist/serve.js +75 -1019
  90. package/dist/sqlstore.js +6 -39
  91. package/dist/stream.js +8 -51
  92. package/dist/telemetry/index.js +24 -608
  93. package/dist/tui/index.d.ts +5 -5
  94. package/dist/tui/index.js +17 -374
  95. package/dist/upgrade.js +6 -114
  96. package/dist/xdg.js +14 -128
  97. package/package.json +130 -25
  98. package/src/README.md +15 -0
  99. package/src/cli.test.ts +56 -1
  100. package/src/cli.ts +24 -4
  101. package/src/completion-values.test.ts +10 -10
  102. package/src/compliance.test.ts +196 -2
  103. package/src/compliance.ts +440 -20
  104. package/src/config.test.ts +187 -1
  105. package/src/config.ts +173 -7
  106. package/src/gen/crud_pb.ts +7 -7
  107. package/src/id/README.md +38 -0
  108. package/src/id/contract.test.ts +1 -1
  109. package/src/id/index.test.ts +1 -1
  110. package/src/id/index.ts +3 -2
  111. package/src/index.test.ts +12 -0
  112. package/src/index.ts +2 -0
  113. package/src/llm-anthropic.conformance.test.ts +1135 -0
  114. package/src/llm-anthropic.test.ts +152 -0
  115. package/src/llm-anthropic.ts +940 -0
  116. package/src/llm-choice-hermetic.test.ts +335 -0
  117. package/src/llm-config.test.ts +232 -0
  118. package/src/llm-config.ts +106 -0
  119. package/src/llm-endpoint.ts +254 -0
  120. package/src/llm-error.ts +17 -0
  121. package/src/llm-errors.ts +152 -0
  122. package/src/llm-file.ts +126 -0
  123. package/src/llm-http.ts +317 -0
  124. package/src/llm-keys.ts +167 -0
  125. package/src/llm-media.conformance.test.ts +87 -0
  126. package/src/llm-media.test.ts +279 -0
  127. package/src/llm-media.ts +322 -0
  128. package/src/llm-openai.conformance.test.ts +407 -0
  129. package/src/llm-openai.test.ts +510 -0
  130. package/src/llm-openai.ts +708 -0
  131. package/src/llm-payload.ts +155 -0
  132. package/src/llm-quote.ts +46 -0
  133. package/src/llm-routellm.conformance.test.ts +44 -0
  134. package/src/llm-toolnames.conformance.test.ts +112 -0
  135. package/src/llm-toolnames.test.ts +132 -0
  136. package/src/llm-toolnames.ts +298 -0
  137. package/src/llm-uri.ts +99 -0
  138. package/src/llm.test.ts +43 -15
  139. package/src/llm.toolcall.test.ts +175 -0
  140. package/src/llm.ts +602 -190
  141. package/src/mcp/README.md +57 -0
  142. package/src/mcp/conformance.test.ts +24 -3
  143. package/src/mcp/dispatch.ts +4 -4
  144. package/src/mcp/identity.test.ts +166 -0
  145. package/src/mcp/identity.ts +72 -0
  146. package/src/mcp/index.ts +6 -0
  147. package/src/mcp/legacy.ts +21 -8
  148. package/src/mcp/mcp.test.ts +14 -4
  149. package/src/mcp/modern-confirm.ts +1 -1
  150. package/src/mcp/modern.ts +12 -11
  151. package/src/mcp/tasks.ts +1 -1
  152. package/src/mcp/types.ts +80 -8
  153. package/src/netpolicy.test.ts +78 -0
  154. package/src/netpolicy.ts +28 -3
  155. package/src/output/README.md +46 -0
  156. package/src/output/builtins.ts +5 -5
  157. package/src/output/error.ts +144 -1
  158. package/src/output/formatters/README.md +50 -0
  159. package/src/output.ts +24 -1
  160. package/src/published-types.test.ts +115 -0
  161. package/src/routellm.test.ts +209 -28
  162. package/src/routellm.toolcall.test.ts +521 -0
  163. package/src/routellm.ts +213 -177
  164. package/src/router/README.md +44 -0
  165. package/src/router/server.test.ts +41 -0
  166. package/src/router/server.ts +11 -0
  167. package/src/safety.test.ts +19 -9
  168. package/src/scope-defaults.json +29 -29
  169. package/src/serve.ts +1 -1
  170. package/src/telemetry/README.md +48 -0
  171. package/src/telemetry/client.ts +5 -5
  172. package/src/toolspec.test.ts +2 -2
  173. package/src/triton/README.md +34 -0
  174. package/src/tui/README.md +42 -0
  175. package/src/wizard.test.ts +7 -7
  176. package/test/llm/conformance-helpers.ts +100 -0
  177. package/test/output/dispatch.test.ts +1 -2
  178. package/test/output/error.test.ts +33 -2
  179. package/test/output/smoke-capture.ts +2 -2
  180. package/test/output/smoke.test.ts +2 -2
  181. package/test/output/taxonomy-contract.test.ts +148 -0
  182. package/test/setup-env.ts +16 -0
  183. package/tsconfig.json +3 -1
  184. package/tsconfig.test.json +10 -0
  185. package/vitest.config.ts +9 -0
  186. package/dist/llm-B5XUWH8T.d.ts +0 -231
  187. package/dist/routellm-PGSt2D1y.d.ts +0 -75
@@ -0,0 +1,1491 @@
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
+ var _chunkR5U7XKVJjs = require('./chunk-R5U7XKVJ.js');
4
+
5
+ // src/mcp/index.ts
6
+ var mcp_exports = {};
7
+ _chunkR5U7XKVJjs.__export.call(void 0, mcp_exports, {
8
+ DEFAULT_MCP_PATH: () => DEFAULT_MCP_PATH,
9
+ DEFAULT_MCP_SERVER_NAME: () => DEFAULT_MCP_SERVER_NAME,
10
+ DEFAULT_MCP_SERVER_VERSION: () => DEFAULT_MCP_SERVER_VERSION,
11
+ DestructiveBlockedError: () => DestructiveBlockedError,
12
+ ElicitationConfirmGate: () => ElicitationConfirmGate,
13
+ HEADER_MCP_METHOD: () => HEADER_MCP_METHOD,
14
+ HEADER_MCP_NAME: () => HEADER_MCP_NAME,
15
+ HEADER_MCP_PROTOCOL_VERSION: () => HEADER_MCP_PROTOCOL_VERSION,
16
+ LegacyMcpHandler: () => LegacyMcpHandler,
17
+ MCP_AUTH_CHALLENGE: () => MCP_AUTH_CHALLENGE,
18
+ MCP_CONFIRM_KEY: () => MCP_CONFIRM_KEY,
19
+ MCP_CONFIRM_STATE_TTL_SECONDS: () => MCP_CONFIRM_STATE_TTL_SECONDS,
20
+ MCP_CONFIRM_STATE_VERSION: () => MCP_CONFIRM_STATE_VERSION,
21
+ MCP_ERR_HEADER_MISMATCH: () => MCP_ERR_HEADER_MISMATCH,
22
+ MCP_ERR_INTERNAL: () => MCP_ERR_INTERNAL,
23
+ MCP_ERR_INVALID_PARAMS: () => MCP_ERR_INVALID_PARAMS,
24
+ MCP_ERR_INVALID_REQUEST: () => MCP_ERR_INVALID_REQUEST,
25
+ MCP_ERR_METHOD_NOT_FOUND: () => MCP_ERR_METHOD_NOT_FOUND,
26
+ MCP_ERR_MISSING_CLIENT_CAPABILITY: () => MCP_ERR_MISSING_CLIENT_CAPABILITY,
27
+ MCP_ERR_PARSE: () => MCP_ERR_PARSE,
28
+ MCP_ERR_UNSUPPORTED_VERSION: () => MCP_ERR_UNSUPPORTED_VERSION,
29
+ MCP_SPEC_2024_11_05: () => MCP_SPEC_2024_11_05,
30
+ MCP_SPEC_2026_07_28: () => MCP_SPEC_2026_07_28,
31
+ META_KEY_CLIENT_CAPABILITIES: () => META_KEY_CLIENT_CAPABILITIES,
32
+ META_KEY_CLIENT_INFO: () => META_KEY_CLIENT_INFO,
33
+ META_KEY_PROTOCOL_VERSION: () => META_KEY_PROTOCOL_VERSION,
34
+ META_KEY_SERVER_INFO: () => META_KEY_SERVER_INFO,
35
+ McpDispatcher: () => McpDispatcher,
36
+ ModernMcpHandler: () => ModernMcpHandler,
37
+ RESULT_TYPE_COMPLETE: () => RESULT_TYPE_COMPLETE,
38
+ RESULT_TYPE_INPUT_REQUIRED: () => RESULT_TYPE_INPUT_REQUIRED,
39
+ RawJSON: () => RawJSON,
40
+ SCOPES_EXTRA_KEY: () => SCOPES_EXTRA_KEY,
41
+ SURFACE_CLI: () => SURFACE_CLI,
42
+ SURFACE_LIB: () => SURFACE_LIB,
43
+ SURFACE_MCP: () => SURFACE_MCP,
44
+ SurfaceNotEnabledError: () => SurfaceNotEnabledError,
45
+ TASKS_EXTENSION: () => TASKS_EXTENSION,
46
+ TASKS_SUPPORTED: () => TASKS_SUPPORTED,
47
+ TASK_METHODS: () => TASK_METHODS,
48
+ UnknownCommandError: () => UnknownCommandError,
49
+ buildToolEnvelope: () => buildToolEnvelope,
50
+ canonicalJSONStringify: () => canonicalJSONStringify,
51
+ clientSupportsFormElicitation: () => clientSupportsFormElicitation,
52
+ commanderBridge: () => commanderBridge,
53
+ createMcpHandler: () => createMcpHandler,
54
+ decodeMcpSentinel: () => decodeMcpSentinel,
55
+ defaultPolicy: () => defaultPolicy,
56
+ detectMcpEra: () => detectMcpEra,
57
+ discoverCapabilities: () => discoverCapabilities,
58
+ encodeEnvelope: () => encodeEnvelope,
59
+ errorResultBlock: () => errorResultBlock,
60
+ establishCaller: () => establishCaller,
61
+ hasModernMetaMarker: () => hasModernMetaMarker,
62
+ headerConfirmationGate: () => headerConfirmationGate,
63
+ invocationMeta: () => invocationMeta,
64
+ isTaskMethod: () => isTaskMethod,
65
+ mcpConfirmArgsDigest: () => mcpConfirmArgsDigest,
66
+ mcpConfirmPrincipal: () => mcpConfirmPrincipal,
67
+ mcpMountConfig: () => mcpMountConfig,
68
+ methodNotAllowedResponse: () => methodNotAllowedResponse,
69
+ mintMcpConfirmState: () => mintMcpConfirmState,
70
+ modernInvocationExtra: () => modernInvocationExtra,
71
+ parseJsonRpcRequest: () => parseJsonRpcRequest,
72
+ parseMcpConfirmRetry: () => parseMcpConfirmRetry,
73
+ parseModernMeta: () => parseModernMeta,
74
+ pathFromToolName: () => pathFromToolName,
75
+ policyAllowed: () => policyAllowed,
76
+ rawToolCallName: () => rawToolCallName,
77
+ renderCallResult: () => renderCallResult,
78
+ resolveMcpConfig: () => resolveMcpConfig,
79
+ singleHeaderValue: () => singleHeaderValue,
80
+ toolName: () => toolName,
81
+ validModernRequestId: () => validModernRequestId,
82
+ verifyMcpConfirmState: () => verifyMcpConfirmState
83
+ });
84
+
85
+ // src/mcp/types.ts
86
+
87
+
88
+
89
+
90
+
91
+
92
+ var _server = require('@modelcontextprotocol/server');
93
+ var META_KEY_PROTOCOL_VERSION = _server.PROTOCOL_VERSION_META_KEY;
94
+ var META_KEY_CLIENT_INFO = _server.CLIENT_INFO_META_KEY;
95
+ var META_KEY_CLIENT_CAPABILITIES = _server.CLIENT_CAPABILITIES_META_KEY;
96
+ var META_KEY_SERVER_INFO = _server.SERVER_INFO_META_KEY;
97
+ var HEADER_MCP_PROTOCOL_VERSION = "MCP-Protocol-Version";
98
+ var HEADER_MCP_METHOD = "Mcp-Method";
99
+ var HEADER_MCP_NAME = "Mcp-Name";
100
+ var MCP_ERR_PARSE = _server.ProtocolErrorCode.ParseError;
101
+ var MCP_ERR_INVALID_REQUEST = _server.ProtocolErrorCode.InvalidRequest;
102
+ var MCP_ERR_METHOD_NOT_FOUND = _server.ProtocolErrorCode.MethodNotFound;
103
+ var MCP_ERR_INVALID_PARAMS = _server.ProtocolErrorCode.InvalidParams;
104
+ var MCP_ERR_INTERNAL = _server.ProtocolErrorCode.InternalError;
105
+ var MCP_ERR_HEADER_MISMATCH = -32020;
106
+ var MCP_ERR_MISSING_CLIENT_CAPABILITY = _server.ProtocolErrorCode.MissingRequiredClientCapability;
107
+ var MCP_ERR_UNSUPPORTED_VERSION = _server.ProtocolErrorCode.UnsupportedProtocolVersion;
108
+ var MCP_SPEC_2024_11_05 = "2024-11-05";
109
+ var MCP_SPEC_2026_07_28 = "2026-07-28";
110
+ var RESULT_TYPE_COMPLETE = "complete";
111
+ var RESULT_TYPE_INPUT_REQUIRED = "input_required";
112
+ var DEFAULT_MCP_SERVER_NAME = "cmdsurface";
113
+ var DEFAULT_MCP_SERVER_VERSION = "0.0.0";
114
+ var DEFAULT_MCP_PATH = "/mcp";
115
+ var SURFACE_CLI = "cli";
116
+ var SURFACE_LIB = "lib";
117
+ var SURFACE_MCP = "mcp";
118
+ function defaultPolicy() {
119
+ return {
120
+ allowDestructiveOn: [],
121
+ defaultEnabled: [SURFACE_CLI, SURFACE_LIB, SURFACE_MCP]
122
+ };
123
+ }
124
+ function policyAllowed(p, cls, s) {
125
+ if (s === SURFACE_CLI || s === SURFACE_LIB) return true;
126
+ if (!cls.destructive) return true;
127
+ return (_nullishCoalesce(p.allowDestructiveOn, () => ( []))).includes(s);
128
+ }
129
+ var DestructiveBlockedError = class extends Error {
130
+ constructor(pathLabel, surface) {
131
+ super(
132
+ `cmdsurface: destructive command blocked on this surface: ${pathLabel} on ${surface}`
133
+ );
134
+ this.name = "DestructiveBlockedError";
135
+ }
136
+ };
137
+ var UnknownCommandError = class extends Error {
138
+ constructor(message = "unknown command") {
139
+ super(message);
140
+ this.name = "UnknownCommandError";
141
+ }
142
+ };
143
+ var SurfaceNotEnabledError = class extends Error {
144
+ constructor(message = "surface not enabled") {
145
+ super(message);
146
+ this.name = "SurfaceNotEnabledError";
147
+ }
148
+ };
149
+ var MCP_AUTH_CHALLENGE = "Bearer";
150
+ function resolveMcpConfig(opts = {}) {
151
+ let legacyEnabled = true;
152
+ let modernEnabled = true;
153
+ if (opts.specVersions !== void 0) {
154
+ if (opts.specVersions.length === 0) {
155
+ throw new Error(
156
+ "cmdsurface: specVersions: at least one spec version required"
157
+ );
158
+ }
159
+ legacyEnabled = false;
160
+ modernEnabled = false;
161
+ for (const v of opts.specVersions) {
162
+ if (v === MCP_SPEC_2024_11_05) legacyEnabled = true;
163
+ else if (v === MCP_SPEC_2026_07_28) modernEnabled = true;
164
+ else {
165
+ throw new Error(
166
+ `cmdsurface: specVersions: unrecognized version "${v}"`
167
+ );
168
+ }
169
+ }
170
+ }
171
+ let cacheTtlMs = 0;
172
+ let cacheScope = "private";
173
+ if (opts.cacheHints !== void 0) {
174
+ const ttl = _nullishCoalesce(opts.cacheHints.ttlMs, () => ( 0));
175
+ if (ttl < 0) {
176
+ throw new Error("cmdsurface: cacheHints: negative ttl");
177
+ }
178
+ cacheTtlMs = Math.trunc(ttl);
179
+ const scope = _nullishCoalesce(opts.cacheHints.cacheScope, () => ( "private"));
180
+ if (scope !== "public" && scope !== "private") {
181
+ throw new Error(
182
+ `cmdsurface: cacheHints: unknown cache scope ${String(scope)}`
183
+ );
184
+ }
185
+ cacheScope = scope;
186
+ }
187
+ let confirmationKey;
188
+ if (opts.confirmationKey !== void 0) {
189
+ const key = typeof opts.confirmationKey === "string" ? new TextEncoder().encode(opts.confirmationKey) : opts.confirmationKey;
190
+ if (key.length === 0) {
191
+ throw new Error("cmdsurface: confirmationKey: empty key");
192
+ }
193
+ confirmationKey = key;
194
+ }
195
+ return {
196
+ path: _nullishCoalesce(opts.path, () => ( DEFAULT_MCP_PATH)),
197
+ serverName: _nullishCoalesce(_optionalChain([opts, 'access', _ => _.serverInfo, 'optionalAccess', _2 => _2.name]), () => ( DEFAULT_MCP_SERVER_NAME)),
198
+ serverVersion: _nullishCoalesce(_optionalChain([opts, 'access', _3 => _3.serverInfo, 'optionalAccess', _4 => _4.version]), () => ( DEFAULT_MCP_SERVER_VERSION)),
199
+ legacyEnabled,
200
+ modernEnabled,
201
+ cacheTtlMs,
202
+ cacheScope,
203
+ originAllowlist: _nullishCoalesce(opts.originAllowlist, () => ( [])),
204
+ confirmationKey,
205
+ policy: _nullishCoalesce(opts.policy, () => ( defaultPolicy())),
206
+ verifier: opts.verifier
207
+ };
208
+ }
209
+ function toolName(path) {
210
+ return path.join(".");
211
+ }
212
+ function pathFromToolName(name) {
213
+ if (name === "") return [];
214
+ return name.split(".");
215
+ }
216
+ function buildToolEnvelope(leaf) {
217
+ const schema = {
218
+ type: "object",
219
+ properties: _nullishCoalesce(leaf.properties, () => ( {}))
220
+ };
221
+ if (leaf.required && leaf.required.length > 0) {
222
+ schema.required = leaf.required;
223
+ }
224
+ return {
225
+ name: toolName(leaf.path),
226
+ description: leaf.description,
227
+ inputSchema: schema
228
+ };
229
+ }
230
+ function renderCallResult(res) {
231
+ const content = [
232
+ { type: "text", text: res.stdout }
233
+ ];
234
+ if (res.stderr) {
235
+ content.push({ type: "text", text: `[stderr] ${res.stderr}` });
236
+ }
237
+ if (res.data !== void 0 && res.data !== null) {
238
+ content.push({ type: "text", text: canonicalJSONStringify(res.data) });
239
+ }
240
+ return { content, isError: res.exitCode !== 0 };
241
+ }
242
+ function errorResultBlock(msg) {
243
+ return {
244
+ content: [{ type: "text", text: msg }],
245
+ isError: true
246
+ };
247
+ }
248
+ var RawJSON = class {
249
+ constructor(raw) {
250
+ this.raw = raw;
251
+ }
252
+ };
253
+ function canonicalJSONStringify(value) {
254
+ if (value instanceof RawJSON) return value.raw;
255
+ if (value === null || typeof value !== "object") {
256
+ return JSON.stringify(value);
257
+ }
258
+ if (Array.isArray(value)) {
259
+ return `[${value.map(canonicalJSONStringify).join(",")}]`;
260
+ }
261
+ const src = value;
262
+ const parts = [];
263
+ for (const key of Object.keys(src).sort()) {
264
+ const v = src[key];
265
+ if (v === void 0) continue;
266
+ parts.push(`${JSON.stringify(key)}:${canonicalJSONStringify(v)}`);
267
+ }
268
+ return `{${parts.join(",")}}`;
269
+ }
270
+ function encodeEnvelope(env) {
271
+ const parts = ['"jsonrpc":"2.0"'];
272
+ if (env.id !== void 0) {
273
+ parts.push(`"id":${env.id.raw}`);
274
+ }
275
+ if (env.error !== void 0) {
276
+ const errParts = [
277
+ `"code":${JSON.stringify(env.error.code)}`,
278
+ `"message":${JSON.stringify(env.error.message)}`
279
+ ];
280
+ if (env.error.data !== void 0) {
281
+ errParts.push(`"data":${canonicalJSONStringify(env.error.data)}`);
282
+ }
283
+ parts.push(`"error":{${errParts.join(",")}}`);
284
+ } else if (env.result !== void 0) {
285
+ parts.push(`"result":${canonicalJSONStringify(env.result)}`);
286
+ }
287
+ return `{${parts.join(",")}}
288
+ `;
289
+ }
290
+
291
+ // src/mcp/identity.ts
292
+ var SCOPES_EXTRA_KEY = "scopes";
293
+ async function establishCaller(verifier, req) {
294
+ if (verifier === void 0) return void 0;
295
+ let ident;
296
+ try {
297
+ ident = await verifier(req);
298
+ } catch (e2) {
299
+ return void 0;
300
+ }
301
+ if (ident === null || typeof ident !== "object") return void 0;
302
+ return ident;
303
+ }
304
+ function invocationMeta(ident, extra) {
305
+ const meta = { surface: SURFACE_MCP, requestedAt: /* @__PURE__ */ new Date() };
306
+ const bag = { ..._nullishCoalesce(extra, () => ( {})) };
307
+ delete bag[SCOPES_EXTRA_KEY];
308
+ if (ident !== void 0) {
309
+ meta.established = "verified";
310
+ if (typeof ident.caller === "string" && ident.caller !== "") {
311
+ meta.caller = ident.caller;
312
+ }
313
+ if (typeof ident.tenant === "string" && ident.tenant !== "") {
314
+ meta.tenant = ident.tenant;
315
+ }
316
+ if (Array.isArray(ident.scopes) && ident.scopes.length > 0) {
317
+ bag[SCOPES_EXTRA_KEY] = ident.scopes.join(",");
318
+ }
319
+ }
320
+ if (Object.keys(bag).length > 0) meta.extra = bag;
321
+ return meta;
322
+ }
323
+
324
+ // src/mcp/legacy.ts
325
+ function writeResult(id, result, status) {
326
+ return jsonResponse(status, encodeEnvelope({ id, result }));
327
+ }
328
+ function writeError(id, error, status) {
329
+ return jsonResponse(status, encodeEnvelope({ id, error }));
330
+ }
331
+ function parseErrorResponse(body) {
332
+ return writeError(
333
+ void 0,
334
+ { code: MCP_ERR_PARSE, message: `parse error: ${goJSONParseMessage(body)}` },
335
+ 400
336
+ );
337
+ }
338
+ function goJSONParseMessage(body) {
339
+ const trimmed = body.replace(/^[\s]*/, "");
340
+ if (trimmed.startsWith("{")) {
341
+ const rest = trimmed.slice(1).replace(/^[\s]*/, "");
342
+ const ch2 = rest[0];
343
+ if (ch2 !== void 0 && ch2 !== '"' && ch2 !== "}") {
344
+ return `invalid character '${ch2}' looking for beginning of object key string`;
345
+ }
346
+ }
347
+ const ch = trimmed[0];
348
+ if (ch !== void 0) {
349
+ return `invalid character '${ch}' looking for beginning of value`;
350
+ }
351
+ return "unexpected end of JSON input";
352
+ }
353
+ var LegacyMcpHandler = class {
354
+ constructor(bridge, cfg) {
355
+ this.bridge = bridge;
356
+ this.cfg = cfg;
357
+ }
358
+ /**
359
+ * Routes one already-parsed JSON-RPC request by method. An unknown
360
+ * method returns -32601 at HTTP 200 — today's behavior, preserved
361
+ * deliberately (the modern handler uses 404 instead; the asymmetry
362
+ * is required by byte-for-byte preservation).
363
+ */
364
+ async serve(req, rpc) {
365
+ if (rpc.jsonrpc !== void 0 && rpc.jsonrpc !== "2.0") {
366
+ return writeError(
367
+ rpc.id,
368
+ { code: MCP_ERR_INVALID_REQUEST, message: "invalid jsonrpc version" },
369
+ 400
370
+ );
371
+ }
372
+ switch (rpc.method) {
373
+ case "initialize":
374
+ return this.handleInitialize(rpc);
375
+ case "tools/list":
376
+ return this.handleToolsList(rpc);
377
+ case "tools/call":
378
+ return this.handleToolsCall(req, rpc);
379
+ default:
380
+ return writeError(
381
+ rpc.id,
382
+ {
383
+ code: MCP_ERR_METHOD_NOT_FOUND,
384
+ message: `method not found: ${rpc.method}`
385
+ },
386
+ 200
387
+ );
388
+ }
389
+ }
390
+ /** The minimal initialize response: version, capabilities, identity. */
391
+ handleInitialize(rpc) {
392
+ return writeResult(
393
+ rpc.id,
394
+ {
395
+ protocolVersion: MCP_SPEC_2024_11_05,
396
+ capabilities: { tools: {} },
397
+ serverInfo: {
398
+ name: this.cfg.serverName,
399
+ version: this.cfg.serverVersion
400
+ }
401
+ },
402
+ 200
403
+ );
404
+ }
405
+ /** One tool envelope per leaf exposed on the MCP surface. */
406
+ handleToolsList(rpc) {
407
+ return writeResult(rpc.id, { tools: this.exposedTools() }, 200);
408
+ }
409
+ exposedTools() {
410
+ const tools = [];
411
+ for (const leaf of this.bridge.leaves()) {
412
+ if (!isExposed(leaf)) continue;
413
+ tools.push(buildToolEnvelope(leaf));
414
+ }
415
+ return tools;
416
+ }
417
+ /**
418
+ * Resolves the leaf, applies the pre-flight auth + confirmation
419
+ * gates, and dispatches through the bridge. Unknown / not-enabled
420
+ * tools are JSON-RPC errors; every other failure (bridge errors,
421
+ * destructive blocks, non-zero exit codes) is an isError result.
422
+ */
423
+ async handleToolsCall(req, rpc) {
424
+ const params = _nullishCoalesce(rpc.params, () => ( {}));
425
+ const name = typeof params.name === "string" ? params.name : "";
426
+ if (name === "") {
427
+ return writeError(
428
+ rpc.id,
429
+ { code: MCP_ERR_INVALID_PARAMS, message: "missing tool name" },
430
+ 200
431
+ );
432
+ }
433
+ const leaf = resolveLeaf(this.bridge, name);
434
+ if (leaf === void 0 || !isExposed(leaf)) {
435
+ return writeError(
436
+ rpc.id,
437
+ { code: MCP_ERR_INVALID_PARAMS, message: `unknown tool: ${name}` },
438
+ 200
439
+ );
440
+ }
441
+ const ident = await establishCaller(this.cfg.verifier, req);
442
+ if (_optionalChain([leaf, 'access', _5 => _5.class, 'optionalAccess', _6 => _6.authRequired]) && ident === void 0) {
443
+ return unauthenticated(
444
+ writeResult(rpc.id, errorResultBlock("authentication required"), 401)
445
+ );
446
+ }
447
+ if (_optionalChain([leaf, 'access', _7 => _7.class, 'optionalAccess', _8 => _8.requiresConfirmation]) && !headerValue(req, "x-confirm-token")) {
448
+ return writeResult(
449
+ rpc.id,
450
+ errorResultBlock("confirmation required"),
451
+ 428
452
+ );
453
+ }
454
+ try {
455
+ const res = await this.bridge.invoke({
456
+ path: [...leaf.path],
457
+ flags: params.arguments,
458
+ meta: invocationMeta(ident)
459
+ });
460
+ return writeResult(rpc.id, renderCallResult(res), 200);
461
+ } catch (err) {
462
+ if (err instanceof UnknownCommandError || err instanceof SurfaceNotEnabledError) {
463
+ return writeError(
464
+ rpc.id,
465
+ { code: MCP_ERR_INVALID_PARAMS, message: `unknown tool: ${name}` },
466
+ 200
467
+ );
468
+ }
469
+ return writeResult(
470
+ rpc.id,
471
+ errorResultBlock(errorMessage(err)),
472
+ 200
473
+ );
474
+ }
475
+ }
476
+ };
477
+ function unauthenticated(res) {
478
+ return {
479
+ ...res,
480
+ headers: { ...res.headers, "WWW-Authenticate": MCP_AUTH_CHALLENGE }
481
+ };
482
+ }
483
+ function isExposed(leaf) {
484
+ return _optionalChain([leaf, 'access', _9 => _9.enabled, 'optionalAccess', _10 => _10[SURFACE_MCP]]) !== false;
485
+ }
486
+ function resolveLeaf(bridge, name) {
487
+ const path = pathFromToolName(name);
488
+ if (path.length === 0) return void 0;
489
+ return bridge.leaves().find(
490
+ (l) => l.path.length === path.length && l.path.every((seg, i) => seg === path[i])
491
+ );
492
+ }
493
+ function headerValue(req, name) {
494
+ const vals = headerValues(req, name);
495
+ return vals.length > 0 ? vals[0] : void 0;
496
+ }
497
+ function headerValues(req, name) {
498
+ const want = name.toLowerCase();
499
+ const out = [];
500
+ for (const [k, v] of Object.entries(_nullishCoalesce(req.headers, () => ( {})))) {
501
+ if (k.toLowerCase() !== want) continue;
502
+ if (Array.isArray(v)) out.push(...v);
503
+ else if (v !== void 0) out.push(v);
504
+ }
505
+ return out;
506
+ }
507
+ function errorMessage(err) {
508
+ if (err instanceof Error) return err.message;
509
+ return String(err);
510
+ }
511
+
512
+ // src/mcp/tasks.ts
513
+ var TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
514
+ var TASK_METHODS = [
515
+ "tasks/get",
516
+ "tasks/update",
517
+ "tasks/list",
518
+ "tasks/result",
519
+ "tasks/cancel"
520
+ ];
521
+ function isTaskMethod(method) {
522
+ return TASK_METHODS.includes(method);
523
+ }
524
+ var TASKS_SUPPORTED = false;
525
+ function taskMethodNotFound(method) {
526
+ return {
527
+ code: MCP_ERR_METHOD_NOT_FOUND,
528
+ msg: `method not found: ${method}`,
529
+ status: 404
530
+ };
531
+ }
532
+ function discoverCapabilities() {
533
+ return { tools: {} };
534
+ }
535
+
536
+ // src/mcp/modern-confirm.ts
537
+ var _crypto = require('crypto');
538
+ var MCP_CONFIRM_KEY = "confirm";
539
+ var MCP_CONFIRM_STATE_TTL_SECONDS = 5 * 60;
540
+ var MCP_CONFIRM_STATE_VERSION = "v1";
541
+ var MAC_DOMAIN = `cmdsurface-mcp-confirm-${MCP_CONFIRM_STATE_VERSION}`;
542
+ var ElicitationConfirmGate = class {
543
+ constructor(key) {
544
+ /**
545
+ * Audit records of rejected states, standing in for Go's bridge sink
546
+ * fan-out, which this port does not carry.
547
+ */
548
+ this.rejections = [];
549
+ if (key.length === 0) {
550
+ throw new Error("cmdsurface: confirmationKey: empty key");
551
+ }
552
+ this.key = Buffer.from(key);
553
+ }
554
+ /**
555
+ * Runs the gate for one `tools/call`. Returns `undefined` to proceed
556
+ * with the invocation, or the refusal / interim result plus its HTTP
557
+ * status. The caller stamps the modern envelope onto whatever is
558
+ * returned.
559
+ */
560
+ evaluate(req, leaf, params) {
561
+ if (!_optionalChain([leaf, 'access', _11 => _11.class, 'optionalAccess', _12 => _12.requiresConfirmation])) return void 0;
562
+ if (!clientSupportsFormElicitation(params)) {
563
+ return headerConfirmationGate(req);
564
+ }
565
+ const binding = {
566
+ tool: leaf.path.join(" "),
567
+ argsDigest: mcpConfirmArgsDigest(params),
568
+ principal: mcpConfirmPrincipal(req)
569
+ };
570
+ const retry = parseMcpConfirmRetry(params);
571
+ if (retry.state === "") {
572
+ return { result: this.inputRequired(leaf, binding), status: 200 };
573
+ }
574
+ const status = verifyMcpConfirmState(
575
+ this.key,
576
+ retry.state,
577
+ binding,
578
+ nowSeconds()
579
+ );
580
+ if (status === "invalid") {
581
+ this.auditRejection(leaf);
582
+ return { result: this.inputRequired(leaf, binding), status: 200 };
583
+ }
584
+ if (status === "expired") {
585
+ return { result: this.inputRequired(leaf, binding), status: 200 };
586
+ }
587
+ if (retry.action === "accept") return void 0;
588
+ if (retry.action === "decline" || retry.action === "cancel") {
589
+ return { result: errorResultBlock("confirmation declined"), status: 200 };
590
+ }
591
+ return { result: this.inputRequired(leaf, binding), status: 200 };
592
+ }
593
+ /**
594
+ * Builds the `input_required` result envelope for one confirmation
595
+ * prompt: the reserved "confirm" `elicitation/create` form request
596
+ * plus freshly minted `requestState` (satisfying the spec MUST of
597
+ * carrying at least one of `inputRequests` / `requestState` — this
598
+ * flow always carries both). The caller stamps the envelope (_meta
599
+ * serverInfo; `resultType` stays "input_required") and writes it at
600
+ * HTTP 200. Interim `input_required` results are never cacheable: no
601
+ * `ttlMs` / `cacheScope` members, ever.
602
+ */
603
+ inputRequired(leaf, binding) {
604
+ const expiry = nowSeconds() + MCP_CONFIRM_STATE_TTL_SECONDS;
605
+ return {
606
+ resultType: RESULT_TYPE_INPUT_REQUIRED,
607
+ inputRequests: {
608
+ [MCP_CONFIRM_KEY]: {
609
+ method: "elicitation/create",
610
+ params: {
611
+ mode: "form",
612
+ message: `Approve execution of ${JSON.stringify(toolName(leaf.path))}?`,
613
+ // No form fields: the approval rides the elicit action
614
+ // (accept / decline / cancel), so the requested schema is
615
+ // the empty object.
616
+ requestedSchema: { type: "object", properties: {} }
617
+ }
618
+ }
619
+ },
620
+ requestState: mintMcpConfirmState(this.key, binding, expiry)
621
+ };
622
+ }
623
+ /**
624
+ * Records a failed `requestState` verification as a
625
+ * security-relevant audit event. Go emits this on the bridge's
626
+ * registered sinks; this port has no sink fan-out, so the records
627
+ * accumulate here for adopters and tests to read. Best-effort by the
628
+ * same contract: recording never affects the response.
629
+ */
630
+ auditRejection(leaf) {
631
+ this.rejections.push({
632
+ path: leaf.path.join(" "),
633
+ mcpConfirmRejection: "request_state_verification_failed"
634
+ });
635
+ }
636
+ };
637
+ function headerConfirmationGate(req) {
638
+ if (headerValue(req, "x-confirm-token")) return void 0;
639
+ return { result: errorResultBlock("confirmation required"), status: 428 };
640
+ }
641
+ function clientSupportsFormElicitation(params) {
642
+ const meta = plainObject(_optionalChain([plainObject, 'call', _13 => _13(params), 'optionalAccess', _14 => _14._meta]));
643
+ if (meta === void 0) return false;
644
+ const caps = plainObject(meta[META_KEY_CLIENT_CAPABILITIES]);
645
+ if (caps === void 0) return false;
646
+ const modes = plainObject(caps.elicitation);
647
+ if (modes === void 0) return false;
648
+ if (Object.keys(modes).length === 0) return true;
649
+ return "form" in modes;
650
+ }
651
+ function parseMcpConfirmRetry(params) {
652
+ const obj = plainObject(params);
653
+ if (obj === void 0) return { state: "", action: "" };
654
+ const state = typeof obj.requestState === "string" ? obj.requestState : "";
655
+ let action = "";
656
+ const entry = plainObject(_optionalChain([plainObject, 'call', _15 => _15(obj.inputResponses), 'optionalAccess', _16 => _16[MCP_CONFIRM_KEY]]));
657
+ if (entry !== void 0 && typeof entry.action === "string") {
658
+ action = entry.action;
659
+ }
660
+ return { state, action };
661
+ }
662
+ function mcpConfirmPrincipal(req) {
663
+ const auth = headerValue(req, "authorization");
664
+ if (!auth) return "";
665
+ return _crypto.createHash.call(void 0, "sha256").update(auth, "utf8").digest("hex");
666
+ }
667
+ function mcpConfirmArgsDigest(params) {
668
+ const args = _nullishCoalesce(plainObject(_optionalChain([plainObject, 'call', _17 => _17(params), 'optionalAccess', _18 => _18.arguments])), () => ( null));
669
+ const canonical = canonicalJSONStringify(args);
670
+ return _crypto.createHash.call(void 0, "sha256").update(canonical, "utf8").digest("hex");
671
+ }
672
+ function mcpConfirmStateMac(key, binding, expiry) {
673
+ const mac = _crypto.createHmac.call(void 0, "sha256", key);
674
+ for (const part of [
675
+ MAC_DOMAIN,
676
+ String(expiry),
677
+ binding.tool,
678
+ binding.argsDigest,
679
+ binding.principal
680
+ ]) {
681
+ mac.update(`${Buffer.byteLength(part, "utf8")}:${part}`, "utf8");
682
+ }
683
+ return mac.digest();
684
+ }
685
+ function mintMcpConfirmState(key, binding, expiry) {
686
+ const mac = mcpConfirmStateMac(Buffer.from(key), binding, expiry);
687
+ return `${MCP_CONFIRM_STATE_VERSION}.${expiry}.${mac.toString("base64url")}`;
688
+ }
689
+ function verifyMcpConfirmState(key, state, binding, now) {
690
+ const parts = state.split(".");
691
+ if (parts.length !== 3 || parts[0] !== MCP_CONFIRM_STATE_VERSION) {
692
+ return "invalid";
693
+ }
694
+ if (!/^-?\d+$/.test(parts[1])) return "invalid";
695
+ const expiry = Number(parts[1]);
696
+ if (!Number.isSafeInteger(expiry)) return "invalid";
697
+ const tag = decodeBase64Url(parts[2]);
698
+ if (tag === void 0) return "invalid";
699
+ const want = mcpConfirmStateMac(Buffer.from(key), binding, expiry);
700
+ if (tag.length !== want.length || !_crypto.timingSafeEqual.call(void 0, tag, want)) {
701
+ return "invalid";
702
+ }
703
+ if (expiry < now) return "expired";
704
+ return "valid";
705
+ }
706
+ function decodeBase64Url(s) {
707
+ if (!/^[A-Za-z0-9_-]*$/.test(s)) return void 0;
708
+ const buf = Buffer.from(s, "base64url");
709
+ if (buf.toString("base64url") !== s) return void 0;
710
+ return buf;
711
+ }
712
+ function nowSeconds() {
713
+ return Math.floor(Date.now() / 1e3);
714
+ }
715
+ function plainObject(v) {
716
+ if (v === null || v === void 0 || typeof v !== "object") return void 0;
717
+ if (Array.isArray(v)) return void 0;
718
+ return v;
719
+ }
720
+
721
+ // src/mcp/modern.ts
722
+ var SENTINEL_PREFIX = "=?base64?";
723
+ var SENTINEL_SUFFIX = "?=";
724
+ var ModernMcpHandler = class {
725
+ constructor(bridge, cfg) {
726
+ this.bridge = bridge;
727
+ this.cfg = cfg;
728
+ if (cfg.confirmationKey !== void 0) {
729
+ this.confirmGate = new ElicitationConfirmGate(cfg.confirmationKey);
730
+ }
731
+ }
732
+ /**
733
+ * The modern entry point. The validation chain runs in the guide's
734
+ * order V1-V9; the first failure responds and stops. HTTP status is
735
+ * 400/404 only where the spec mandates it — application-level
736
+ * JSON-RPC errors ride HTTP 200, matching legacy's convention.
737
+ */
738
+ async serve(req, rpc) {
739
+ if (!this.originAllowed(req)) {
740
+ return this.writeModernError(rpc, {
741
+ code: MCP_ERR_INVALID_REQUEST,
742
+ msg: "origin not allowed",
743
+ status: 403
744
+ });
745
+ }
746
+ if (rpc.jsonrpc !== void 0 && rpc.jsonrpc !== "2.0") {
747
+ return this.writeModernError(rpc, {
748
+ code: MCP_ERR_INVALID_REQUEST,
749
+ msg: "invalid jsonrpc version",
750
+ status: 400
751
+ });
752
+ }
753
+ if (rpc.id === void 0) {
754
+ return acceptedResponse();
755
+ }
756
+ if (!validModernRequestId(rpc.id)) {
757
+ return this.writeModernError(rpc, {
758
+ code: MCP_ERR_INVALID_REQUEST,
759
+ msg: `invalid request id: must be a string or integer, got ${rpc.id.raw}`,
760
+ status: 400
761
+ });
762
+ }
763
+ const parsed = parseModernMeta(rpc.params);
764
+ if ("error" in parsed) {
765
+ return this.writeModernError(rpc, parsed.error);
766
+ }
767
+ const meta = parsed.meta;
768
+ const proto = singleHeaderValue(req, HEADER_MCP_PROTOCOL_VERSION);
769
+ if (!proto.ok) {
770
+ return this.writeModernError(rpc, {
771
+ code: MCP_ERR_HEADER_MISMATCH,
772
+ msg: `${HEADER_MCP_PROTOCOL_VERSION} header sent with conflicting duplicate values`,
773
+ status: 400
774
+ });
775
+ }
776
+ if (proto.value === "") {
777
+ return this.writeModernError(rpc, {
778
+ code: MCP_ERR_HEADER_MISMATCH,
779
+ msg: `missing ${HEADER_MCP_PROTOCOL_VERSION} header`,
780
+ status: 400
781
+ });
782
+ }
783
+ if (!meta.versionIsText || proto.value !== meta.version) {
784
+ return this.writeModernError(rpc, {
785
+ code: MCP_ERR_HEADER_MISMATCH,
786
+ msg: `${HEADER_MCP_PROTOCOL_VERSION} header ${JSON.stringify(proto.value)} does not match _meta protocolVersion ${goFormatValue(meta.versionRaw)}`,
787
+ status: 400
788
+ });
789
+ }
790
+ if (meta.version !== MCP_SPEC_2026_07_28) {
791
+ return this.writeModernError(rpc, {
792
+ code: MCP_ERR_UNSUPPORTED_VERSION,
793
+ msg: `unsupported protocol version: ${meta.version}`,
794
+ status: 400,
795
+ data: {
796
+ supported: [MCP_SPEC_2026_07_28],
797
+ requested: meta.versionRaw
798
+ }
799
+ });
800
+ }
801
+ const methodErr = this.validateMethodHeader(req, rpc);
802
+ if (methodErr) return this.writeModernError(rpc, methodErr);
803
+ switch (rpc.method) {
804
+ case "server/discover":
805
+ return this.handleDiscover(rpc);
806
+ case "tools/list":
807
+ return this.handleToolsList(rpc);
808
+ case "tools/call":
809
+ return this.handleToolsCall(req, rpc, meta);
810
+ default:
811
+ if (isTaskMethod(rpc.method)) {
812
+ return this.writeModernError(rpc, taskMethodNotFound(rpc.method));
813
+ }
814
+ return this.writeModernError(rpc, {
815
+ code: MCP_ERR_METHOD_NOT_FOUND,
816
+ msg: `method not found: ${rpc.method}`,
817
+ status: 404
818
+ });
819
+ }
820
+ }
821
+ /**
822
+ * server/discover — the mandatory modern discovery method. Carries
823
+ * no listChanged flag (notifications unimplemented), no extensions
824
+ * map (none supported, which is what makes tasks/* method-not-found),
825
+ * and no instructions.
826
+ */
827
+ handleDiscover(rpc) {
828
+ const res = {
829
+ supportedVersions: [MCP_SPEC_2026_07_28],
830
+ capabilities: { tools: {} }
831
+ };
832
+ this.applyCacheHints(res);
833
+ this.stampResultEnvelope(res);
834
+ return writeResult(rpc.id, res, 200);
835
+ }
836
+ /**
837
+ * Modern tools/list: the same tool envelopes the legacy handler
838
+ * emits (so schema drift between eras cannot happen), wrapped in
839
+ * the modern complete-result envelope with cache hints. Pagination
840
+ * is not implemented — a cursor param is ignored, no nextCursor.
841
+ */
842
+ handleToolsList(rpc) {
843
+ const tools = [];
844
+ for (const leaf of this.bridge.leaves()) {
845
+ if (!isExposed(leaf)) continue;
846
+ tools.push(buildToolEnvelope(leaf));
847
+ }
848
+ const res = { tools };
849
+ this.applyCacheHints(res);
850
+ this.stampResultEnvelope(res);
851
+ return writeResult(rpc.id, res, 200);
852
+ }
853
+ /**
854
+ * Modern tools/call: V7, V9, the legacy pre-flight gates, invoke,
855
+ * render. The shared bridge invoke path keeps the policy gate
856
+ * identical across eras — there is no way to reach a leaf here that
857
+ * the legacy path would have blocked. Results carry no cache hints.
858
+ */
859
+ async handleToolsCall(req, rpc, meta) {
860
+ const peek = rawToolCallName(rpc.params);
861
+ const nameErr = this.validateNameHeader(req, peek);
862
+ if (nameErr) return this.writeModernError(rpc, nameErr);
863
+ const params = _nullishCoalesce(rpc.params, () => ( {}));
864
+ const name = typeof params.name === "string" ? params.name : "";
865
+ if (name === "") {
866
+ return writeError(
867
+ rpc.id,
868
+ { code: MCP_ERR_INVALID_PARAMS, message: "missing tool name" },
869
+ 200
870
+ );
871
+ }
872
+ const leaf = resolveLeaf(this.bridge, name);
873
+ if (leaf === void 0 || !isExposed(leaf)) {
874
+ return writeError(
875
+ rpc.id,
876
+ { code: MCP_ERR_INVALID_PARAMS, message: `unknown tool: ${name}` },
877
+ 200
878
+ );
879
+ }
880
+ const ident = await establishCaller(this.cfg.verifier, req);
881
+ if (_optionalChain([leaf, 'access', _19 => _19.class, 'optionalAccess', _20 => _20.authRequired]) && ident === void 0) {
882
+ return unauthenticated(
883
+ this.writeCallError(rpc, "authentication required", 401)
884
+ );
885
+ }
886
+ const gated = this.confirmationGate(req, leaf, rpc.params);
887
+ if (gated !== void 0) {
888
+ return writeResult(
889
+ rpc.id,
890
+ this.stampResultEnvelope(gated.result),
891
+ gated.status
892
+ );
893
+ }
894
+ try {
895
+ const res = await this.bridge.invoke({
896
+ path: [...leaf.path],
897
+ flags: params.arguments,
898
+ meta: invocationMeta(ident, modernInvocationExtra(meta))
899
+ });
900
+ const out = renderCallResult(res);
901
+ if (res.data !== void 0 && res.data !== null) {
902
+ out.structuredContent = res.data;
903
+ }
904
+ return writeResult(rpc.id, this.stampResultEnvelope(out), 200);
905
+ } catch (err) {
906
+ if (err instanceof UnknownCommandError || err instanceof SurfaceNotEnabledError) {
907
+ return writeError(
908
+ rpc.id,
909
+ { code: MCP_ERR_INVALID_PARAMS, message: `unknown tool: ${name}` },
910
+ 200
911
+ );
912
+ }
913
+ return this.writeCallError(rpc, errorMessage(err), 200);
914
+ }
915
+ }
916
+ /**
917
+ * Selects and runs the confirmation strategy for one `tools/call`.
918
+ * Returns `undefined` to proceed with the invocation.
919
+ *
920
+ * A leaf that does not require confirmation is never gated. A mount
921
+ * without a `confirmationKey` has no state to MAC, so the header gate
922
+ * applies to every client — this is the byte-for-byte preservation
923
+ * path, identical to what the legacy handler does.
924
+ */
925
+ confirmationGate(req, leaf, params) {
926
+ if (!_optionalChain([leaf, 'access', _21 => _21.class, 'optionalAccess', _22 => _22.requiresConfirmation])) return void 0;
927
+ if (this.confirmGate === void 0) return headerConfirmationGate(req);
928
+ return this.confirmGate.evaluate(req, leaf, params);
929
+ }
930
+ /** V6: Mcp-Method header presence + agreement with the body method. */
931
+ validateMethodHeader(req, rpc) {
932
+ const hdr = singleHeaderValue(req, HEADER_MCP_METHOD);
933
+ if (!hdr.ok) {
934
+ return {
935
+ code: MCP_ERR_HEADER_MISMATCH,
936
+ msg: `${HEADER_MCP_METHOD} header sent with conflicting duplicate values`,
937
+ status: 400
938
+ };
939
+ }
940
+ if (hdr.value === "") {
941
+ return {
942
+ code: MCP_ERR_HEADER_MISMATCH,
943
+ msg: `missing ${HEADER_MCP_METHOD} header`,
944
+ status: 400
945
+ };
946
+ }
947
+ if (hdr.value !== rpc.method) {
948
+ return {
949
+ code: MCP_ERR_HEADER_MISMATCH,
950
+ msg: `${HEADER_MCP_METHOD} header ${JSON.stringify(hdr.value)} does not match body method ${JSON.stringify(rpc.method)}`,
951
+ status: 400
952
+ };
953
+ }
954
+ return void 0;
955
+ }
956
+ /**
957
+ * V7: on tools/call the Mcp-Name header MUST be present, non-empty
958
+ * after Base64-sentinel decoding, and byte-equal to params.name,
959
+ * which MUST itself be present. Any violation is a header failure
960
+ * (-32020 @ 400), decided ahead of any body-shape check: headers
961
+ * are the routing signal gateways trust without parsing the body,
962
+ * so an empty or contradicted signal is malformed at the header
963
+ * layer.
964
+ */
965
+ validateNameHeader(req, peek) {
966
+ const hdr = singleHeaderValue(req, HEADER_MCP_NAME);
967
+ if (!hdr.ok) {
968
+ return {
969
+ code: MCP_ERR_HEADER_MISMATCH,
970
+ msg: `${HEADER_MCP_NAME} header sent with conflicting duplicate values`,
971
+ status: 400
972
+ };
973
+ }
974
+ if (hdr.value === "") {
975
+ return {
976
+ code: MCP_ERR_HEADER_MISMATCH,
977
+ msg: `missing ${HEADER_MCP_NAME} header`,
978
+ status: 400
979
+ };
980
+ }
981
+ const decoded = decodeMcpSentinel(hdr.value);
982
+ if (decoded === void 0) {
983
+ return {
984
+ code: MCP_ERR_HEADER_MISMATCH,
985
+ msg: `${HEADER_MCP_NAME} header value is not valid base64-sentinel encoded`,
986
+ status: 400
987
+ };
988
+ }
989
+ if (decoded === "") {
990
+ return {
991
+ code: MCP_ERR_HEADER_MISMATCH,
992
+ msg: `${HEADER_MCP_NAME} header decodes to an empty value`,
993
+ status: 400
994
+ };
995
+ }
996
+ if (!peek.present) {
997
+ return {
998
+ code: MCP_ERR_HEADER_MISMATCH,
999
+ msg: `${HEADER_MCP_NAME} header present but body params.name is absent`,
1000
+ status: 400
1001
+ };
1002
+ }
1003
+ if (!peek.isString) {
1004
+ return void 0;
1005
+ }
1006
+ if (decoded !== peek.name) {
1007
+ return {
1008
+ code: MCP_ERR_HEADER_MISMATCH,
1009
+ msg: `${HEADER_MCP_NAME} header ${JSON.stringify(decoded)} does not match body params.name ${JSON.stringify(peek.name)}`,
1010
+ status: 400
1011
+ };
1012
+ }
1013
+ return void 0;
1014
+ }
1015
+ /**
1016
+ * Adds the members every modern result envelope carries: resultType
1017
+ * and a result-level _meta with serverInfo built from the mount's
1018
+ * configured identity. A producer that already chose a resultType
1019
+ * keeps it (the MRTR confirmation gate stamps "input_required").
1020
+ */
1021
+ stampResultEnvelope(m) {
1022
+ if (!("resultType" in m)) {
1023
+ m.resultType = RESULT_TYPE_COMPLETE;
1024
+ }
1025
+ m._meta = {
1026
+ [META_KEY_SERVER_INFO]: {
1027
+ name: this.cfg.serverName,
1028
+ version: this.cfg.serverVersion
1029
+ }
1030
+ };
1031
+ return m;
1032
+ }
1033
+ /**
1034
+ * Adds ttlMs and cacheScope to a cacheable complete-result —
1035
+ * server/discover and tools/list only; tools/call carries none.
1036
+ * Defaults are ttlMs 0 (immediately stale: the leaf set can mutate
1037
+ * at runtime and no list_changed notification exists) and
1038
+ * cacheScope "private".
1039
+ */
1040
+ applyCacheHints(m) {
1041
+ m.ttlMs = this.cfg.cacheTtlMs;
1042
+ m.cacheScope = this.cfg.cacheScope;
1043
+ return m;
1044
+ }
1045
+ /** Opt-in Origin allowlist; a request without Origin is never refused. */
1046
+ originAllowed(req) {
1047
+ if (this.cfg.originAllowlist.length === 0) return true;
1048
+ const origin = headerValue(req, "origin");
1049
+ if (!origin) return true;
1050
+ return this.cfg.originAllowlist.includes(origin);
1051
+ }
1052
+ /**
1053
+ * Writes a modern JSON-RPC error. When the rejected request's
1054
+ * method is "initialize" the message additionally names the
1055
+ * supported versions: a legacy client has no fall-forward
1056
+ * mechanism, so the version list in the error text is its only
1057
+ * recovery hint.
1058
+ */
1059
+ writeModernError(rpc, e) {
1060
+ let msg = e.msg;
1061
+ if (rpc.method === "initialize") {
1062
+ msg += `; supported protocol versions: ${MCP_SPEC_2026_07_28}`;
1063
+ }
1064
+ return writeError(
1065
+ rpc.id,
1066
+ { code: e.code, message: msg, data: e.data },
1067
+ e.status
1068
+ );
1069
+ }
1070
+ /** An isError tools/call result with the modern envelope stamped on. */
1071
+ writeCallError(rpc, msg, status) {
1072
+ return writeResult(
1073
+ rpc.id,
1074
+ this.stampResultEnvelope(errorResultBlock(msg)),
1075
+ status
1076
+ );
1077
+ }
1078
+ };
1079
+ function singleHeaderValue(req, name) {
1080
+ const vals = headerValues(req, name);
1081
+ if (vals.length === 0) return { value: "", ok: true };
1082
+ if (vals.length === 1) return { value: vals[0], ok: true };
1083
+ for (const v of vals.slice(1)) {
1084
+ if (v !== vals[0]) return { value: "", ok: false };
1085
+ }
1086
+ return { value: vals[0], ok: true };
1087
+ }
1088
+ function validModernRequestId(id) {
1089
+ const raw = id.raw.trim();
1090
+ if (raw === "null") return false;
1091
+ let parsed;
1092
+ try {
1093
+ parsed = JSON.parse(raw);
1094
+ } catch (e3) {
1095
+ return false;
1096
+ }
1097
+ if (typeof parsed === "string") return true;
1098
+ if (typeof parsed === "number") return Number.isInteger(parsed);
1099
+ return false;
1100
+ }
1101
+ function parseModernMeta(params) {
1102
+ const fail = (msg) => ({
1103
+ error: { code: MCP_ERR_INVALID_PARAMS, msg, status: 400 }
1104
+ });
1105
+ if (params === void 0 || params === null || typeof params !== "object") {
1106
+ return fail("missing required params._meta");
1107
+ }
1108
+ const metaRaw = params._meta;
1109
+ if (metaRaw === void 0 || metaRaw === null || typeof metaRaw !== "object" || Array.isArray(metaRaw)) {
1110
+ return fail("missing required params._meta");
1111
+ }
1112
+ const metaObj = metaRaw;
1113
+ if (!(META_KEY_PROTOCOL_VERSION in metaObj)) {
1114
+ return fail(`missing required _meta key: ${META_KEY_PROTOCOL_VERSION}`);
1115
+ }
1116
+ if (!(META_KEY_CLIENT_CAPABILITIES in metaObj)) {
1117
+ return fail(`missing required _meta key: ${META_KEY_CLIENT_CAPABILITIES}`);
1118
+ }
1119
+ const verRaw = metaObj[META_KEY_PROTOCOL_VERSION];
1120
+ const meta = {
1121
+ version: typeof verRaw === "string" ? verRaw : "",
1122
+ versionIsText: typeof verRaw === "string",
1123
+ versionRaw: verRaw,
1124
+ hasClientInfo: false
1125
+ };
1126
+ const ci = metaObj[META_KEY_CLIENT_INFO];
1127
+ if (ci !== void 0 && ci !== null && typeof ci === "object" && !Array.isArray(ci)) {
1128
+ const obj = ci;
1129
+ meta.hasClientInfo = true;
1130
+ meta.clientName = typeof obj.name === "string" ? obj.name : "";
1131
+ meta.clientVersion = typeof obj.version === "string" ? obj.version : "";
1132
+ }
1133
+ return { meta };
1134
+ }
1135
+ function rawToolCallName(params) {
1136
+ if (params === void 0 || params === null || typeof params !== "object" || Array.isArray(params)) {
1137
+ return { name: "", present: false, isString: false };
1138
+ }
1139
+ const obj = params;
1140
+ if (!("name" in obj)) return { name: "", present: false, isString: false };
1141
+ const v = obj.name;
1142
+ if (typeof v !== "string") return { name: "", present: true, isString: false };
1143
+ return { name: v, present: true, isString: true };
1144
+ }
1145
+ function decodeMcpSentinel(v) {
1146
+ if (!v.startsWith(SENTINEL_PREFIX) || !v.endsWith(SENTINEL_SUFFIX)) {
1147
+ return v;
1148
+ }
1149
+ const inner = v.slice(SENTINEL_PREFIX.length, v.length - SENTINEL_SUFFIX.length);
1150
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(inner) || inner.length % 4 !== 0) {
1151
+ return void 0;
1152
+ }
1153
+ const buf = Buffer.from(inner, "base64");
1154
+ if (buf.toString("base64") !== inner) return void 0;
1155
+ return buf.toString("utf8");
1156
+ }
1157
+ function modernInvocationExtra(meta) {
1158
+ const extra = {
1159
+ mcp_spec_version: MCP_SPEC_2026_07_28
1160
+ };
1161
+ if (meta.hasClientInfo) {
1162
+ extra.mcp_client_name = _nullishCoalesce(meta.clientName, () => ( ""));
1163
+ extra.mcp_client_version = _nullishCoalesce(meta.clientVersion, () => ( ""));
1164
+ }
1165
+ return extra;
1166
+ }
1167
+ function goFormatValue(v) {
1168
+ if (v === null || v === void 0) return "<nil>";
1169
+ if (typeof v === "string") return v;
1170
+ if (typeof v === "boolean") return v ? "true" : "false";
1171
+ if (typeof v === "number") return String(v);
1172
+ return JSON.stringify(v);
1173
+ }
1174
+
1175
+ // src/mcp/dispatch.ts
1176
+ function jsonResponse(status, body) {
1177
+ return {
1178
+ status,
1179
+ headers: { "Content-Type": "application/json" },
1180
+ body
1181
+ };
1182
+ }
1183
+ function acceptedResponse() {
1184
+ return { status: 202, headers: {}, body: "" };
1185
+ }
1186
+ function detectMcpEra(req, rpc) {
1187
+ if (rpc.method === "initialize") return "legacy";
1188
+ if (rpc.method === "server/discover") return "modern";
1189
+ if (headerValues(req, HEADER_MCP_METHOD).length > 0) return "modern";
1190
+ if (headerValues(req, HEADER_MCP_NAME).length > 0) return "modern";
1191
+ if (hasModernMetaMarker(rpc.params)) return "modern";
1192
+ return "legacy";
1193
+ }
1194
+ function hasModernMetaMarker(params) {
1195
+ if (params === null || typeof params !== "object" || Array.isArray(params)) {
1196
+ return false;
1197
+ }
1198
+ const meta = params._meta;
1199
+ if (meta === null || typeof meta !== "object" || Array.isArray(meta)) {
1200
+ return false;
1201
+ }
1202
+ return META_KEY_PROTOCOL_VERSION in meta;
1203
+ }
1204
+ function createMcpHandler(bridge, opts = {}) {
1205
+ const cfg = resolveMcpConfig(opts);
1206
+ const dispatcher = new McpDispatcher(bridge, cfg);
1207
+ return (req) => dispatcher.handle(req);
1208
+ }
1209
+ function mcpMountConfig(opts = {}) {
1210
+ return resolveMcpConfig(opts);
1211
+ }
1212
+ var McpDispatcher = class {
1213
+ constructor(bridge, cfg) {
1214
+ this.cfg = cfg;
1215
+ this.legacy = new LegacyMcpHandler(bridge, cfg);
1216
+ this.modern = new ModernMcpHandler(bridge, cfg);
1217
+ }
1218
+ async handle(req) {
1219
+ const verb = (req.method || "POST").toUpperCase();
1220
+ if (verb !== "POST") {
1221
+ if (this.cfg.modernEnabled && (verb === "GET" || verb === "DELETE")) {
1222
+ return methodNotAllowedResponse();
1223
+ }
1224
+ return methodNotAllowedResponse();
1225
+ }
1226
+ const body = req.body;
1227
+ if (body === void 0) {
1228
+ return writeError(
1229
+ void 0,
1230
+ {
1231
+ code: MCP_ERR_INTERNAL,
1232
+ message: "read request body: unexpected EOF"
1233
+ },
1234
+ 400
1235
+ );
1236
+ }
1237
+ let rpc;
1238
+ try {
1239
+ rpc = parseJsonRpcRequest(body);
1240
+ } catch (e4) {
1241
+ return parseErrorResponse(body);
1242
+ }
1243
+ if (this.cfg.modernEnabled && !this.cfg.legacyEnabled) {
1244
+ return this.modern.serve(req, rpc);
1245
+ }
1246
+ if (this.cfg.legacyEnabled && !this.cfg.modernEnabled) {
1247
+ return this.legacy.serve(req, rpc);
1248
+ }
1249
+ switch (detectMcpEra(req, rpc)) {
1250
+ case "modern":
1251
+ return this.modern.serve(req, rpc);
1252
+ default:
1253
+ return this.legacy.serve(req, rpc);
1254
+ }
1255
+ }
1256
+ };
1257
+ function methodNotAllowedResponse() {
1258
+ return jsonResponse(
1259
+ 405,
1260
+ '{"jsonrpc":"2.0","error":{"code":-32600,"message":"method not allowed"}}\n'
1261
+ );
1262
+ }
1263
+ function parseJsonRpcRequest(body) {
1264
+ const decoded = JSON.parse(body);
1265
+ if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded)) {
1266
+ throw new SyntaxError("not a JSON-RPC object");
1267
+ }
1268
+ const obj = decoded;
1269
+ const out = {
1270
+ method: typeof obj.method === "string" ? obj.method : ""
1271
+ };
1272
+ if (typeof obj.jsonrpc === "string") out.jsonrpc = obj.jsonrpc;
1273
+ if ("id" in obj) out.id = new RawJSON(rawIdBytes(body, obj.id));
1274
+ if ("params" in obj) out.params = obj.params;
1275
+ return out;
1276
+ }
1277
+ function rawIdBytes(_body, id) {
1278
+ return _nullishCoalesce(JSON.stringify(id), () => ( "null"));
1279
+ }
1280
+
1281
+ // src/mcp/bridge.ts
1282
+ var ANN_SIDE_EFFECT = "kit/side-effect";
1283
+ var ANN_AUTH_REQUIRED = "kit/auth-required";
1284
+ var ANN_REQUIRES_CONFIRM = "kit/requires-confirmation";
1285
+ var ANN_PERMISSIONS = "kit/permissions";
1286
+ var ANN_EXIT_CODES = "kit/exit-codes";
1287
+ function commanderBridge(root, opts) {
1288
+ const policy = _nullishCoalesce(opts.policy, () => ( defaultPolicy()));
1289
+ const leaves = () => {
1290
+ const out = [];
1291
+ walkLeaves(root, [], (cmd, path) => {
1292
+ const leaf = {
1293
+ path,
1294
+ description: _nullishCoalesce(cmd.description(), () => ( "")),
1295
+ ...collectFlags(cmd),
1296
+ class: classify(cmd)
1297
+ };
1298
+ const en = _optionalChain([opts, 'access', _23 => _23.enabled, 'optionalCall', _24 => _24(leaf)]);
1299
+ if (en) leaf.enabled = en;
1300
+ out.push(leaf);
1301
+ });
1302
+ return out;
1303
+ };
1304
+ return {
1305
+ leaves,
1306
+ async invoke(inv) {
1307
+ const target = leaves().find(
1308
+ (l) => l.path.length === inv.path.length && l.path.every((seg, i) => seg === inv.path[i])
1309
+ );
1310
+ if (target === void 0) {
1311
+ throw new UnknownCommandError(
1312
+ `unknown command: ${toolName(inv.path)}`
1313
+ );
1314
+ }
1315
+ if (_optionalChain([target, 'access', _25 => _25.enabled, 'optionalAccess', _26 => _26[inv.meta.surface]]) === false) {
1316
+ throw new SurfaceNotEnabledError(
1317
+ `surface not enabled: ${inv.meta.surface}`
1318
+ );
1319
+ }
1320
+ if (!policyAllowed(policy, _nullishCoalesce(target.class, () => ( {})), inv.meta.surface)) {
1321
+ throw new DestructiveBlockedError(
1322
+ target.path.join(" "),
1323
+ inv.meta.surface
1324
+ );
1325
+ }
1326
+ const cmd = findCommand(root, target.path);
1327
+ if (cmd === void 0) {
1328
+ throw new UnknownCommandError(
1329
+ `unknown command: ${toolName(inv.path)}`
1330
+ );
1331
+ }
1332
+ return opts.run(inv, cmd);
1333
+ }
1334
+ };
1335
+ }
1336
+ function classify(cmd) {
1337
+ const ann = _nullishCoalesce(cmd.annotations, () => ( {}));
1338
+ const cls = {};
1339
+ switch (ann[ANN_SIDE_EFFECT]) {
1340
+ case "destructive":
1341
+ case "destructive-local":
1342
+ case "destructive-shared":
1343
+ cls.destructive = true;
1344
+ break;
1345
+ default:
1346
+ break;
1347
+ }
1348
+ if (ann[ANN_AUTH_REQUIRED] === "true") cls.authRequired = true;
1349
+ if (ann[ANN_REQUIRES_CONFIRM] === "true") cls.requiresConfirmation = true;
1350
+ const perms = splitCSV(ann[ANN_PERMISSIONS]);
1351
+ if (perms) cls.permissions = perms;
1352
+ const codes = splitCSV(ann[ANN_EXIT_CODES]);
1353
+ if (codes) cls.exitCodes = codes;
1354
+ return cls;
1355
+ }
1356
+ function splitCSV(s) {
1357
+ if (!s) return void 0;
1358
+ const out = s.split(",").map((p) => p.trim()).filter((p) => p !== "");
1359
+ return out.length > 0 ? out : void 0;
1360
+ }
1361
+ function walkLeaves(cmd, path, visit) {
1362
+ const subs = cmd.commands;
1363
+ if (subs.length === 0) {
1364
+ if (path.length > 0) visit(cmd, path);
1365
+ return;
1366
+ }
1367
+ for (const sub of subs) {
1368
+ walkLeaves(sub, [...path, sub.name()], visit);
1369
+ }
1370
+ }
1371
+ function findCommand(root, path) {
1372
+ let cur = root;
1373
+ for (const seg of path) {
1374
+ const next = cur.commands.find((c) => c.name() === seg);
1375
+ if (next === void 0) return void 0;
1376
+ cur = next;
1377
+ }
1378
+ return cur;
1379
+ }
1380
+ function collectFlags(cmd) {
1381
+ const properties = {};
1382
+ const required = [];
1383
+ const seen = /* @__PURE__ */ new Set();
1384
+ for (const opt of cmd.options) {
1385
+ if (opt.hidden) continue;
1386
+ const name = optionName(opt);
1387
+ if (name === "" || seen.has(name)) continue;
1388
+ seen.add(name);
1389
+ properties[name] = flagProperty(opt);
1390
+ if (opt.mandatory) required.push(name);
1391
+ }
1392
+ return required.length > 0 ? { properties, required } : { properties };
1393
+ }
1394
+ function optionName(opt) {
1395
+ const long = opt.long;
1396
+ if (long) return long.replace(/^--/, "");
1397
+ return (_nullishCoalesce(opt.short, () => ( ""))).replace(/^-/, "");
1398
+ }
1399
+ function flagProperty(opt) {
1400
+ const type = optionJSONType(opt);
1401
+ const prop = {
1402
+ type,
1403
+ description: _nullishCoalesce(opt.description, () => ( ""))
1404
+ };
1405
+ if (type === "array") prop.items = { type: "string" };
1406
+ return prop;
1407
+ }
1408
+ function optionJSONType(opt) {
1409
+ if (opt.variadic) return "array";
1410
+ if (typeof opt.isBoolean === "function" && opt.isBoolean()) return "boolean";
1411
+ return "string";
1412
+ }
1413
+
1414
+
1415
+
1416
+
1417
+
1418
+
1419
+
1420
+
1421
+
1422
+
1423
+
1424
+
1425
+
1426
+
1427
+
1428
+
1429
+
1430
+
1431
+
1432
+
1433
+
1434
+
1435
+
1436
+
1437
+
1438
+
1439
+
1440
+
1441
+
1442
+
1443
+
1444
+
1445
+
1446
+
1447
+
1448
+
1449
+
1450
+
1451
+
1452
+
1453
+
1454
+
1455
+
1456
+
1457
+
1458
+
1459
+
1460
+
1461
+
1462
+
1463
+
1464
+
1465
+
1466
+
1467
+
1468
+
1469
+
1470
+
1471
+
1472
+
1473
+
1474
+
1475
+
1476
+
1477
+
1478
+
1479
+
1480
+
1481
+
1482
+
1483
+
1484
+
1485
+
1486
+
1487
+
1488
+
1489
+
1490
+
1491
+ 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.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.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.commanderBridge = commanderBridge; exports.mcp_exports = mcp_exports;