@hop-top/kit 0.5.0-alpha.0 → 0.5.0-alpha.2

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