@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,138 @@
1
+ /**
2
+ * @module mcp
3
+ * @package @hop-top/kit
4
+ *
5
+ * Dual-spec MCP surface: one mount serving both 2024-11-05 (legacy
6
+ * handshake) and 2026-07-28 (stateless per-request envelope), with
7
+ * per-request era detection.
8
+ *
9
+ * The protocol layer comes from the official v2 SDK packages
10
+ * (`@modelcontextprotocol/core` + `@modelcontextprotocol/server`).
11
+ * The v1 package `@modelcontextprotocol/sdk` is legacy-era only and
12
+ * cannot serve 2026-07-28 — it is deliberately not a dependency.
13
+ *
14
+ * Usage:
15
+ *
16
+ * ```ts
17
+ * import { createMcpHandler } from '@hop-top/kit/mcp';
18
+ *
19
+ * const handler = createMcpHandler(bridge);
20
+ * const res = await handler({ method: 'POST', headers, body });
21
+ * ```
22
+ *
23
+ * The handler is framework-free: binding it to node:http, hono,
24
+ * express, fastify, or a Worker is the adopter's job.
25
+ */
26
+
27
+ export {
28
+ createMcpHandler,
29
+ detectMcpEra,
30
+ hasModernMetaMarker,
31
+ mcpMountConfig,
32
+ McpDispatcher,
33
+ methodNotAllowedResponse,
34
+ parseJsonRpcRequest,
35
+ type JsonRpcRequest,
36
+ type McpEra,
37
+ type McpHandler,
38
+ type McpHttpRequest,
39
+ type McpHttpResponse,
40
+ } from './dispatch.js';
41
+
42
+ export { LegacyMcpHandler } from './legacy.js';
43
+
44
+ export {
45
+ decodeMcpSentinel,
46
+ ModernMcpHandler,
47
+ modernInvocationExtra,
48
+ parseModernMeta,
49
+ rawToolCallName,
50
+ singleHeaderValue,
51
+ validModernRequestId,
52
+ type ModernRequestMeta,
53
+ } from './modern.js';
54
+
55
+ export {
56
+ clientSupportsFormElicitation,
57
+ ElicitationConfirmGate,
58
+ headerConfirmationGate,
59
+ MCP_CONFIRM_KEY,
60
+ MCP_CONFIRM_STATE_TTL_SECONDS,
61
+ MCP_CONFIRM_STATE_VERSION,
62
+ mcpConfirmArgsDigest,
63
+ mcpConfirmPrincipal,
64
+ mintMcpConfirmState,
65
+ parseMcpConfirmRetry,
66
+ verifyMcpConfirmState,
67
+ type McpConfirmBinding,
68
+ type McpConfirmDecision,
69
+ type McpConfirmRejection,
70
+ type McpConfirmStateStatus,
71
+ } from './modern-confirm.js';
72
+
73
+ export {
74
+ discoverCapabilities,
75
+ isTaskMethod,
76
+ TASK_METHODS,
77
+ TASKS_EXTENSION,
78
+ TASKS_SUPPORTED,
79
+ type TaskMethod,
80
+ } from './tasks.js';
81
+
82
+ export {
83
+ buildToolEnvelope,
84
+ canonicalJSONStringify,
85
+ DEFAULT_MCP_PATH,
86
+ DEFAULT_MCP_SERVER_NAME,
87
+ DEFAULT_MCP_SERVER_VERSION,
88
+ defaultPolicy,
89
+ DestructiveBlockedError,
90
+ encodeEnvelope,
91
+ errorResultBlock,
92
+ HEADER_MCP_METHOD,
93
+ HEADER_MCP_NAME,
94
+ HEADER_MCP_PROTOCOL_VERSION,
95
+ MCP_ERR_HEADER_MISMATCH,
96
+ MCP_ERR_INTERNAL,
97
+ MCP_ERR_INVALID_PARAMS,
98
+ MCP_ERR_INVALID_REQUEST,
99
+ MCP_ERR_METHOD_NOT_FOUND,
100
+ MCP_ERR_MISSING_CLIENT_CAPABILITY,
101
+ MCP_ERR_PARSE,
102
+ MCP_ERR_UNSUPPORTED_VERSION,
103
+ MCP_SPEC_2024_11_05,
104
+ MCP_SPEC_2026_07_28,
105
+ META_KEY_CLIENT_CAPABILITIES,
106
+ META_KEY_CLIENT_INFO,
107
+ META_KEY_PROTOCOL_VERSION,
108
+ META_KEY_SERVER_INFO,
109
+ pathFromToolName,
110
+ policyAllowed,
111
+ RawJSON,
112
+ renderCallResult,
113
+ resolveMcpConfig,
114
+ RESULT_TYPE_COMPLETE,
115
+ RESULT_TYPE_INPUT_REQUIRED,
116
+ SURFACE_CLI,
117
+ SURFACE_LIB,
118
+ SURFACE_MCP,
119
+ SurfaceNotEnabledError,
120
+ toolName,
121
+ UnknownCommandError,
122
+ type FlagSchema,
123
+ type Invocation,
124
+ type InvocationMeta,
125
+ type InvokeResult,
126
+ type JsonRpcErrorObject,
127
+ type Leaf,
128
+ type McpBridge,
129
+ type McpCacheScope,
130
+ type McpMountOptions,
131
+ type McpSpecVersion,
132
+ type Policy,
133
+ type ResolvedMcpConfig,
134
+ type SafetyClass,
135
+ type Surface,
136
+ } from './types.js';
137
+
138
+ export { commanderBridge, type CommanderBridgeOptions } from './bridge.js';
@@ -0,0 +1,314 @@
1
+ /**
2
+ * @module mcp/legacy
3
+ * @package @hop-top/kit
4
+ *
5
+ * The 2024-11-05 MCP handler: `initialize`, `tools/list`,
6
+ * `tools/call`, plain JSON-RPC over one POST path, no sessions, no
7
+ * SSE.
8
+ *
9
+ * This module is byte-for-byte frozen. ADR 0042's hard invariant is
10
+ * "2024-11-05 behavior is preserved byte-for-byte; additive only; no
11
+ * deprecation", and the three-way module split (legacy / modern /
12
+ * dispatch) exists precisely so a reviewer can confirm a modern-era
13
+ * change did not touch this file. Modern-era behavior belongs in
14
+ * modern.ts — never here.
15
+ */
16
+
17
+ import {
18
+ errorResultBlock,
19
+ encodeEnvelope,
20
+ buildToolEnvelope,
21
+ MCP_ERR_INVALID_PARAMS,
22
+ MCP_ERR_INVALID_REQUEST,
23
+ MCP_ERR_METHOD_NOT_FOUND,
24
+ MCP_ERR_PARSE,
25
+ MCP_SPEC_2024_11_05,
26
+ pathFromToolName,
27
+ renderCallResult,
28
+ SURFACE_MCP,
29
+ type JsonRpcErrorObject,
30
+ type Leaf,
31
+ type McpBridge,
32
+ type RawJSON,
33
+ type ResolvedMcpConfig,
34
+ } from './types.js';
35
+ import {
36
+ DestructiveBlockedError,
37
+ SurfaceNotEnabledError,
38
+ UnknownCommandError,
39
+ } from './types.js';
40
+ import type { JsonRpcRequest, McpHttpRequest, McpHttpResponse } from './dispatch.js';
41
+ import { jsonResponse } from './dispatch.js';
42
+
43
+ /** Writes a successful JSON-RPC envelope. */
44
+ export function writeResult(
45
+ id: RawJSON | undefined,
46
+ result: unknown,
47
+ status: number,
48
+ ): McpHttpResponse {
49
+ return jsonResponse(status, encodeEnvelope({ id, result }));
50
+ }
51
+
52
+ /** Writes a JSON-RPC error envelope. */
53
+ export function writeError(
54
+ id: RawJSON | undefined,
55
+ error: JsonRpcErrorObject,
56
+ status: number,
57
+ ): McpHttpResponse {
58
+ return jsonResponse(status, encodeEnvelope({ id, error }));
59
+ }
60
+
61
+ /**
62
+ * Renders the -32700 parse error exactly as Go does, including the
63
+ * encoding/json message text the fixtures pin. Go reports the offset
64
+ * of the first offending byte in the phrase "invalid character %q
65
+ * looking for beginning of object key string" when an object key is
66
+ * expected; other positions produce different wording. Only the
67
+ * shapes this surface can actually receive are modelled.
68
+ */
69
+ export function parseErrorResponse(body: string): McpHttpResponse {
70
+ return writeError(
71
+ undefined,
72
+ { code: MCP_ERR_PARSE, message: `parse error: ${goJSONParseMessage(body)}` },
73
+ 400,
74
+ );
75
+ }
76
+
77
+ /**
78
+ * Reproduces Go's encoding/json syntax-error text for a body this
79
+ * surface failed to parse. Go's decoder reports the first character
80
+ * that cannot begin the token it expects; for a top-level object
81
+ * whose first key is unquoted (the fixture case `{not json`) that is
82
+ * "invalid character 'n' looking for beginning of object key string".
83
+ */
84
+ function goJSONParseMessage(body: string): string {
85
+ const trimmed = body.replace(/^[\s]*/, '');
86
+ if (trimmed.startsWith('{')) {
87
+ // Scan past the opening brace and any whitespace to the first
88
+ // character of what must be a quoted object key.
89
+ const rest = trimmed.slice(1).replace(/^[\s]*/, '');
90
+ const ch = rest[0];
91
+ if (ch !== undefined && ch !== '"' && ch !== '}') {
92
+ return `invalid character '${ch}' looking for beginning of object key string`;
93
+ }
94
+ }
95
+ const ch = trimmed[0];
96
+ if (ch !== undefined) {
97
+ return `invalid character '${ch}' looking for beginning of value`;
98
+ }
99
+ return 'unexpected end of JSON input';
100
+ }
101
+
102
+ /**
103
+ * The 2024-11-05 handler. Stateless across requests; holds only
104
+ * immutable mount configuration and the bridge.
105
+ */
106
+ export class LegacyMcpHandler {
107
+ constructor(
108
+ private readonly bridge: McpBridge,
109
+ private readonly cfg: ResolvedMcpConfig,
110
+ ) {}
111
+
112
+ /**
113
+ * Routes one already-parsed JSON-RPC request by method. An unknown
114
+ * method returns -32601 at HTTP 200 — today's behavior, preserved
115
+ * deliberately (the modern handler uses 404 instead; the asymmetry
116
+ * is required by byte-for-byte preservation).
117
+ */
118
+ async serve(
119
+ req: McpHttpRequest,
120
+ rpc: JsonRpcRequest,
121
+ ): Promise<McpHttpResponse> {
122
+ if (rpc.jsonrpc !== undefined && rpc.jsonrpc !== '2.0') {
123
+ return writeError(
124
+ rpc.id,
125
+ { code: MCP_ERR_INVALID_REQUEST, message: 'invalid jsonrpc version' },
126
+ 400,
127
+ );
128
+ }
129
+
130
+ switch (rpc.method) {
131
+ case 'initialize':
132
+ return this.handleInitialize(rpc);
133
+ case 'tools/list':
134
+ return this.handleToolsList(rpc);
135
+ case 'tools/call':
136
+ return this.handleToolsCall(req, rpc);
137
+ default:
138
+ return writeError(
139
+ rpc.id,
140
+ {
141
+ code: MCP_ERR_METHOD_NOT_FOUND,
142
+ message: `method not found: ${rpc.method}`,
143
+ },
144
+ 200,
145
+ );
146
+ }
147
+ }
148
+
149
+ /** The minimal initialize response: version, capabilities, identity. */
150
+ private handleInitialize(rpc: JsonRpcRequest): McpHttpResponse {
151
+ return writeResult(
152
+ rpc.id,
153
+ {
154
+ protocolVersion: MCP_SPEC_2024_11_05,
155
+ capabilities: { tools: {} },
156
+ serverInfo: {
157
+ name: this.cfg.serverName,
158
+ version: this.cfg.serverVersion,
159
+ },
160
+ },
161
+ 200,
162
+ );
163
+ }
164
+
165
+ /** One tool envelope per leaf exposed on the MCP surface. */
166
+ private handleToolsList(rpc: JsonRpcRequest): McpHttpResponse {
167
+ return writeResult(rpc.id, { tools: this.exposedTools() }, 200);
168
+ }
169
+
170
+ private exposedTools(): Array<Record<string, unknown>> {
171
+ const tools: Array<Record<string, unknown>> = [];
172
+ for (const leaf of this.bridge.leaves()) {
173
+ if (!isExposed(leaf)) continue;
174
+ tools.push(buildToolEnvelope(leaf));
175
+ }
176
+ return tools;
177
+ }
178
+
179
+ /**
180
+ * Resolves the leaf, applies the pre-flight auth + confirmation
181
+ * gates, and dispatches through the bridge. Unknown / not-enabled
182
+ * tools are JSON-RPC errors; every other failure (bridge errors,
183
+ * destructive blocks, non-zero exit codes) is an isError result.
184
+ */
185
+ private async handleToolsCall(
186
+ req: McpHttpRequest,
187
+ rpc: JsonRpcRequest,
188
+ ): Promise<McpHttpResponse> {
189
+ const params = (rpc.params ?? {}) as {
190
+ name?: unknown;
191
+ arguments?: Record<string, unknown>;
192
+ };
193
+ const name = typeof params.name === 'string' ? params.name : '';
194
+ if (name === '') {
195
+ return writeError(
196
+ rpc.id,
197
+ { code: MCP_ERR_INVALID_PARAMS, message: 'missing tool name' },
198
+ 200,
199
+ );
200
+ }
201
+
202
+ const leaf = resolveLeaf(this.bridge, name);
203
+ if (leaf === undefined || !isExposed(leaf)) {
204
+ return writeError(
205
+ rpc.id,
206
+ { code: MCP_ERR_INVALID_PARAMS, message: `unknown tool: ${name}` },
207
+ 200,
208
+ );
209
+ }
210
+
211
+ // Auth + confirmation gating, mirrored onto the result envelope so
212
+ // MCP-aware clients see isError while HTTP-only clients see the
213
+ // matching status code.
214
+ if (leaf.class?.authRequired && !headerValue(req, 'authorization')) {
215
+ return writeResult(
216
+ rpc.id,
217
+ errorResultBlock('authentication required'),
218
+ 401,
219
+ );
220
+ }
221
+ if (
222
+ leaf.class?.requiresConfirmation &&
223
+ !headerValue(req, 'x-confirm-token')
224
+ ) {
225
+ return writeResult(
226
+ rpc.id,
227
+ errorResultBlock('confirmation required'),
228
+ 428,
229
+ );
230
+ }
231
+
232
+ try {
233
+ const res = await this.bridge.invoke({
234
+ path: [...leaf.path],
235
+ flags: params.arguments,
236
+ meta: { surface: SURFACE_MCP, requestedAt: new Date() },
237
+ });
238
+ return writeResult(rpc.id, renderCallResult(res), 200);
239
+ } catch (err) {
240
+ if (
241
+ err instanceof UnknownCommandError ||
242
+ err instanceof SurfaceNotEnabledError
243
+ ) {
244
+ return writeError(
245
+ rpc.id,
246
+ { code: MCP_ERR_INVALID_PARAMS, message: `unknown tool: ${name}` },
247
+ 200,
248
+ );
249
+ }
250
+ // DestructiveBlockedError and every other invoke failure render
251
+ // as an isError result at HTTP 200.
252
+ return writeResult(
253
+ rpc.id,
254
+ errorResultBlock(errorMessage(err)),
255
+ 200,
256
+ );
257
+ }
258
+ }
259
+ }
260
+
261
+ /** Reports whether a leaf is exposed on the MCP surface. */
262
+ export function isExposed(leaf: Leaf): boolean {
263
+ // Absent `enabled` means the bridge applies its policy defaults,
264
+ // which include the MCP surface; an explicit false hides the leaf.
265
+ return leaf.enabled?.[SURFACE_MCP] !== false;
266
+ }
267
+
268
+ /** Resolves a dotted tool name to a leaf, or undefined. */
269
+ export function resolveLeaf(
270
+ bridge: McpBridge,
271
+ name: string,
272
+ ): Leaf | undefined {
273
+ const path = pathFromToolName(name);
274
+ if (path.length === 0) return undefined;
275
+ return bridge
276
+ .leaves()
277
+ .find(
278
+ (l) =>
279
+ l.path.length === path.length &&
280
+ l.path.every((seg, i) => seg === path[i]),
281
+ );
282
+ }
283
+
284
+ /** Case-insensitive single header lookup. */
285
+ export function headerValue(
286
+ req: McpHttpRequest,
287
+ name: string,
288
+ ): string | undefined {
289
+ const vals = headerValues(req, name);
290
+ return vals.length > 0 ? vals[0] : undefined;
291
+ }
292
+
293
+ /** All values for a header name, matched case-insensitively. */
294
+ export function headerValues(
295
+ req: McpHttpRequest,
296
+ name: string,
297
+ ): string[] {
298
+ const want = name.toLowerCase();
299
+ const out: string[] = [];
300
+ for (const [k, v] of Object.entries(req.headers ?? {})) {
301
+ if (k.toLowerCase() !== want) continue;
302
+ if (Array.isArray(v)) out.push(...v);
303
+ else if (v !== undefined) out.push(v);
304
+ }
305
+ return out;
306
+ }
307
+
308
+ /** Extracts an error message the way Go's err.Error() renders it. */
309
+ export function errorMessage(err: unknown): string {
310
+ if (err instanceof Error) return err.message;
311
+ return String(err);
312
+ }
313
+
314
+ export { DestructiveBlockedError };