@hop-top/kit 0.5.0-alpha.1 → 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 (101) hide show
  1. package/CHANGELOG.md +87 -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 +190 -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 +1 -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 +21 -3
  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 +120 -31
  98. package/src/tui/parity.ts +58 -7
  99. package/test/output/csv.test.ts +164 -0
  100. package/test/output/error.test.ts +241 -0
  101. package/src/tui/parity.json +0 -74
@@ -0,0 +1,1073 @@
1
+ import { Command } from 'commander';
2
+
3
+ /**
4
+ * @module mcp/types
5
+ * @package @hop-top/kit
6
+ *
7
+ * Shared vocabulary for the dual-spec MCP surface: the bridge
8
+ * abstraction the surface invokes through, the safety gate, the
9
+ * mount options, and the canonical JSON encoder that makes wire
10
+ * output byte-identical to the Go reference.
11
+ *
12
+ * Protocol constants are taken from the official v2 SDK
13
+ * (@modelcontextprotocol/server) rather than re-declared here, so a
14
+ * reserved key or spec error code can never drift from upstream. The
15
+ * v1 package (@modelcontextprotocol/sdk) is legacy-era only and
16
+ * cannot serve 2026-07-28 — it is deliberately not a dependency.
17
+ */
18
+
19
+ /** Reserved `params._meta` / result `_meta` keys (from the v2 SDK). */
20
+ declare const META_KEY_PROTOCOL_VERSION = "io.modelcontextprotocol/protocolVersion";
21
+ declare const META_KEY_CLIENT_INFO = "io.modelcontextprotocol/clientInfo";
22
+ declare const META_KEY_CLIENT_CAPABILITIES = "io.modelcontextprotocol/clientCapabilities";
23
+ declare const META_KEY_SERVER_INFO = "io.modelcontextprotocol/serverInfo";
24
+ /** Header names carrying the modern routing signals. */
25
+ declare const HEADER_MCP_PROTOCOL_VERSION = "MCP-Protocol-Version";
26
+ declare const HEADER_MCP_METHOD = "Mcp-Method";
27
+ declare const HEADER_MCP_NAME = "Mcp-Name";
28
+ /**
29
+ * JSON-RPC error codes. The base codes and the two spec-reserved
30
+ * 2026-07-28 additions come from the SDK's ProtocolErrorCode;
31
+ * HeaderMismatch (-32020) is spec-reserved but absent from the SDK
32
+ * enum, so it is pinned here.
33
+ */
34
+ declare const MCP_ERR_PARSE = ProtocolErrorCode.ParseError;
35
+ declare const MCP_ERR_INVALID_REQUEST = ProtocolErrorCode.InvalidRequest;
36
+ declare const MCP_ERR_METHOD_NOT_FOUND = ProtocolErrorCode.MethodNotFound;
37
+ declare const MCP_ERR_INVALID_PARAMS = ProtocolErrorCode.InvalidParams;
38
+ declare const MCP_ERR_INTERNAL = ProtocolErrorCode.InternalError;
39
+ declare const MCP_ERR_HEADER_MISMATCH = -32020;
40
+ declare const MCP_ERR_MISSING_CLIENT_CAPABILITY = ProtocolErrorCode.MissingRequiredClientCapability;
41
+ declare const MCP_ERR_UNSUPPORTED_VERSION = ProtocolErrorCode.UnsupportedProtocolVersion;
42
+ /** The two protocol revisions this surface serves. */
43
+ declare const MCP_SPEC_2024_11_05 = "2024-11-05";
44
+ declare const MCP_SPEC_2026_07_28 = "2026-07-28";
45
+ type McpSpecVersion = typeof MCP_SPEC_2024_11_05 | typeof MCP_SPEC_2026_07_28;
46
+ /** resultType discriminator values on modern result envelopes. */
47
+ declare const RESULT_TYPE_COMPLETE = "complete";
48
+ declare const RESULT_TYPE_INPUT_REQUIRED = "input_required";
49
+ /** cacheScope values on modern cacheable list results. */
50
+ type McpCacheScope = 'public' | 'private';
51
+ /** Default server identity, matching Go's cmdsurface defaults. */
52
+ declare const DEFAULT_MCP_SERVER_NAME = "cmdsurface";
53
+ declare const DEFAULT_MCP_SERVER_VERSION = "0.0.0";
54
+ declare const DEFAULT_MCP_PATH = "/mcp";
55
+ /**
56
+ * Surfaces a leaf may be invoked through. Mirrors Go's Surface type;
57
+ * both MCP spec revisions share the single "mcp" surface — one
58
+ * mount, one exposure decision.
59
+ */
60
+ type Surface = 'cli' | 'lib' | 'mcp' | 'rest' | 'rpc' | 'ws' | 'bus';
61
+ declare const SURFACE_CLI: Surface;
62
+ declare const SURFACE_LIB: Surface;
63
+ declare const SURFACE_MCP: Surface;
64
+ /**
65
+ * SafetyClass is the bridge's read of a leaf's safety annotations —
66
+ * the input the policy gate consults. Mirrors Go's SafetyClass.
67
+ */
68
+ interface SafetyClass {
69
+ /** Set for the destructive kit/side-effect tiers. */
70
+ destructive?: boolean;
71
+ /** Set when kit/auth-required is "true". */
72
+ authRequired?: boolean;
73
+ /** Set when kit/requires-confirmation is "true". */
74
+ requiresConfirmation?: boolean;
75
+ permissions?: string[];
76
+ exitCodes?: string[];
77
+ }
78
+ /**
79
+ * Policy gates which Surface may invoke a leaf of a given
80
+ * SafetyClass. Ported from Go's cmdsurface Policy — NOT from
81
+ * src/safety.ts, which implements the unrelated Factor 10 CLI
82
+ * `--force` guard and has no bearing on surface exposure.
83
+ */
84
+ interface Policy {
85
+ /**
86
+ * Surfaces on which destructive leaves MAY be invoked. CLI and Lib
87
+ * are always allowed regardless. Empty = block all remote
88
+ * destructive invocation (the default).
89
+ */
90
+ allowDestructiveOn?: Surface[];
91
+ /** Surfaces a leaf is exposed on when its config omits `enabled`. */
92
+ defaultEnabled?: Surface[];
93
+ }
94
+ /**
95
+ * The conservative default policy: no remote surface may invoke a
96
+ * destructive command; default enablement is CLI + Lib + MCP.
97
+ * `allowDestructiveOn` is deliberately empty — empty means block-all,
98
+ * not allow-all.
99
+ */
100
+ declare function defaultPolicy(): Policy;
101
+ /**
102
+ * Reports whether `cls` may be invoked via surface `s` under `p`.
103
+ *
104
+ * 1. cli and lib are always allowed (local runtime).
105
+ * 2. Non-destructive commands are allowed on every other surface.
106
+ * 3. Destructive commands are allowed only when `s` is listed in
107
+ * `allowDestructiveOn`.
108
+ *
109
+ * Surface enablement (per-leaf opt-in) is gated separately; this
110
+ * enforces only the destructive ceiling.
111
+ */
112
+ declare function policyAllowed(p: Policy, cls: SafetyClass, s: Surface): boolean;
113
+ /** Error a bridge raises when the policy gate blocks a leaf. */
114
+ declare class DestructiveBlockedError extends Error {
115
+ constructor(pathLabel: string, surface: Surface);
116
+ }
117
+ /** Error a bridge raises when a leaf path resolves to nothing. */
118
+ declare class UnknownCommandError extends Error {
119
+ constructor(message?: string);
120
+ }
121
+ /** Error a bridge raises when a leaf is not exposed on the surface. */
122
+ declare class SurfaceNotEnabledError extends Error {
123
+ constructor(message?: string);
124
+ }
125
+ /** A JSON Schema property object describing one flag. */
126
+ interface FlagSchema {
127
+ type: string;
128
+ description: string;
129
+ items?: {
130
+ type: string;
131
+ };
132
+ }
133
+ /**
134
+ * One invocable leaf command exposed as an MCP tool. `path` is the
135
+ * leaf's command path; the MCP tool name is the dotted join.
136
+ */
137
+ interface Leaf {
138
+ /** Command path, e.g. ["widget","add"] → tool "widget.add". */
139
+ path: string[];
140
+ /** Short description, used as the tool description. */
141
+ description: string;
142
+ /** JSON Schema properties derived from the leaf's flags. */
143
+ properties: Record<string, FlagSchema>;
144
+ /** Names of required flags, in declaration order. */
145
+ required?: string[];
146
+ /** Safety annotations consulted by the policy gate. */
147
+ class?: SafetyClass;
148
+ /** Surfaces this leaf is exposed on. */
149
+ enabled?: Partial<Record<Surface, boolean>>;
150
+ }
151
+ /** Metadata attached to one invocation, forwarded to audit sinks. */
152
+ interface InvocationMeta {
153
+ surface: Surface;
154
+ requestedAt: Date;
155
+ /** Free-form audit bag; the modern path records spec + client info. */
156
+ extra?: Record<string, string>;
157
+ }
158
+ /** One leaf invocation. */
159
+ interface Invocation {
160
+ path: string[];
161
+ flags?: Record<string, unknown>;
162
+ meta: InvocationMeta;
163
+ }
164
+ /** The result of invoking a leaf. */
165
+ interface InvokeResult {
166
+ stdout: string;
167
+ stderr?: string;
168
+ exitCode: number;
169
+ /** Structured payload; becomes structuredContent on the modern path. */
170
+ data?: unknown;
171
+ }
172
+ /**
173
+ * The command-tree abstraction the MCP surface serves. Adopters
174
+ * implement this over their own command framework (see
175
+ * `commanderBridge` for a commander adapter); the surface itself
176
+ * never touches commander, so it stays framework-free.
177
+ */
178
+ interface McpBridge {
179
+ /** Every leaf known to the bridge, in stable enumeration order. */
180
+ leaves(): Leaf[];
181
+ /**
182
+ * Invokes one leaf. MUST apply the policy gate and throw
183
+ * DestructiveBlockedError when it blocks, so both eras inherit the
184
+ * identical destructive ceiling from one code path.
185
+ */
186
+ invoke(inv: Invocation): Promise<InvokeResult> | InvokeResult;
187
+ }
188
+ /**
189
+ * Mount options, mirroring Go's MountMCP option set. Defaults match
190
+ * Go exactly: both eras, path "/mcp", empty origin allowlist, cache
191
+ * hints ttlMs=0 / cacheScope="private".
192
+ */
193
+ interface McpMountOptions {
194
+ /** Mount path. Default "/mcp". */
195
+ path?: string;
196
+ /** Server identity in serverInfo. */
197
+ serverInfo?: {
198
+ name: string;
199
+ version: string;
200
+ };
201
+ /**
202
+ * Which eras this mount serves. Absent = both. An explicit empty
203
+ * array, or an unrecognized version, is a mount-time error.
204
+ */
205
+ specVersions?: McpSpecVersion[];
206
+ /** ttlMs + cacheScope on modern cacheable list results. */
207
+ cacheHints?: {
208
+ ttlMs?: number;
209
+ cacheScope?: McpCacheScope;
210
+ };
211
+ /** Exact-match Origin allowlist; absent = no Origin check. */
212
+ originAllowlist?: string[];
213
+ /** HMAC key enabling the MRTR confirmation flow. Must be non-empty. */
214
+ confirmationKey?: Uint8Array | string;
215
+ /** Policy gate. Default: defaultPolicy(). */
216
+ policy?: Policy;
217
+ }
218
+ /** Resolved, validated mount configuration. */
219
+ interface ResolvedMcpConfig {
220
+ path: string;
221
+ serverName: string;
222
+ serverVersion: string;
223
+ legacyEnabled: boolean;
224
+ modernEnabled: boolean;
225
+ cacheTtlMs: number;
226
+ cacheScope: McpCacheScope;
227
+ originAllowlist: string[];
228
+ confirmationKey?: Uint8Array;
229
+ policy: Policy;
230
+ }
231
+ /**
232
+ * Validates and resolves mount options. Reproduces Go's two
233
+ * mount-time errors rather than silently absorbing them: an explicit
234
+ * empty spec-version set, and a negative ttl or unrecognized scope.
235
+ */
236
+ declare function resolveMcpConfig(opts?: McpMountOptions): ResolvedMcpConfig;
237
+ /** Renders a leaf path as a dotted MCP tool name. */
238
+ declare function toolName(path: string[]): string;
239
+ /** Splits a dotted MCP tool name back into a leaf path. */
240
+ declare function pathFromToolName(name: string): string[];
241
+ /** Renders one leaf as an MCP tool descriptor (shared by both eras). */
242
+ declare function buildToolEnvelope(leaf: Leaf): Record<string, unknown>;
243
+ /**
244
+ * Renders a bridge result as the tools/call content block list.
245
+ * Shared verbatim by both eras so content layout cannot drift:
246
+ * stdout text block, "[stderr] " block when present, JSON text block
247
+ * when `data` is present.
248
+ */
249
+ declare function renderCallResult(res: InvokeResult): Record<string, unknown>;
250
+ /** A tools/call result envelope flagged isError with one text block. */
251
+ declare function errorResultBlock(msg: string): Record<string, unknown>;
252
+ /**
253
+ * A pre-serialized JSON fragment emitted verbatim. Used to echo a
254
+ * request `id` back exactly as received (including `null`, which Go
255
+ * round-trips byte-for-byte through json.RawMessage).
256
+ */
257
+ declare class RawJSON {
258
+ readonly raw: string;
259
+ constructor(raw: string);
260
+ }
261
+ /**
262
+ * Serializes a value the way Go's encoding/json does for the shapes
263
+ * this surface emits, so wire output is byte-identical to the Go
264
+ * reference rather than merely structurally equal — the fixtures
265
+ * compare bytes, with no decode/re-encode step.
266
+ *
267
+ * Go's rule is not "sort everything": `encoding/json` emits STRUCT
268
+ * fields in declaration order and MAP keys in sorted order. This
269
+ * surface builds result bodies as map[string]any (sorted) inside a
270
+ * jsonRPCResponse struct (declaration order), so the encoder mirrors
271
+ * exactly that split: plain objects are sorted, and the response
272
+ * envelope is emitted through `encodeEnvelope` below, which pins
273
+ * field order. Sorting is by UTF-16 code unit (the JS default),
274
+ * which agrees with Go's byte-wise sort over the ASCII keys emitted
275
+ * here.
276
+ */
277
+ declare function canonicalJSONStringify(value: unknown): string;
278
+ /** A JSON-RPC error object, emitted in Go struct-field order. */
279
+ interface JsonRpcErrorObject {
280
+ code: number;
281
+ message: string;
282
+ data?: unknown;
283
+ }
284
+ /**
285
+ * Encodes one JSON-RPC response envelope with Go's struct field
286
+ * order — `jsonrpc`, `id`, then `result` or `error` — and a trailing
287
+ * newline, matching json.Encoder.Encode. `id` is omitted entirely
288
+ * when absent (Go's `omitempty` on a nil json.RawMessage) but
289
+ * emitted as `null` when the request carried an explicit null id.
290
+ */
291
+ declare function encodeEnvelope(env: {
292
+ id?: RawJSON;
293
+ result?: unknown;
294
+ error?: JsonRpcErrorObject;
295
+ }): string;
296
+
297
+ /**
298
+ * @module mcp/dispatch
299
+ * @package @hop-top/kit
300
+ *
301
+ * Era detection + dispatch for the dual-spec MCP surface, plus the
302
+ * framework-free handler export.
303
+ *
304
+ * Hosting model (ADR 0043 §2): this module exports a
305
+ * transport-agnostic request handler, not a server. Binding it to
306
+ * node:http, hono, express, fastify, or a Worker is the adopter's
307
+ * job — kit does not own the adopter's HTTP stack, and a pure
308
+ * request→response function is directly testable against the wire
309
+ * fixtures with no socket.
310
+ *
311
+ * Detection implements ADR 0042's normative rules literally: the
312
+ * marker set M1-M4, the two deliberate non-markers, and the
313
+ * precedence chain D1-D4. It deliberately does NOT delegate to the
314
+ * v2 SDK's own `classifyInboundRequest`: that classifier treats a
315
+ * modern `MCP-Protocol-Version` header as a routing signal and
316
+ * routes `initialize`-plus-modern-envelope to the modern era, both
317
+ * of which contradict ADR 0042 (and the wire fixtures, which are the
318
+ * parity contract). The SDK is still the source of the protocol
319
+ * constants and error codes — see types.ts.
320
+ */
321
+
322
+ /**
323
+ * A normalized inbound request: method, headers, and body bytes. A
324
+ * header may repeat, which the modern header checks treat as
325
+ * significant, so values may be an array.
326
+ */
327
+ interface McpHttpRequest {
328
+ /** HTTP method, e.g. "POST". */
329
+ method: string;
330
+ /** Header names are matched case-insensitively. */
331
+ headers?: Record<string, string | string[] | undefined>;
332
+ /** Raw body bytes, exactly as received — never re-encoded. */
333
+ body?: string;
334
+ }
335
+ /** A normalized response: status, headers, and body bytes. */
336
+ interface McpHttpResponse {
337
+ status: number;
338
+ headers: Record<string, string>;
339
+ body: string;
340
+ }
341
+ /**
342
+ * A decoded JSON-RPC request envelope. `id` is kept as a raw JSON
343
+ * fragment so it round-trips byte-for-byte (Go uses json.RawMessage
344
+ * for exactly this reason), and its absence is distinguishable from
345
+ * an explicit null.
346
+ */
347
+ interface JsonRpcRequest {
348
+ jsonrpc?: string;
349
+ id?: RawJSON;
350
+ method: string;
351
+ params?: unknown;
352
+ }
353
+ /** Which handler a request routes to. */
354
+ type McpEra = 'legacy' | 'modern';
355
+ /**
356
+ * Implements ADR 0042's per-request era detection, precedence D1-D4.
357
+ * Never fails — it only classifies an already-parsed request; D1
358
+ * (parse) is the caller's responsibility.
359
+ *
360
+ * Markers:
361
+ * M1 — Mcp-Method header present
362
+ * M2 — Mcp-Name header present
363
+ * M3 — params._meta contains the reserved protocolVersion key
364
+ * (key presence only; the value is not inspected here)
365
+ * M4 — method == "server/discover"
366
+ *
367
+ * Deliberate non-markers, both of which are the subtle part and the
368
+ * most likely source of silent divergence:
369
+ * - Bare params._meta. 2024-11-05 clients legitimately send
370
+ * _meta.progressToken and OTel traceparent; only the reserved
371
+ * protocolVersion key signals modern.
372
+ * - The MCP-Protocol-Version header, at any value. It predates
373
+ * 2026-07-28, so clients that negotiated down to legacy send it
374
+ * on every subsequent request; treating it as a modern signal
375
+ * would serve their handshake and then brick the session.
376
+ */
377
+ declare function detectMcpEra(req: McpHttpRequest, rpc: JsonRpcRequest): McpEra;
378
+ /**
379
+ * M3: whether params._meta carries the reserved protocolVersion key.
380
+ * Only key presence is tested; the value is never inspected at
381
+ * detection time. Malformed or non-object params/_meta are treated as
382
+ * "no marker" — detection never fails, and shape errors are the
383
+ * handlers' business.
384
+ */
385
+ declare function hasModernMetaMarker(params: unknown): boolean;
386
+ /** A framework-free MCP request handler. */
387
+ type McpHandler = (req: McpHttpRequest) => Promise<McpHttpResponse>;
388
+ /**
389
+ * Builds the MCP handler for a bridge. Mirrors Go's
390
+ * `MountMCP(bridge, router, opts...)`, minus the router: the caller
391
+ * binds the returned function to whatever HTTP stack it uses.
392
+ *
393
+ * Defaults match Go exactly: both eras enabled, path "/mcp", empty
394
+ * origin allowlist, cache hints ttlMs=0 / cacheScope="private".
395
+ * The two mount-time errors are reproduced rather than absorbed —
396
+ * an explicit empty spec-version set, and a negative ttl or
397
+ * unrecognized cache scope, both throw here.
398
+ */
399
+ declare function createMcpHandler(bridge: McpBridge, opts?: McpMountOptions): McpHandler;
400
+ /** The resolved mount config for a handler, for adopters that need it. */
401
+ declare function mcpMountConfig(opts?: McpMountOptions): ResolvedMcpConfig;
402
+ /**
403
+ * Routes each request to exactly one era's handler. Holds no mutable
404
+ * per-request state; both handlers are safe to share concurrently.
405
+ */
406
+ declare class McpDispatcher {
407
+ private readonly cfg;
408
+ private readonly legacy;
409
+ private readonly modern;
410
+ constructor(bridge: McpBridge, cfg: ResolvedMcpConfig);
411
+ handle(req: McpHttpRequest): Promise<McpHttpResponse>;
412
+ }
413
+ /** The 405 GET/DELETE answer at the mount path. */
414
+ declare function methodNotAllowedResponse(): McpHttpResponse;
415
+ /**
416
+ * Parses one JSON-RPC request, preserving the `id` as raw bytes.
417
+ * Throws on unparseable JSON so the caller can render D1's -32700.
418
+ */
419
+ declare function parseJsonRpcRequest(body: string): JsonRpcRequest;
420
+
421
+ /**
422
+ * @module mcp/legacy
423
+ * @package @hop-top/kit
424
+ *
425
+ * The 2024-11-05 MCP handler: `initialize`, `tools/list`,
426
+ * `tools/call`, plain JSON-RPC over one POST path, no sessions, no
427
+ * SSE.
428
+ *
429
+ * This module is byte-for-byte frozen. ADR 0042's hard invariant is
430
+ * "2024-11-05 behavior is preserved byte-for-byte; additive only; no
431
+ * deprecation", and the three-way module split (legacy / modern /
432
+ * dispatch) exists precisely so a reviewer can confirm a modern-era
433
+ * change did not touch this file. Modern-era behavior belongs in
434
+ * modern.ts — never here.
435
+ */
436
+
437
+ /**
438
+ * The 2024-11-05 handler. Stateless across requests; holds only
439
+ * immutable mount configuration and the bridge.
440
+ */
441
+ declare class LegacyMcpHandler {
442
+ private readonly bridge;
443
+ private readonly cfg;
444
+ constructor(bridge: McpBridge, cfg: ResolvedMcpConfig);
445
+ /**
446
+ * Routes one already-parsed JSON-RPC request by method. An unknown
447
+ * method returns -32601 at HTTP 200 — today's behavior, preserved
448
+ * deliberately (the modern handler uses 404 instead; the asymmetry
449
+ * is required by byte-for-byte preservation).
450
+ */
451
+ serve(req: McpHttpRequest, rpc: JsonRpcRequest): Promise<McpHttpResponse>;
452
+ /** The minimal initialize response: version, capabilities, identity. */
453
+ private handleInitialize;
454
+ /** One tool envelope per leaf exposed on the MCP surface. */
455
+ private handleToolsList;
456
+ private exposedTools;
457
+ /**
458
+ * Resolves the leaf, applies the pre-flight auth + confirmation
459
+ * gates, and dispatches through the bridge. Unknown / not-enabled
460
+ * tools are JSON-RPC errors; every other failure (bridge errors,
461
+ * destructive blocks, non-zero exit codes) is an isError result.
462
+ */
463
+ private handleToolsCall;
464
+ }
465
+
466
+ /**
467
+ * @module mcp/modern-confirm
468
+ * @package @hop-top/kit
469
+ *
470
+ * MRTR (multi round-trip requests) confirmation for the modern
471
+ * (2026-07-28) `tools/call` path: the elicitation-based strategy that
472
+ * fills the confirmation-gate slot when a mount is given key material
473
+ * via `confirmationKey`.
474
+ *
475
+ * Flow (spec: basic/patterns/mrtr + client/elicitation): the first
476
+ * call on a `kit/requires-confirmation` leaf returns `resultType`
477
+ * "input_required" carrying a single `elicitation/create` form request
478
+ * under the reserved `inputRequests` key "confirm" plus an
479
+ * integrity-protected `requestState`. The client gathers the user's
480
+ * decision and retries the original call (new JSON-RPC id) with
481
+ * `params.inputResponses` and the echoed `params.requestState`; the
482
+ * gate verifies the state and lets the invocation proceed only when the
483
+ * confirm response's action is "accept". Decline/cancel refuse the call
484
+ * with an isError complete result.
485
+ *
486
+ * Statelessness: everything a retry needs lives inside `requestState`.
487
+ * There is no server-side pending-request storage of any kind, so any
488
+ * instance holding the same key verifies state minted by any other —
489
+ * which is exactly why the key must be adopter-supplied and shared, and
490
+ * why there is deliberately no generated-at-mount default. The
491
+ * corollary (spec: replay warning) is that an accepted state remains
492
+ * honorable for identical (leaf, arguments, principal) until its TTL
493
+ * lapses; single-use redemption would require the server-side state
494
+ * this surface deliberately does not keep, so the short TTL bounds the
495
+ * window instead.
496
+ *
497
+ * Two verification failures are deliberately distinct (ADR 0004): an
498
+ * expired-but-authentic state is a routine re-prompt; a state failing
499
+ * HMAC verification is never honored — the rejection is recorded as a
500
+ * security-relevant audit event first, and only then is a fresh prompt
501
+ * (with newly minted state) issued. Tampering can therefore cost a
502
+ * request, but is never silently treated as a re-prompt.
503
+ *
504
+ * MRTR confirmation is an alternative way to SATISFY confirmation,
505
+ * never a way to bypass the destructive ceiling: the policy gate runs
506
+ * inside `bridge.invoke` after this gate, exactly as on every other
507
+ * path.
508
+ */
509
+
510
+ /**
511
+ * The single reserved `inputRequests` key the confirmation flow uses;
512
+ * the retry's answer is read from the same key in
513
+ * `params.inputResponses`.
514
+ */
515
+ declare const MCP_CONFIRM_KEY = "confirm";
516
+ /**
517
+ * Lifetime of a minted `requestState`, in seconds. Long enough for a
518
+ * human to read and answer the prompt; short enough to bound the replay
519
+ * window the stateless design cannot otherwise close (see the module
520
+ * comment).
521
+ */
522
+ declare const MCP_CONFIRM_STATE_TTL_SECONDS: number;
523
+ /**
524
+ * Tags the `requestState` wire format so a future format change
525
+ * invalidates (rather than misparses) old state.
526
+ */
527
+ declare const MCP_CONFIRM_STATE_VERSION = "v1";
528
+ /**
529
+ * The request context a `requestState` is bound to. The HMAC covers
530
+ * every field plus the expiry, so state presented for a different leaf,
531
+ * different arguments, or by a different principal fails verification
532
+ * outright (spec: reject state presented on a request that does not
533
+ * match / by a different principal).
534
+ */
535
+ interface McpConfirmBinding {
536
+ /** The leaf path key, space-joined, e.g. "widget purge". */
537
+ tool: string;
538
+ /** Hex SHA-256 of the canonically serialized `params.arguments`. */
539
+ argsDigest: string;
540
+ /**
541
+ * Hex SHA-256 of the `Authorization` header value, or "" when the
542
+ * request carried none. Hashed so the MAC input never embeds
543
+ * credential material.
544
+ */
545
+ principal: string;
546
+ }
547
+ /** The outcome of verifying a presented `requestState`. */
548
+ type McpConfirmStateStatus = 'valid' | 'expired' | 'invalid';
549
+ /** One recorded rejection of a state that failed integrity verification. */
550
+ interface McpConfirmRejection {
551
+ path: string;
552
+ mcpConfirmRejection: string;
553
+ }
554
+ /** A gate decision: the result body to write plus its HTTP status. */
555
+ type McpConfirmDecision = {
556
+ result: Record<string, unknown>;
557
+ status: number;
558
+ };
559
+ /**
560
+ * The MRTR confirmation gate for mounts configured with a
561
+ * `confirmationKey`.
562
+ *
563
+ * Clients that did not declare form-mode elicitation keep the
564
+ * `X-Confirm-Token` header gate: the spec forbids sending
565
+ * `inputRequests` for a capability the client never declared, and the
566
+ * capability stays optional precisely because this fallback exists — so
567
+ * a missing elicitation capability is never -32021 here.
568
+ */
569
+ declare class ElicitationConfirmGate {
570
+ private readonly key;
571
+ /**
572
+ * Audit records of rejected states, standing in for Go's bridge sink
573
+ * fan-out, which this port does not carry.
574
+ */
575
+ readonly rejections: McpConfirmRejection[];
576
+ constructor(key: Uint8Array);
577
+ /**
578
+ * Runs the gate for one `tools/call`. Returns `undefined` to proceed
579
+ * with the invocation, or the refusal / interim result plus its HTTP
580
+ * status. The caller stamps the modern envelope onto whatever is
581
+ * returned.
582
+ */
583
+ evaluate(req: McpHttpRequest, leaf: Leaf, params: unknown): McpConfirmDecision | undefined;
584
+ /**
585
+ * Builds the `input_required` result envelope for one confirmation
586
+ * prompt: the reserved "confirm" `elicitation/create` form request
587
+ * plus freshly minted `requestState` (satisfying the spec MUST of
588
+ * carrying at least one of `inputRequests` / `requestState` — this
589
+ * flow always carries both). The caller stamps the envelope (_meta
590
+ * serverInfo; `resultType` stays "input_required") and writes it at
591
+ * HTTP 200. Interim `input_required` results are never cacheable: no
592
+ * `ttlMs` / `cacheScope` members, ever.
593
+ */
594
+ inputRequired(leaf: Leaf, binding: McpConfirmBinding): Record<string, unknown>;
595
+ /**
596
+ * Records a failed `requestState` verification as a
597
+ * security-relevant audit event. Go emits this on the bridge's
598
+ * registered sinks; this port has no sink fan-out, so the records
599
+ * accumulate here for adopters and tests to read. Best-effort by the
600
+ * same contract: recording never affects the response.
601
+ */
602
+ private auditRejection;
603
+ }
604
+ /**
605
+ * The default gate: a `requiresConfirmation` leaf needs the
606
+ * `X-Confirm-Token` header, exactly as on the legacy path. This is the
607
+ * fallback for clients without form elicitation and the whole gate for
608
+ * mounts without a confirmation key.
609
+ */
610
+ declare function headerConfirmationGate(req: McpHttpRequest): McpConfirmDecision | undefined;
611
+ /**
612
+ * Reports whether the request's
613
+ * `io.modelcontextprotocol/clientCapabilities` declares form-mode
614
+ * elicitation. Per spec, an empty `elicitation` object (`{}`) declares
615
+ * form-only support; a non-empty object must name "form" among its
616
+ * modes (a url-only client cannot receive this flow's form request).
617
+ * Anything that is not a conforming object declaration — key absent,
618
+ * value null or non-object — counts as undeclared, failing toward the
619
+ * header fallback rather than toward sending a request the client never
620
+ * said it could handle.
621
+ */
622
+ declare function clientSupportsFormElicitation(params: unknown): boolean;
623
+ /**
624
+ * The tolerant read of the MRTR retry members of a `tools/call`
625
+ * request. Members that are absent or of the wrong JSON type simply
626
+ * stay empty — the gate treats a missing state as "prompt" and a
627
+ * missing/unusable action as "re-prompt", so malformed retries converge
628
+ * on a fresh `input_required` rather than a decode error.
629
+ */
630
+ declare function parseMcpConfirmRetry(params: unknown): {
631
+ state: string;
632
+ action: string;
633
+ };
634
+ /**
635
+ * Derives the principal component of the state binding: hex SHA-256 of
636
+ * the `Authorization` value, "" when the header is absent.
637
+ * Presence-only bearer checking is all this surface does for auth
638
+ * (`class.authRequired`), so the raw header value is the closest stable
639
+ * principal identifier available; hashing keeps credential material out
640
+ * of the MAC input.
641
+ */
642
+ declare function mcpConfirmPrincipal(req: McpHttpRequest): string;
643
+ /**
644
+ * Returns the hex SHA-256 of the canonically serialized
645
+ * `params.arguments`. Canonical form sorts object keys at every nesting
646
+ * level, so equal argument sets digest identically regardless of the
647
+ * client's key order; absent arguments canonicalize to "null". Only the
648
+ * arguments participate: `_meta`, `inputResponses`, and `requestState`
649
+ * all legitimately differ between the first call and its retry, and the
650
+ * tool name is bound separately via the leaf path key.
651
+ */
652
+ declare function mcpConfirmArgsDigest(params: unknown): string;
653
+ /**
654
+ * Renders an opaque-to-clients `requestState`:
655
+ * `v1.<expiry-unix>.<base64url(mac)>`. Only the version and expiry
656
+ * travel in the clear; the full binding is reconstructed from the retry
657
+ * request itself at verification time, which is what keeps the state
658
+ * small and the flow stateless.
659
+ */
660
+ declare function mintMcpConfirmState(key: Uint8Array, binding: McpConfirmBinding, expiry: number): string;
661
+ /**
662
+ * Checks a presented state against the current request's binding.
663
+ * Authenticity is decided BEFORE expiry, so "expired" is only ever
664
+ * reported for a state that verifiably came from this key and this
665
+ * exact binding — a tampered expiry fails the MAC and lands in
666
+ * "invalid", never in "expired". Any structural defect (wrong part
667
+ * count, unknown version, non-decimal expiry, undecodable tag) is a
668
+ * verification failure too: a state that cannot be verified is never
669
+ * honored.
670
+ */
671
+ declare function verifyMcpConfirmState(key: Uint8Array, state: string, binding: McpConfirmBinding, now: number): McpConfirmStateStatus;
672
+
673
+ /**
674
+ * @module mcp/modern
675
+ * @package @hop-top/kit
676
+ *
677
+ * The 2026-07-28 MCP handler: the stateless request core behind the
678
+ * era dispatcher. Implements ADR 0042's validation order V1-V9,
679
+ * `server/discover`, the modern error writers (-32020 / -32021 /
680
+ * -32022 with their status mapping), result-envelope stamping
681
+ * (`resultType` + serverInfo `_meta`), and cache-hint application.
682
+ *
683
+ * Statelessness is the revision's core contract: every request
684
+ * carries protocol version, client identity, and capabilities in
685
+ * `params._meta` under reserved io.modelcontextprotocol/* keys;
686
+ * there is no initialize/initialized handshake and no session id.
687
+ * The handler holds only immutable mount configuration, so any
688
+ * instance can serve any request.
689
+ */
690
+
691
+ /** One validation-chain failure: code, message, status, optional data. */
692
+ interface CheckError {
693
+ code: number;
694
+ msg: string;
695
+ status: number;
696
+ data?: unknown;
697
+ }
698
+ /** The decoded view of the reserved params._meta keys (V3). */
699
+ interface ModernRequestMeta {
700
+ version: string;
701
+ versionIsText: boolean;
702
+ versionRaw: unknown;
703
+ clientName?: string;
704
+ clientVersion?: string;
705
+ hasClientInfo: boolean;
706
+ }
707
+ /** The 2026-07-28 handler. */
708
+ declare class ModernMcpHandler {
709
+ private readonly bridge;
710
+ private readonly cfg;
711
+ /**
712
+ * The MRTR confirmation strategy, installed only when the mount was
713
+ * given key material. Without a key there is nothing to MAC state
714
+ * with, so every client — elicitation-capable or not — keeps the
715
+ * `X-Confirm-Token` header gate.
716
+ */
717
+ readonly confirmGate?: ElicitationConfirmGate;
718
+ constructor(bridge: McpBridge, cfg: ResolvedMcpConfig);
719
+ /**
720
+ * The modern entry point. The validation chain runs in ADR 0042's
721
+ * order V1-V9; the first failure responds and stops. HTTP status is
722
+ * 400/404 only where the spec mandates it — application-level
723
+ * JSON-RPC errors ride HTTP 200, matching legacy's convention.
724
+ */
725
+ serve(req: McpHttpRequest, rpc: JsonRpcRequest): Promise<McpHttpResponse>;
726
+ /**
727
+ * server/discover — the mandatory modern discovery method. Carries
728
+ * no listChanged flag (notifications unimplemented), no extensions
729
+ * map (none supported, which is what makes tasks/* method-not-found),
730
+ * and no instructions.
731
+ */
732
+ private handleDiscover;
733
+ /**
734
+ * Modern tools/list: the same tool envelopes the legacy handler
735
+ * emits (so schema drift between eras cannot happen), wrapped in
736
+ * the modern complete-result envelope with cache hints. Pagination
737
+ * is not implemented — a cursor param is ignored, no nextCursor.
738
+ */
739
+ private handleToolsList;
740
+ /**
741
+ * Modern tools/call: V7, V9, the legacy pre-flight gates, invoke,
742
+ * render. The shared bridge invoke path keeps the policy gate
743
+ * identical across eras — there is no way to reach a leaf here that
744
+ * the legacy path would have blocked. Results carry no cache hints.
745
+ */
746
+ private handleToolsCall;
747
+ /**
748
+ * Selects and runs the confirmation strategy for one `tools/call`.
749
+ * Returns `undefined` to proceed with the invocation.
750
+ *
751
+ * A leaf that does not require confirmation is never gated. A mount
752
+ * without a `confirmationKey` has no state to MAC, so the header gate
753
+ * applies to every client — this is the byte-for-byte preservation
754
+ * path, identical to what the legacy handler does.
755
+ */
756
+ private confirmationGate;
757
+ /** V6: Mcp-Method header presence + agreement with the body method. */
758
+ private validateMethodHeader;
759
+ /**
760
+ * V7: on tools/call the Mcp-Name header MUST be present, non-empty
761
+ * after Base64-sentinel decoding, and byte-equal to params.name,
762
+ * which MUST itself be present. Any violation is a header failure
763
+ * (-32020 @ 400), decided ahead of any body-shape check: headers
764
+ * are the routing signal gateways trust without parsing the body,
765
+ * so an empty or contradicted signal is malformed at the header
766
+ * layer.
767
+ */
768
+ private validateNameHeader;
769
+ /**
770
+ * Adds the members every modern result envelope carries: resultType
771
+ * and a result-level _meta with serverInfo built from the mount's
772
+ * configured identity. A producer that already chose a resultType
773
+ * keeps it (the MRTR confirmation gate stamps "input_required").
774
+ */
775
+ stampResultEnvelope(m: Record<string, unknown>): Record<string, unknown>;
776
+ /**
777
+ * Adds ttlMs and cacheScope to a cacheable complete-result —
778
+ * server/discover and tools/list only; tools/call carries none.
779
+ * Defaults are ttlMs 0 (immediately stale: the leaf set can mutate
780
+ * at runtime and no list_changed notification exists) and
781
+ * cacheScope "private".
782
+ */
783
+ applyCacheHints(m: Record<string, unknown>): Record<string, unknown>;
784
+ /** Opt-in Origin allowlist; a request without Origin is never refused. */
785
+ private originAllowed;
786
+ /**
787
+ * Writes a modern JSON-RPC error. When the rejected request's
788
+ * method is "initialize" the message additionally names the
789
+ * supported versions: a legacy client has no fall-forward
790
+ * mechanism, so the version list in the error text is its only
791
+ * recovery hint.
792
+ */
793
+ private writeModernError;
794
+ /** An isError tools/call result with the modern envelope stamped on. */
795
+ private writeCallError;
796
+ }
797
+ /**
798
+ * Reduces all occurrences of a header to one value for comparison
799
+ * against the body. Sent once, or several times with byte-identical
800
+ * values (benign proxy duplication), resolves to that value. Sent
801
+ * several times with differing values is a validation failure in its
802
+ * own right — conflicting duplicates are exactly the
803
+ * multiple-sources-of-truth hazard header/body validation closes — so
804
+ * ok=false and the caller rejects without comparing anything.
805
+ */
806
+ declare function singleHeaderValue(req: McpHttpRequest, name: string): {
807
+ value: string;
808
+ ok: boolean;
809
+ };
810
+ /**
811
+ * V2's id rule: a JSON string, or a JSON number with no fractional
812
+ * part. Base JSON-RPC also allows null, but this revision forbids it;
813
+ * boolean, object, and array ids are rejected the same way.
814
+ */
815
+ declare function validModernRequestId(id: RawJSON): boolean;
816
+ /**
817
+ * V3: decodes the reserved params._meta keys. protocolVersion and
818
+ * clientCapabilities are required; clientInfo is optional. A missing
819
+ * or non-object params/_meta fails the same way as missing keys.
820
+ */
821
+ declare function parseModernMeta(params: unknown): {
822
+ meta: ModernRequestMeta;
823
+ } | {
824
+ error: CheckError;
825
+ };
826
+ /**
827
+ * Peeks params.name out of a tools/call body without requiring the
828
+ * rest of params to decode, so V7 can run independently of whatever
829
+ * else is wrong with the body. `present` reports whether params is an
830
+ * object carrying a "name" key at all; `isString` distinguishes a
831
+ * non-string value, which V7 defers to V9 rather than treating as
832
+ * absent.
833
+ */
834
+ declare function rawToolCallName(params: unknown): {
835
+ name: string;
836
+ present: boolean;
837
+ isString: boolean;
838
+ };
839
+ /**
840
+ * Decodes a header value that may carry the Base64 sentinel encoding.
841
+ * A value that is not sentinel-wrapped is returned unchanged.
842
+ * A wrapped value that fails to decode returns undefined so the
843
+ * caller fails closed: the spec requires decoding before comparing,
844
+ * and a malformed encoding can never legitimately match the body.
845
+ * A value that merely looks like the sentinel is always treated as
846
+ * encoded, per spec.
847
+ */
848
+ declare function decodeMcpSentinel(v: string): string | undefined;
849
+ /**
850
+ * The Meta.extra audit bag for a modern invocation: the spec version
851
+ * always, and the client identity when the request carried clientInfo.
852
+ */
853
+ declare function modernInvocationExtra(meta: ModernRequestMeta): Record<string, string>;
854
+
855
+ /**
856
+ * @module mcp/tasks
857
+ * @package @hop-top/kit
858
+ *
859
+ * The `io.modelcontextprotocol/tasks` extension slot.
860
+ *
861
+ * kit does not implement the tasks extension (ADR 0042 gap matrix:
862
+ * "Not implemented. capabilities.extensions omitted from
863
+ * server/discover (= unsupported); tasks/* → -32601 @ 404"). This
864
+ * module makes that decision explicit and testable rather than
865
+ * implicit in a `default:` branch, and marks the designated slot if
866
+ * the extension is ever added.
867
+ *
868
+ * The negotiation contract matters for parity: because
869
+ * server/discover omits `capabilities.extensions` entirely, a
870
+ * conforming client never negotiates the extension and never sends
871
+ * `tasks/*`. A client that sends it anyway gets the same
872
+ * method-not-found response any other unknown modern method gets —
873
+ * NOT a distinct "extension unsupported" error, which would be a wire
874
+ * behavior the Go reference does not produce.
875
+ */
876
+ /** The reserved extension identifier, as named by the spec. */
877
+ declare const TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
878
+ /**
879
+ * The task-extension methods. Listed so the surface can recognize
880
+ * them for documentation and testing purposes; recognizing one does
881
+ * NOT change its response.
882
+ */
883
+ declare const TASK_METHODS: readonly ["tasks/get", "tasks/update", "tasks/list", "tasks/result", "tasks/cancel"];
884
+ type TaskMethod = (typeof TASK_METHODS)[number];
885
+ /** Reports whether a method name belongs to the tasks extension. */
886
+ declare function isTaskMethod(method: string): method is TaskMethod;
887
+ /**
888
+ * Whether this mount supports the tasks extension. Always false: the
889
+ * extension is a non-goal, and `server/discover` therefore omits the
890
+ * `capabilities.extensions` map entirely (an empty map would
891
+ * advertise the *ability* to carry extensions, which is a different
892
+ * claim than making none).
893
+ */
894
+ declare const TASKS_SUPPORTED: false;
895
+ /**
896
+ * The `capabilities` object `server/discover` reports. The extensions
897
+ * map is omitted rather than emitted empty — see TASKS_SUPPORTED.
898
+ */
899
+ declare function discoverCapabilities(): Record<string, unknown>;
900
+
901
+ /**
902
+ * @module mcp/bridge
903
+ * @package @hop-top/kit
904
+ *
905
+ * A commander adapter for the MCP surface's `McpBridge` interface.
906
+ *
907
+ * The surface itself never imports commander — that is what keeps
908
+ * the handler framework-free and lets adopters on another command
909
+ * framework implement `McpBridge` directly. This adapter is the
910
+ * convenience path for the commander trees the TS SDK's own `cli`
911
+ * module builds.
912
+ *
913
+ * The safety gate lives here, on the invoke path, so BOTH eras
914
+ * inherit one destructive ceiling from one place: there is no way to
915
+ * reach a leaf through the modern handler that the legacy handler
916
+ * would have blocked.
917
+ */
918
+
919
+ interface CommanderBridgeOptions {
920
+ /** Policy gate. Defaults to defaultPolicy() (block remote destructive). */
921
+ policy?: Policy;
922
+ /**
923
+ * Runs one leaf and returns its result. Adopters supply this
924
+ * because kit does not dictate how a command's output is captured.
925
+ */
926
+ run: (inv: Invocation, cmd: Command) => Promise<InvokeResult> | InvokeResult;
927
+ /** Per-leaf surface enablement override. */
928
+ enabled?: (leaf: Leaf) => Partial<Record<Surface, boolean>> | undefined;
929
+ }
930
+ /**
931
+ * Builds an `McpBridge` over a commander tree. Leaves are the
932
+ * commands with no subcommands, enumerated depth-first in
933
+ * declaration order, with the root's own name excluded from the path
934
+ * (so `root widget add` is the tool `widget.add`).
935
+ */
936
+ declare function commanderBridge(root: Command, opts: CommanderBridgeOptions): McpBridge;
937
+
938
+ /**
939
+ * @module mcp
940
+ * @package @hop-top/kit
941
+ *
942
+ * Dual-spec MCP surface: one mount serving both 2024-11-05 (legacy
943
+ * handshake) and 2026-07-28 (stateless per-request envelope), with
944
+ * per-request era detection.
945
+ *
946
+ * The protocol layer comes from the official v2 SDK packages
947
+ * (`@modelcontextprotocol/core` + `@modelcontextprotocol/server`).
948
+ * The v1 package `@modelcontextprotocol/sdk` is legacy-era only and
949
+ * cannot serve 2026-07-28 — it is deliberately not a dependency.
950
+ *
951
+ * Usage:
952
+ *
953
+ * ```ts
954
+ * import { createMcpHandler } from '@hop-top/kit/mcp';
955
+ *
956
+ * const handler = createMcpHandler(bridge);
957
+ * const res = await handler({ method: 'POST', headers, body });
958
+ * ```
959
+ *
960
+ * The handler is framework-free: binding it to node:http, hono,
961
+ * express, fastify, or a Worker is the adopter's job.
962
+ */
963
+
964
+ type index_CommanderBridgeOptions = CommanderBridgeOptions;
965
+ declare const index_DEFAULT_MCP_PATH: typeof DEFAULT_MCP_PATH;
966
+ declare const index_DEFAULT_MCP_SERVER_NAME: typeof DEFAULT_MCP_SERVER_NAME;
967
+ declare const index_DEFAULT_MCP_SERVER_VERSION: typeof DEFAULT_MCP_SERVER_VERSION;
968
+ type index_DestructiveBlockedError = DestructiveBlockedError;
969
+ declare const index_DestructiveBlockedError: typeof DestructiveBlockedError;
970
+ type index_ElicitationConfirmGate = ElicitationConfirmGate;
971
+ declare const index_ElicitationConfirmGate: typeof ElicitationConfirmGate;
972
+ type index_FlagSchema = FlagSchema;
973
+ declare const index_HEADER_MCP_METHOD: typeof HEADER_MCP_METHOD;
974
+ declare const index_HEADER_MCP_NAME: typeof HEADER_MCP_NAME;
975
+ declare const index_HEADER_MCP_PROTOCOL_VERSION: typeof HEADER_MCP_PROTOCOL_VERSION;
976
+ type index_Invocation = Invocation;
977
+ type index_InvocationMeta = InvocationMeta;
978
+ type index_InvokeResult = InvokeResult;
979
+ type index_JsonRpcErrorObject = JsonRpcErrorObject;
980
+ type index_JsonRpcRequest = JsonRpcRequest;
981
+ type index_Leaf = Leaf;
982
+ type index_LegacyMcpHandler = LegacyMcpHandler;
983
+ declare const index_LegacyMcpHandler: typeof LegacyMcpHandler;
984
+ declare const index_MCP_CONFIRM_KEY: typeof MCP_CONFIRM_KEY;
985
+ declare const index_MCP_CONFIRM_STATE_TTL_SECONDS: typeof MCP_CONFIRM_STATE_TTL_SECONDS;
986
+ declare const index_MCP_CONFIRM_STATE_VERSION: typeof MCP_CONFIRM_STATE_VERSION;
987
+ declare const index_MCP_ERR_HEADER_MISMATCH: typeof MCP_ERR_HEADER_MISMATCH;
988
+ declare const index_MCP_ERR_INTERNAL: typeof MCP_ERR_INTERNAL;
989
+ declare const index_MCP_ERR_INVALID_PARAMS: typeof MCP_ERR_INVALID_PARAMS;
990
+ declare const index_MCP_ERR_INVALID_REQUEST: typeof MCP_ERR_INVALID_REQUEST;
991
+ declare const index_MCP_ERR_METHOD_NOT_FOUND: typeof MCP_ERR_METHOD_NOT_FOUND;
992
+ declare const index_MCP_ERR_MISSING_CLIENT_CAPABILITY: typeof MCP_ERR_MISSING_CLIENT_CAPABILITY;
993
+ declare const index_MCP_ERR_PARSE: typeof MCP_ERR_PARSE;
994
+ declare const index_MCP_ERR_UNSUPPORTED_VERSION: typeof MCP_ERR_UNSUPPORTED_VERSION;
995
+ declare const index_MCP_SPEC_2024_11_05: typeof MCP_SPEC_2024_11_05;
996
+ declare const index_MCP_SPEC_2026_07_28: typeof MCP_SPEC_2026_07_28;
997
+ declare const index_META_KEY_CLIENT_CAPABILITIES: typeof META_KEY_CLIENT_CAPABILITIES;
998
+ declare const index_META_KEY_CLIENT_INFO: typeof META_KEY_CLIENT_INFO;
999
+ declare const index_META_KEY_PROTOCOL_VERSION: typeof META_KEY_PROTOCOL_VERSION;
1000
+ declare const index_META_KEY_SERVER_INFO: typeof META_KEY_SERVER_INFO;
1001
+ type index_McpBridge = McpBridge;
1002
+ type index_McpCacheScope = McpCacheScope;
1003
+ type index_McpConfirmBinding = McpConfirmBinding;
1004
+ type index_McpConfirmDecision = McpConfirmDecision;
1005
+ type index_McpConfirmRejection = McpConfirmRejection;
1006
+ type index_McpConfirmStateStatus = McpConfirmStateStatus;
1007
+ type index_McpDispatcher = McpDispatcher;
1008
+ declare const index_McpDispatcher: typeof McpDispatcher;
1009
+ type index_McpEra = McpEra;
1010
+ type index_McpHandler = McpHandler;
1011
+ type index_McpHttpRequest = McpHttpRequest;
1012
+ type index_McpHttpResponse = McpHttpResponse;
1013
+ type index_McpMountOptions = McpMountOptions;
1014
+ type index_McpSpecVersion = McpSpecVersion;
1015
+ type index_ModernMcpHandler = ModernMcpHandler;
1016
+ declare const index_ModernMcpHandler: typeof ModernMcpHandler;
1017
+ type index_ModernRequestMeta = ModernRequestMeta;
1018
+ type index_Policy = Policy;
1019
+ declare const index_RESULT_TYPE_COMPLETE: typeof RESULT_TYPE_COMPLETE;
1020
+ declare const index_RESULT_TYPE_INPUT_REQUIRED: typeof RESULT_TYPE_INPUT_REQUIRED;
1021
+ type index_RawJSON = RawJSON;
1022
+ declare const index_RawJSON: typeof RawJSON;
1023
+ type index_ResolvedMcpConfig = ResolvedMcpConfig;
1024
+ declare const index_SURFACE_CLI: typeof SURFACE_CLI;
1025
+ declare const index_SURFACE_LIB: typeof SURFACE_LIB;
1026
+ declare const index_SURFACE_MCP: typeof SURFACE_MCP;
1027
+ type index_SafetyClass = SafetyClass;
1028
+ type index_Surface = Surface;
1029
+ type index_SurfaceNotEnabledError = SurfaceNotEnabledError;
1030
+ declare const index_SurfaceNotEnabledError: typeof SurfaceNotEnabledError;
1031
+ declare const index_TASKS_EXTENSION: typeof TASKS_EXTENSION;
1032
+ declare const index_TASKS_SUPPORTED: typeof TASKS_SUPPORTED;
1033
+ declare const index_TASK_METHODS: typeof TASK_METHODS;
1034
+ type index_TaskMethod = TaskMethod;
1035
+ type index_UnknownCommandError = UnknownCommandError;
1036
+ declare const index_UnknownCommandError: typeof UnknownCommandError;
1037
+ declare const index_buildToolEnvelope: typeof buildToolEnvelope;
1038
+ declare const index_canonicalJSONStringify: typeof canonicalJSONStringify;
1039
+ declare const index_clientSupportsFormElicitation: typeof clientSupportsFormElicitation;
1040
+ declare const index_commanderBridge: typeof commanderBridge;
1041
+ declare const index_createMcpHandler: typeof createMcpHandler;
1042
+ declare const index_decodeMcpSentinel: typeof decodeMcpSentinel;
1043
+ declare const index_defaultPolicy: typeof defaultPolicy;
1044
+ declare const index_detectMcpEra: typeof detectMcpEra;
1045
+ declare const index_discoverCapabilities: typeof discoverCapabilities;
1046
+ declare const index_encodeEnvelope: typeof encodeEnvelope;
1047
+ declare const index_errorResultBlock: typeof errorResultBlock;
1048
+ declare const index_hasModernMetaMarker: typeof hasModernMetaMarker;
1049
+ declare const index_headerConfirmationGate: typeof headerConfirmationGate;
1050
+ declare const index_isTaskMethod: typeof isTaskMethod;
1051
+ declare const index_mcpConfirmArgsDigest: typeof mcpConfirmArgsDigest;
1052
+ declare const index_mcpConfirmPrincipal: typeof mcpConfirmPrincipal;
1053
+ declare const index_mcpMountConfig: typeof mcpMountConfig;
1054
+ declare const index_methodNotAllowedResponse: typeof methodNotAllowedResponse;
1055
+ declare const index_mintMcpConfirmState: typeof mintMcpConfirmState;
1056
+ declare const index_modernInvocationExtra: typeof modernInvocationExtra;
1057
+ declare const index_parseJsonRpcRequest: typeof parseJsonRpcRequest;
1058
+ declare const index_parseMcpConfirmRetry: typeof parseMcpConfirmRetry;
1059
+ declare const index_parseModernMeta: typeof parseModernMeta;
1060
+ declare const index_pathFromToolName: typeof pathFromToolName;
1061
+ declare const index_policyAllowed: typeof policyAllowed;
1062
+ declare const index_rawToolCallName: typeof rawToolCallName;
1063
+ declare const index_renderCallResult: typeof renderCallResult;
1064
+ declare const index_resolveMcpConfig: typeof resolveMcpConfig;
1065
+ declare const index_singleHeaderValue: typeof singleHeaderValue;
1066
+ declare const index_toolName: typeof toolName;
1067
+ declare const index_validModernRequestId: typeof validModernRequestId;
1068
+ declare const index_verifyMcpConfirmState: typeof verifyMcpConfirmState;
1069
+ declare namespace index {
1070
+ export { type index_CommanderBridgeOptions as CommanderBridgeOptions, index_DEFAULT_MCP_PATH as DEFAULT_MCP_PATH, index_DEFAULT_MCP_SERVER_NAME as DEFAULT_MCP_SERVER_NAME, index_DEFAULT_MCP_SERVER_VERSION as DEFAULT_MCP_SERVER_VERSION, index_DestructiveBlockedError as DestructiveBlockedError, index_ElicitationConfirmGate as ElicitationConfirmGate, type index_FlagSchema as FlagSchema, index_HEADER_MCP_METHOD as HEADER_MCP_METHOD, index_HEADER_MCP_NAME as HEADER_MCP_NAME, index_HEADER_MCP_PROTOCOL_VERSION as HEADER_MCP_PROTOCOL_VERSION, type index_Invocation as Invocation, type index_InvocationMeta as InvocationMeta, type index_InvokeResult as InvokeResult, type index_JsonRpcErrorObject as JsonRpcErrorObject, type index_JsonRpcRequest as JsonRpcRequest, type index_Leaf as Leaf, index_LegacyMcpHandler as LegacyMcpHandler, index_MCP_CONFIRM_KEY as MCP_CONFIRM_KEY, index_MCP_CONFIRM_STATE_TTL_SECONDS as MCP_CONFIRM_STATE_TTL_SECONDS, index_MCP_CONFIRM_STATE_VERSION as MCP_CONFIRM_STATE_VERSION, index_MCP_ERR_HEADER_MISMATCH as MCP_ERR_HEADER_MISMATCH, index_MCP_ERR_INTERNAL as MCP_ERR_INTERNAL, index_MCP_ERR_INVALID_PARAMS as MCP_ERR_INVALID_PARAMS, index_MCP_ERR_INVALID_REQUEST as MCP_ERR_INVALID_REQUEST, index_MCP_ERR_METHOD_NOT_FOUND as MCP_ERR_METHOD_NOT_FOUND, index_MCP_ERR_MISSING_CLIENT_CAPABILITY as MCP_ERR_MISSING_CLIENT_CAPABILITY, index_MCP_ERR_PARSE as MCP_ERR_PARSE, index_MCP_ERR_UNSUPPORTED_VERSION as MCP_ERR_UNSUPPORTED_VERSION, index_MCP_SPEC_2024_11_05 as MCP_SPEC_2024_11_05, index_MCP_SPEC_2026_07_28 as MCP_SPEC_2026_07_28, index_META_KEY_CLIENT_CAPABILITIES as META_KEY_CLIENT_CAPABILITIES, index_META_KEY_CLIENT_INFO as META_KEY_CLIENT_INFO, index_META_KEY_PROTOCOL_VERSION as META_KEY_PROTOCOL_VERSION, index_META_KEY_SERVER_INFO as META_KEY_SERVER_INFO, type index_McpBridge as McpBridge, type index_McpCacheScope as McpCacheScope, type index_McpConfirmBinding as McpConfirmBinding, type index_McpConfirmDecision as McpConfirmDecision, type index_McpConfirmRejection as McpConfirmRejection, type index_McpConfirmStateStatus as McpConfirmStateStatus, index_McpDispatcher as McpDispatcher, type index_McpEra as McpEra, type index_McpHandler as McpHandler, type index_McpHttpRequest as McpHttpRequest, type index_McpHttpResponse as McpHttpResponse, type index_McpMountOptions as McpMountOptions, type index_McpSpecVersion as McpSpecVersion, index_ModernMcpHandler as ModernMcpHandler, type index_ModernRequestMeta as ModernRequestMeta, type index_Policy as Policy, index_RESULT_TYPE_COMPLETE as RESULT_TYPE_COMPLETE, index_RESULT_TYPE_INPUT_REQUIRED as RESULT_TYPE_INPUT_REQUIRED, index_RawJSON as RawJSON, type index_ResolvedMcpConfig as ResolvedMcpConfig, index_SURFACE_CLI as SURFACE_CLI, index_SURFACE_LIB as SURFACE_LIB, index_SURFACE_MCP as SURFACE_MCP, type index_SafetyClass as SafetyClass, type index_Surface as Surface, index_SurfaceNotEnabledError as SurfaceNotEnabledError, index_TASKS_EXTENSION as TASKS_EXTENSION, index_TASKS_SUPPORTED as TASKS_SUPPORTED, index_TASK_METHODS as TASK_METHODS, type index_TaskMethod as TaskMethod, index_UnknownCommandError as UnknownCommandError, index_buildToolEnvelope as buildToolEnvelope, index_canonicalJSONStringify as canonicalJSONStringify, index_clientSupportsFormElicitation as clientSupportsFormElicitation, index_commanderBridge as commanderBridge, index_createMcpHandler as createMcpHandler, index_decodeMcpSentinel as decodeMcpSentinel, index_defaultPolicy as defaultPolicy, index_detectMcpEra as detectMcpEra, index_discoverCapabilities as discoverCapabilities, index_encodeEnvelope as encodeEnvelope, index_errorResultBlock as errorResultBlock, index_hasModernMetaMarker as hasModernMetaMarker, index_headerConfirmationGate as headerConfirmationGate, index_isTaskMethod as isTaskMethod, index_mcpConfirmArgsDigest as mcpConfirmArgsDigest, index_mcpConfirmPrincipal as mcpConfirmPrincipal, index_mcpMountConfig as mcpMountConfig, index_methodNotAllowedResponse as methodNotAllowedResponse, index_mintMcpConfirmState as mintMcpConfirmState, index_modernInvocationExtra as modernInvocationExtra, index_parseJsonRpcRequest as parseJsonRpcRequest, index_parseMcpConfirmRetry as parseMcpConfirmRetry, index_parseModernMeta as parseModernMeta, index_pathFromToolName as pathFromToolName, index_policyAllowed as policyAllowed, index_rawToolCallName as rawToolCallName, index_renderCallResult as renderCallResult, index_resolveMcpConfig as resolveMcpConfig, index_singleHeaderValue as singleHeaderValue, index_toolName as toolName, index_validModernRequestId as validModernRequestId, index_verifyMcpConfirmState as verifyMcpConfirmState };
1071
+ }
1072
+
1073
+ export { type ResolvedMcpConfig as $, type McpCacheScope as A, type McpConfirmBinding as B, type CommanderBridgeOptions as C, DEFAULT_MCP_PATH as D, ElicitationConfirmGate as E, type FlagSchema as F, type McpConfirmDecision as G, HEADER_MCP_METHOD as H, type Invocation as I, type JsonRpcErrorObject as J, type McpConfirmRejection as K, type Leaf as L, MCP_CONFIRM_KEY as M, type McpConfirmStateStatus as N, McpDispatcher as O, type McpEra as P, type McpHandler as Q, type McpHttpRequest as R, type McpHttpResponse as S, type McpMountOptions as T, type McpSpecVersion as U, ModernMcpHandler as V, type ModernRequestMeta as W, type Policy as X, RESULT_TYPE_COMPLETE as Y, RESULT_TYPE_INPUT_REQUIRED as Z, RawJSON as _, DEFAULT_MCP_SERVER_NAME as a, SURFACE_CLI as a0, SURFACE_LIB as a1, SURFACE_MCP as a2, type SafetyClass as a3, type Surface as a4, SurfaceNotEnabledError as a5, TASKS_EXTENSION as a6, TASKS_SUPPORTED as a7, TASK_METHODS as a8, type TaskMethod as a9, policyAllowed as aA, rawToolCallName as aB, renderCallResult as aC, resolveMcpConfig as aD, singleHeaderValue as aE, toolName as aF, validModernRequestId as aG, verifyMcpConfirmState as aH, UnknownCommandError as aa, buildToolEnvelope as ab, canonicalJSONStringify as ac, clientSupportsFormElicitation as ad, commanderBridge as ae, createMcpHandler as af, decodeMcpSentinel as ag, defaultPolicy as ah, detectMcpEra as ai, discoverCapabilities as aj, encodeEnvelope as ak, errorResultBlock as al, hasModernMetaMarker as am, headerConfirmationGate as an, index as ao, isTaskMethod as ap, mcpConfirmArgsDigest as aq, mcpConfirmPrincipal as ar, mcpMountConfig as as, methodNotAllowedResponse as at, mintMcpConfirmState as au, modernInvocationExtra as av, parseJsonRpcRequest as aw, parseMcpConfirmRetry as ax, parseModernMeta as ay, pathFromToolName as az, DEFAULT_MCP_SERVER_VERSION as b, DestructiveBlockedError as c, HEADER_MCP_NAME as d, HEADER_MCP_PROTOCOL_VERSION as e, type InvocationMeta as f, type InvokeResult as g, type JsonRpcRequest as h, LegacyMcpHandler as i, MCP_CONFIRM_STATE_TTL_SECONDS as j, MCP_CONFIRM_STATE_VERSION as k, MCP_ERR_HEADER_MISMATCH as l, MCP_ERR_INTERNAL as m, MCP_ERR_INVALID_PARAMS as n, MCP_ERR_INVALID_REQUEST as o, MCP_ERR_METHOD_NOT_FOUND as p, MCP_ERR_MISSING_CLIENT_CAPABILITY as q, MCP_ERR_PARSE as r, MCP_ERR_UNSUPPORTED_VERSION as s, MCP_SPEC_2024_11_05 as t, MCP_SPEC_2026_07_28 as u, META_KEY_CLIENT_CAPABILITIES as v, META_KEY_CLIENT_INFO as w, META_KEY_PROTOCOL_VERSION as x, META_KEY_SERVER_INFO as y, type McpBridge as z };