@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.3
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.
- package/CHANGELOG.md +107 -0
- package/README.md +333 -9
- package/dist/aim-CTp-kJW2.d.ts +139 -0
- package/dist/aim.d.ts +1 -116
- package/dist/alias-dhhr08Ei.d.ts +88 -0
- package/dist/alias.d.ts +2 -73
- package/dist/api-miiso81x.d.ts +77 -0
- package/dist/api.d.ts +1 -62
- package/dist/auth-2-jfgiHn.d.ts +34 -0
- package/dist/auth.d.ts +1 -26
- package/dist/cli-DLygZLi9.d.ts +450 -0
- package/dist/cli.d.ts +6 -309
- package/dist/cli.js +192 -63
- package/dist/config-BUY7_W2n.d.ts +103 -0
- package/dist/config.d.ts +1 -97
- package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
- package/dist/errcorrect.d.ts +1 -37
- package/dist/error-DISJKeDu.d.ts +144 -0
- package/dist/id/index.d.ts +2 -83
- package/dist/index-Bc5c7Ty5.d.ts +328 -0
- package/dist/index-C3Zw4wDJ.d.ts +359 -0
- package/dist/index-MLrRDvEG.d.ts +1073 -0
- package/dist/index-QSffbLnj.d.ts +94 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +6794 -0
- package/dist/llm-B5XUWH8T.d.ts +231 -0
- package/dist/llm.d.ts +1 -188
- package/dist/mcp/index.d.ts +2 -0
- package/dist/mcp/index.js +1453 -0
- package/dist/netpolicy-asvCfwi8.d.ts +138 -0
- package/dist/netpolicy.d.ts +1 -0
- package/dist/netpolicy.js +118 -0
- package/dist/output-4aXs91GY.d.ts +396 -0
- package/dist/output.d.ts +3 -213
- package/dist/output.js +567 -43
- package/dist/progress-CAzyxeWl.d.ts +38 -0
- package/dist/progress.d.ts +1 -30
- package/dist/provenance-SMFHm5gx.d.ts +30 -0
- package/dist/provenance.d.ts +1 -24
- package/dist/routellm-PGSt2D1y.d.ts +75 -0
- package/dist/routellm.d.ts +2 -64
- package/dist/rpc-D5xLEf8V.d.ts +32 -0
- package/dist/rpc.d.ts +2 -25
- package/dist/safety-CUaYEjZc.d.ts +30 -0
- package/dist/safety.d.ts +1 -24
- package/dist/scope-BrhYB4ij.d.ts +141 -0
- package/dist/scope.d.ts +1 -121
- package/dist/serve-DE-jscpb.d.ts +646 -0
- package/dist/serve.d.ts +3 -0
- package/dist/serve.js +1019 -0
- package/dist/stream-CrjeCp0M.d.ts +44 -0
- package/dist/stream.d.ts +1 -35
- package/dist/telemetry/index.d.ts +1 -315
- package/dist/telemetry/index.js +12 -1
- package/dist/tui/index.d.ts +5 -298
- package/dist/tui/index.js +3 -10
- package/dist/upgrade-p_zh3pvV.d.ts +102 -0
- package/dist/upgrade.d.ts +1 -95
- package/dist/xdg-DB7Shoib.d.ts +179 -0
- package/dist/xdg.d.ts +1 -169
- package/package.json +26 -3
- package/src/cli.offline.test.ts +93 -0
- package/src/cli.parity.test.ts +192 -0
- package/src/cli.ts +112 -12
- package/src/index.test.ts +58 -0
- package/src/index.ts +37 -0
- package/src/log.parity.test.ts +105 -0
- package/src/log.ts +64 -13
- package/src/mcp/bridge.test.ts +150 -0
- package/src/mcp/bridge.ts +246 -0
- package/src/mcp/conformance.test.ts +336 -0
- package/src/mcp/dispatch.ts +313 -0
- package/src/mcp/index.ts +138 -0
- package/src/mcp/legacy.ts +314 -0
- package/src/mcp/mcp.test.ts +697 -0
- package/src/mcp/modern-confirm.test.ts +520 -0
- package/src/mcp/modern-confirm.ts +452 -0
- package/src/mcp/modern.ts +723 -0
- package/src/mcp/tasks.ts +82 -0
- package/src/mcp/testtree.ts +250 -0
- package/src/mcp/types.ts +504 -0
- package/src/netpolicy.test.ts +202 -0
- package/src/netpolicy.ts +231 -0
- package/src/output/dispatch.ts +10 -2
- package/src/output/error.ts +316 -0
- package/src/output/formatter.ts +29 -5
- package/src/output/formatters/csv.ts +48 -12
- package/src/output/formatters/json.ts +4 -25
- package/src/output/formatters/project.ts +34 -0
- package/src/output/formatters/table.ts +8 -6
- package/src/output/formatters/text.ts +7 -3
- package/src/output/formatters/yaml.ts +5 -22
- package/src/output/projection.test.ts +298 -0
- package/src/output/projection.ts +33 -59
- package/src/output/template.ts +11 -21
- package/src/output.surface.test.ts +41 -0
- package/src/output.ts +41 -3
- package/src/serve.test.ts +1257 -0
- package/src/serve.ts +1665 -0
- package/src/telemetry/client.test.ts +31 -0
- package/src/telemetry/client.ts +7 -1
- package/src/telemetry/offline.test.ts +64 -0
- package/src/tui/parity.test.ts +120 -31
- package/src/tui/parity.ts +58 -7
- package/test/output/csv.test.ts +164 -0
- package/test/output/error.test.ts +246 -0
- package/src/tui/parity.json +0 -74
package/src/mcp/types.ts
ADDED
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module mcp/types
|
|
3
|
+
* @package @hop-top/kit
|
|
4
|
+
*
|
|
5
|
+
* Shared vocabulary for the dual-spec MCP surface: the bridge
|
|
6
|
+
* abstraction the surface invokes through, the safety gate, the
|
|
7
|
+
* mount options, and the canonical JSON encoder that makes wire
|
|
8
|
+
* output byte-identical to the Go reference.
|
|
9
|
+
*
|
|
10
|
+
* Protocol constants are taken from the official v2 SDK
|
|
11
|
+
* (@modelcontextprotocol/server) rather than re-declared here, so a
|
|
12
|
+
* reserved key or spec error code can never drift from upstream. The
|
|
13
|
+
* v1 package (@modelcontextprotocol/sdk) is legacy-era only and
|
|
14
|
+
* cannot serve 2026-07-28 — it is deliberately not a dependency.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import {
|
|
18
|
+
CLIENT_CAPABILITIES_META_KEY,
|
|
19
|
+
CLIENT_INFO_META_KEY,
|
|
20
|
+
PROTOCOL_VERSION_META_KEY,
|
|
21
|
+
ProtocolErrorCode,
|
|
22
|
+
SERVER_INFO_META_KEY,
|
|
23
|
+
} from '@modelcontextprotocol/server';
|
|
24
|
+
|
|
25
|
+
// --- protocol constants -------------------------------------------------
|
|
26
|
+
|
|
27
|
+
/** Reserved `params._meta` / result `_meta` keys (from the v2 SDK). */
|
|
28
|
+
export const META_KEY_PROTOCOL_VERSION = PROTOCOL_VERSION_META_KEY;
|
|
29
|
+
export const META_KEY_CLIENT_INFO = CLIENT_INFO_META_KEY;
|
|
30
|
+
export const META_KEY_CLIENT_CAPABILITIES = CLIENT_CAPABILITIES_META_KEY;
|
|
31
|
+
export const META_KEY_SERVER_INFO = SERVER_INFO_META_KEY;
|
|
32
|
+
|
|
33
|
+
/** Header names carrying the modern routing signals. */
|
|
34
|
+
export const HEADER_MCP_PROTOCOL_VERSION = 'MCP-Protocol-Version';
|
|
35
|
+
export const HEADER_MCP_METHOD = 'Mcp-Method';
|
|
36
|
+
export const HEADER_MCP_NAME = 'Mcp-Name';
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* JSON-RPC error codes. The base codes and the two spec-reserved
|
|
40
|
+
* 2026-07-28 additions come from the SDK's ProtocolErrorCode;
|
|
41
|
+
* HeaderMismatch (-32020) is spec-reserved but absent from the SDK
|
|
42
|
+
* enum, so it is pinned here.
|
|
43
|
+
*/
|
|
44
|
+
export const MCP_ERR_PARSE = ProtocolErrorCode.ParseError;
|
|
45
|
+
export const MCP_ERR_INVALID_REQUEST = ProtocolErrorCode.InvalidRequest;
|
|
46
|
+
export const MCP_ERR_METHOD_NOT_FOUND = ProtocolErrorCode.MethodNotFound;
|
|
47
|
+
export const MCP_ERR_INVALID_PARAMS = ProtocolErrorCode.InvalidParams;
|
|
48
|
+
export const MCP_ERR_INTERNAL = ProtocolErrorCode.InternalError;
|
|
49
|
+
export const MCP_ERR_HEADER_MISMATCH = -32020;
|
|
50
|
+
export const MCP_ERR_MISSING_CLIENT_CAPABILITY =
|
|
51
|
+
ProtocolErrorCode.MissingRequiredClientCapability;
|
|
52
|
+
export const MCP_ERR_UNSUPPORTED_VERSION =
|
|
53
|
+
ProtocolErrorCode.UnsupportedProtocolVersion;
|
|
54
|
+
|
|
55
|
+
/** The two protocol revisions this surface serves. */
|
|
56
|
+
export const MCP_SPEC_2024_11_05 = '2024-11-05';
|
|
57
|
+
export const MCP_SPEC_2026_07_28 = '2026-07-28';
|
|
58
|
+
|
|
59
|
+
export type McpSpecVersion =
|
|
60
|
+
| typeof MCP_SPEC_2024_11_05
|
|
61
|
+
| typeof MCP_SPEC_2026_07_28;
|
|
62
|
+
|
|
63
|
+
/** resultType discriminator values on modern result envelopes. */
|
|
64
|
+
export const RESULT_TYPE_COMPLETE = 'complete';
|
|
65
|
+
export const RESULT_TYPE_INPUT_REQUIRED = 'input_required';
|
|
66
|
+
|
|
67
|
+
/** cacheScope values on modern cacheable list results. */
|
|
68
|
+
export type McpCacheScope = 'public' | 'private';
|
|
69
|
+
|
|
70
|
+
/** Default server identity, matching Go's cmdsurface defaults. */
|
|
71
|
+
export const DEFAULT_MCP_SERVER_NAME = 'cmdsurface';
|
|
72
|
+
export const DEFAULT_MCP_SERVER_VERSION = '0.0.0';
|
|
73
|
+
export const DEFAULT_MCP_PATH = '/mcp';
|
|
74
|
+
|
|
75
|
+
// --- safety gate --------------------------------------------------------
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Surfaces a leaf may be invoked through. Mirrors Go's Surface type;
|
|
79
|
+
* both MCP spec revisions share the single "mcp" surface — one
|
|
80
|
+
* mount, one exposure decision.
|
|
81
|
+
*/
|
|
82
|
+
export type Surface = 'cli' | 'lib' | 'mcp' | 'rest' | 'rpc' | 'ws' | 'bus';
|
|
83
|
+
|
|
84
|
+
export const SURFACE_CLI: Surface = 'cli';
|
|
85
|
+
export const SURFACE_LIB: Surface = 'lib';
|
|
86
|
+
export const SURFACE_MCP: Surface = 'mcp';
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* SafetyClass is the bridge's read of a leaf's safety annotations —
|
|
90
|
+
* the input the policy gate consults. Mirrors Go's SafetyClass.
|
|
91
|
+
*/
|
|
92
|
+
export interface SafetyClass {
|
|
93
|
+
/** Set for the destructive kit/side-effect tiers. */
|
|
94
|
+
destructive?: boolean;
|
|
95
|
+
/** Set when kit/auth-required is "true". */
|
|
96
|
+
authRequired?: boolean;
|
|
97
|
+
/** Set when kit/requires-confirmation is "true". */
|
|
98
|
+
requiresConfirmation?: boolean;
|
|
99
|
+
permissions?: string[];
|
|
100
|
+
exitCodes?: string[];
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Policy gates which Surface may invoke a leaf of a given
|
|
105
|
+
* SafetyClass. Ported from Go's cmdsurface Policy — NOT from
|
|
106
|
+
* src/safety.ts, which implements the unrelated Factor 10 CLI
|
|
107
|
+
* `--force` guard and has no bearing on surface exposure.
|
|
108
|
+
*/
|
|
109
|
+
export interface Policy {
|
|
110
|
+
/**
|
|
111
|
+
* Surfaces on which destructive leaves MAY be invoked. CLI and Lib
|
|
112
|
+
* are always allowed regardless. Empty = block all remote
|
|
113
|
+
* destructive invocation (the default).
|
|
114
|
+
*/
|
|
115
|
+
allowDestructiveOn?: Surface[];
|
|
116
|
+
/** Surfaces a leaf is exposed on when its config omits `enabled`. */
|
|
117
|
+
defaultEnabled?: Surface[];
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* The conservative default policy: no remote surface may invoke a
|
|
122
|
+
* destructive command; default enablement is CLI + Lib + MCP.
|
|
123
|
+
* `allowDestructiveOn` is deliberately empty — empty means block-all,
|
|
124
|
+
* not allow-all.
|
|
125
|
+
*/
|
|
126
|
+
export function defaultPolicy(): Policy {
|
|
127
|
+
return {
|
|
128
|
+
allowDestructiveOn: [],
|
|
129
|
+
defaultEnabled: [SURFACE_CLI, SURFACE_LIB, SURFACE_MCP],
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Reports whether `cls` may be invoked via surface `s` under `p`.
|
|
135
|
+
*
|
|
136
|
+
* 1. cli and lib are always allowed (local runtime).
|
|
137
|
+
* 2. Non-destructive commands are allowed on every other surface.
|
|
138
|
+
* 3. Destructive commands are allowed only when `s` is listed in
|
|
139
|
+
* `allowDestructiveOn`.
|
|
140
|
+
*
|
|
141
|
+
* Surface enablement (per-leaf opt-in) is gated separately; this
|
|
142
|
+
* enforces only the destructive ceiling.
|
|
143
|
+
*/
|
|
144
|
+
export function policyAllowed(
|
|
145
|
+
p: Policy,
|
|
146
|
+
cls: SafetyClass,
|
|
147
|
+
s: Surface,
|
|
148
|
+
): boolean {
|
|
149
|
+
if (s === SURFACE_CLI || s === SURFACE_LIB) return true;
|
|
150
|
+
if (!cls.destructive) return true;
|
|
151
|
+
return (p.allowDestructiveOn ?? []).includes(s);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Error a bridge raises when the policy gate blocks a leaf. */
|
|
155
|
+
export class DestructiveBlockedError extends Error {
|
|
156
|
+
constructor(pathLabel: string, surface: Surface) {
|
|
157
|
+
super(
|
|
158
|
+
`cmdsurface: destructive command blocked on this surface: ${pathLabel} on ${surface}`,
|
|
159
|
+
);
|
|
160
|
+
this.name = 'DestructiveBlockedError';
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Error a bridge raises when a leaf path resolves to nothing. */
|
|
165
|
+
export class UnknownCommandError extends Error {
|
|
166
|
+
constructor(message = 'unknown command') {
|
|
167
|
+
super(message);
|
|
168
|
+
this.name = 'UnknownCommandError';
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Error a bridge raises when a leaf is not exposed on the surface. */
|
|
173
|
+
export class SurfaceNotEnabledError extends Error {
|
|
174
|
+
constructor(message = 'surface not enabled') {
|
|
175
|
+
super(message);
|
|
176
|
+
this.name = 'SurfaceNotEnabledError';
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// --- bridge -------------------------------------------------------------
|
|
181
|
+
|
|
182
|
+
/** A JSON Schema property object describing one flag. */
|
|
183
|
+
export interface FlagSchema {
|
|
184
|
+
type: string;
|
|
185
|
+
description: string;
|
|
186
|
+
items?: { type: string };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* One invocable leaf command exposed as an MCP tool. `path` is the
|
|
191
|
+
* leaf's command path; the MCP tool name is the dotted join.
|
|
192
|
+
*/
|
|
193
|
+
export interface Leaf {
|
|
194
|
+
/** Command path, e.g. ["widget","add"] → tool "widget.add". */
|
|
195
|
+
path: string[];
|
|
196
|
+
/** Short description, used as the tool description. */
|
|
197
|
+
description: string;
|
|
198
|
+
/** JSON Schema properties derived from the leaf's flags. */
|
|
199
|
+
properties: Record<string, FlagSchema>;
|
|
200
|
+
/** Names of required flags, in declaration order. */
|
|
201
|
+
required?: string[];
|
|
202
|
+
/** Safety annotations consulted by the policy gate. */
|
|
203
|
+
class?: SafetyClass;
|
|
204
|
+
/** Surfaces this leaf is exposed on. */
|
|
205
|
+
enabled?: Partial<Record<Surface, boolean>>;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Metadata attached to one invocation, forwarded to audit sinks. */
|
|
209
|
+
export interface InvocationMeta {
|
|
210
|
+
surface: Surface;
|
|
211
|
+
requestedAt: Date;
|
|
212
|
+
/** Free-form audit bag; the modern path records spec + client info. */
|
|
213
|
+
extra?: Record<string, string>;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** One leaf invocation. */
|
|
217
|
+
export interface Invocation {
|
|
218
|
+
path: string[];
|
|
219
|
+
flags?: Record<string, unknown>;
|
|
220
|
+
meta: InvocationMeta;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** The result of invoking a leaf. */
|
|
224
|
+
export interface InvokeResult {
|
|
225
|
+
stdout: string;
|
|
226
|
+
stderr?: string;
|
|
227
|
+
exitCode: number;
|
|
228
|
+
/** Structured payload; becomes structuredContent on the modern path. */
|
|
229
|
+
data?: unknown;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* The command-tree abstraction the MCP surface serves. Adopters
|
|
234
|
+
* implement this over their own command framework (see
|
|
235
|
+
* `commanderBridge` for a commander adapter); the surface itself
|
|
236
|
+
* never touches commander, so it stays framework-free.
|
|
237
|
+
*/
|
|
238
|
+
export interface McpBridge {
|
|
239
|
+
/** Every leaf known to the bridge, in stable enumeration order. */
|
|
240
|
+
leaves(): Leaf[];
|
|
241
|
+
/**
|
|
242
|
+
* Invokes one leaf. MUST apply the policy gate and throw
|
|
243
|
+
* DestructiveBlockedError when it blocks, so both eras inherit the
|
|
244
|
+
* identical destructive ceiling from one code path.
|
|
245
|
+
*/
|
|
246
|
+
invoke(inv: Invocation): Promise<InvokeResult> | InvokeResult;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// --- mount options ------------------------------------------------------
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Mount options, mirroring Go's MountMCP option set. Defaults match
|
|
253
|
+
* Go exactly: both eras, path "/mcp", empty origin allowlist, cache
|
|
254
|
+
* hints ttlMs=0 / cacheScope="private".
|
|
255
|
+
*/
|
|
256
|
+
export interface McpMountOptions {
|
|
257
|
+
/** Mount path. Default "/mcp". */
|
|
258
|
+
path?: string;
|
|
259
|
+
/** Server identity in serverInfo. */
|
|
260
|
+
serverInfo?: { name: string; version: string };
|
|
261
|
+
/**
|
|
262
|
+
* Which eras this mount serves. Absent = both. An explicit empty
|
|
263
|
+
* array, or an unrecognized version, is a mount-time error.
|
|
264
|
+
*/
|
|
265
|
+
specVersions?: McpSpecVersion[];
|
|
266
|
+
/** ttlMs + cacheScope on modern cacheable list results. */
|
|
267
|
+
cacheHints?: { ttlMs?: number; cacheScope?: McpCacheScope };
|
|
268
|
+
/** Exact-match Origin allowlist; absent = no Origin check. */
|
|
269
|
+
originAllowlist?: string[];
|
|
270
|
+
/** HMAC key enabling the MRTR confirmation flow. Must be non-empty. */
|
|
271
|
+
confirmationKey?: Uint8Array | string;
|
|
272
|
+
/** Policy gate. Default: defaultPolicy(). */
|
|
273
|
+
policy?: Policy;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Resolved, validated mount configuration. */
|
|
277
|
+
export interface ResolvedMcpConfig {
|
|
278
|
+
path: string;
|
|
279
|
+
serverName: string;
|
|
280
|
+
serverVersion: string;
|
|
281
|
+
legacyEnabled: boolean;
|
|
282
|
+
modernEnabled: boolean;
|
|
283
|
+
cacheTtlMs: number;
|
|
284
|
+
cacheScope: McpCacheScope;
|
|
285
|
+
originAllowlist: string[];
|
|
286
|
+
confirmationKey?: Uint8Array;
|
|
287
|
+
policy: Policy;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Validates and resolves mount options. Reproduces Go's two
|
|
292
|
+
* mount-time errors rather than silently absorbing them: an explicit
|
|
293
|
+
* empty spec-version set, and a negative ttl or unrecognized scope.
|
|
294
|
+
*/
|
|
295
|
+
export function resolveMcpConfig(
|
|
296
|
+
opts: McpMountOptions = {},
|
|
297
|
+
): ResolvedMcpConfig {
|
|
298
|
+
let legacyEnabled = true;
|
|
299
|
+
let modernEnabled = true;
|
|
300
|
+
|
|
301
|
+
if (opts.specVersions !== undefined) {
|
|
302
|
+
if (opts.specVersions.length === 0) {
|
|
303
|
+
throw new Error(
|
|
304
|
+
'cmdsurface: specVersions: at least one spec version required',
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
legacyEnabled = false;
|
|
308
|
+
modernEnabled = false;
|
|
309
|
+
for (const v of opts.specVersions) {
|
|
310
|
+
if (v === MCP_SPEC_2024_11_05) legacyEnabled = true;
|
|
311
|
+
else if (v === MCP_SPEC_2026_07_28) modernEnabled = true;
|
|
312
|
+
else {
|
|
313
|
+
throw new Error(
|
|
314
|
+
`cmdsurface: specVersions: unrecognized version "${v}"`,
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
let cacheTtlMs = 0;
|
|
321
|
+
let cacheScope: McpCacheScope = 'private';
|
|
322
|
+
if (opts.cacheHints !== undefined) {
|
|
323
|
+
const ttl = opts.cacheHints.ttlMs ?? 0;
|
|
324
|
+
if (ttl < 0) {
|
|
325
|
+
throw new Error('cmdsurface: cacheHints: negative ttl');
|
|
326
|
+
}
|
|
327
|
+
// Truncate to whole milliseconds, matching Go's
|
|
328
|
+
// time.Duration.Milliseconds().
|
|
329
|
+
cacheTtlMs = Math.trunc(ttl);
|
|
330
|
+
const scope = opts.cacheHints.cacheScope ?? 'private';
|
|
331
|
+
if (scope !== 'public' && scope !== 'private') {
|
|
332
|
+
throw new Error(
|
|
333
|
+
`cmdsurface: cacheHints: unknown cache scope ${String(scope)}`,
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
cacheScope = scope;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
let confirmationKey: Uint8Array | undefined;
|
|
340
|
+
if (opts.confirmationKey !== undefined) {
|
|
341
|
+
const key =
|
|
342
|
+
typeof opts.confirmationKey === 'string'
|
|
343
|
+
? new TextEncoder().encode(opts.confirmationKey)
|
|
344
|
+
: opts.confirmationKey;
|
|
345
|
+
if (key.length === 0) {
|
|
346
|
+
throw new Error('cmdsurface: confirmationKey: empty key');
|
|
347
|
+
}
|
|
348
|
+
confirmationKey = key;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
return {
|
|
352
|
+
path: opts.path ?? DEFAULT_MCP_PATH,
|
|
353
|
+
serverName: opts.serverInfo?.name ?? DEFAULT_MCP_SERVER_NAME,
|
|
354
|
+
serverVersion: opts.serverInfo?.version ?? DEFAULT_MCP_SERVER_VERSION,
|
|
355
|
+
legacyEnabled,
|
|
356
|
+
modernEnabled,
|
|
357
|
+
cacheTtlMs,
|
|
358
|
+
cacheScope,
|
|
359
|
+
originAllowlist: opts.originAllowlist ?? [],
|
|
360
|
+
confirmationKey,
|
|
361
|
+
policy: opts.policy ?? defaultPolicy(),
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// --- tool naming --------------------------------------------------------
|
|
366
|
+
|
|
367
|
+
/** Renders a leaf path as a dotted MCP tool name. */
|
|
368
|
+
export function toolName(path: string[]): string {
|
|
369
|
+
return path.join('.');
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** Splits a dotted MCP tool name back into a leaf path. */
|
|
373
|
+
export function pathFromToolName(name: string): string[] {
|
|
374
|
+
if (name === '') return [];
|
|
375
|
+
return name.split('.');
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** Renders one leaf as an MCP tool descriptor (shared by both eras). */
|
|
379
|
+
export function buildToolEnvelope(leaf: Leaf): Record<string, unknown> {
|
|
380
|
+
const schema: Record<string, unknown> = {
|
|
381
|
+
type: 'object',
|
|
382
|
+
properties: leaf.properties ?? {},
|
|
383
|
+
};
|
|
384
|
+
if (leaf.required && leaf.required.length > 0) {
|
|
385
|
+
schema.required = leaf.required;
|
|
386
|
+
}
|
|
387
|
+
return {
|
|
388
|
+
name: toolName(leaf.path),
|
|
389
|
+
description: leaf.description,
|
|
390
|
+
inputSchema: schema,
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Renders a bridge result as the tools/call content block list.
|
|
396
|
+
* Shared verbatim by both eras so content layout cannot drift:
|
|
397
|
+
* stdout text block, "[stderr] " block when present, JSON text block
|
|
398
|
+
* when `data` is present.
|
|
399
|
+
*/
|
|
400
|
+
export function renderCallResult(
|
|
401
|
+
res: InvokeResult,
|
|
402
|
+
): Record<string, unknown> {
|
|
403
|
+
const content: Array<Record<string, unknown>> = [
|
|
404
|
+
{ type: 'text', text: res.stdout },
|
|
405
|
+
];
|
|
406
|
+
if (res.stderr) {
|
|
407
|
+
content.push({ type: 'text', text: `[stderr] ${res.stderr}` });
|
|
408
|
+
}
|
|
409
|
+
if (res.data !== undefined && res.data !== null) {
|
|
410
|
+
content.push({ type: 'text', text: canonicalJSONStringify(res.data) });
|
|
411
|
+
}
|
|
412
|
+
return { content, isError: res.exitCode !== 0 };
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** A tools/call result envelope flagged isError with one text block. */
|
|
416
|
+
export function errorResultBlock(msg: string): Record<string, unknown> {
|
|
417
|
+
return {
|
|
418
|
+
content: [{ type: 'text', text: msg }],
|
|
419
|
+
isError: true,
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// --- canonical JSON -----------------------------------------------------
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* A pre-serialized JSON fragment emitted verbatim. Used to echo a
|
|
427
|
+
* request `id` back exactly as received (including `null`, which Go
|
|
428
|
+
* round-trips byte-for-byte through json.RawMessage).
|
|
429
|
+
*/
|
|
430
|
+
export class RawJSON {
|
|
431
|
+
constructor(readonly raw: string) {}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Serializes a value the way Go's encoding/json does for the shapes
|
|
436
|
+
* this surface emits, so wire output is byte-identical to the Go
|
|
437
|
+
* reference rather than merely structurally equal — the fixtures
|
|
438
|
+
* compare bytes, with no decode/re-encode step.
|
|
439
|
+
*
|
|
440
|
+
* Go's rule is not "sort everything": `encoding/json` emits STRUCT
|
|
441
|
+
* fields in declaration order and MAP keys in sorted order. This
|
|
442
|
+
* surface builds result bodies as map[string]any (sorted) inside a
|
|
443
|
+
* jsonRPCResponse struct (declaration order), so the encoder mirrors
|
|
444
|
+
* exactly that split: plain objects are sorted, and the response
|
|
445
|
+
* envelope is emitted through `encodeEnvelope` below, which pins
|
|
446
|
+
* field order. Sorting is by UTF-16 code unit (the JS default),
|
|
447
|
+
* which agrees with Go's byte-wise sort over the ASCII keys emitted
|
|
448
|
+
* here.
|
|
449
|
+
*/
|
|
450
|
+
export function canonicalJSONStringify(value: unknown): string {
|
|
451
|
+
if (value instanceof RawJSON) return value.raw;
|
|
452
|
+
if (value === null || typeof value !== 'object') {
|
|
453
|
+
return JSON.stringify(value) as string;
|
|
454
|
+
}
|
|
455
|
+
if (Array.isArray(value)) {
|
|
456
|
+
return `[${value.map(canonicalJSONStringify).join(',')}]`;
|
|
457
|
+
}
|
|
458
|
+
const src = value as Record<string, unknown>;
|
|
459
|
+
const parts: string[] = [];
|
|
460
|
+
for (const key of Object.keys(src).sort()) {
|
|
461
|
+
const v = src[key];
|
|
462
|
+
if (v === undefined) continue;
|
|
463
|
+
parts.push(`${JSON.stringify(key)}:${canonicalJSONStringify(v)}`);
|
|
464
|
+
}
|
|
465
|
+
return `{${parts.join(',')}}`;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** A JSON-RPC error object, emitted in Go struct-field order. */
|
|
469
|
+
export interface JsonRpcErrorObject {
|
|
470
|
+
code: number;
|
|
471
|
+
message: string;
|
|
472
|
+
data?: unknown;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Encodes one JSON-RPC response envelope with Go's struct field
|
|
477
|
+
* order — `jsonrpc`, `id`, then `result` or `error` — and a trailing
|
|
478
|
+
* newline, matching json.Encoder.Encode. `id` is omitted entirely
|
|
479
|
+
* when absent (Go's `omitempty` on a nil json.RawMessage) but
|
|
480
|
+
* emitted as `null` when the request carried an explicit null id.
|
|
481
|
+
*/
|
|
482
|
+
export function encodeEnvelope(env: {
|
|
483
|
+
id?: RawJSON;
|
|
484
|
+
result?: unknown;
|
|
485
|
+
error?: JsonRpcErrorObject;
|
|
486
|
+
}): string {
|
|
487
|
+
const parts: string[] = ['"jsonrpc":"2.0"'];
|
|
488
|
+
if (env.id !== undefined) {
|
|
489
|
+
parts.push(`"id":${env.id.raw}`);
|
|
490
|
+
}
|
|
491
|
+
if (env.error !== undefined) {
|
|
492
|
+
const errParts: string[] = [
|
|
493
|
+
`"code":${JSON.stringify(env.error.code)}`,
|
|
494
|
+
`"message":${JSON.stringify(env.error.message)}`,
|
|
495
|
+
];
|
|
496
|
+
if (env.error.data !== undefined) {
|
|
497
|
+
errParts.push(`"data":${canonicalJSONStringify(env.error.data)}`);
|
|
498
|
+
}
|
|
499
|
+
parts.push(`"error":{${errParts.join(',')}}`);
|
|
500
|
+
} else if (env.result !== undefined) {
|
|
501
|
+
parts.push(`"result":${canonicalJSONStringify(env.result)}`);
|
|
502
|
+
}
|
|
503
|
+
return `{${parts.join(',')}}\n`;
|
|
504
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mirrors `go/core/netpolicy/netpolicy_test.go` and `install_test.go`.
|
|
3
|
+
*
|
|
4
|
+
* The semantics under test are the Go contract: block external egress when
|
|
5
|
+
* the marker is set, exempt loopback, treat DNS names as remote, leave an
|
|
6
|
+
* unmarked scope untouched, and fail with a matchable error rather than a
|
|
7
|
+
* silent no-op.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
ErrOffline,
|
|
14
|
+
guardFetch,
|
|
15
|
+
install,
|
|
16
|
+
isOffline,
|
|
17
|
+
isOfflineError,
|
|
18
|
+
withOffline,
|
|
19
|
+
} from './netpolicy';
|
|
20
|
+
|
|
21
|
+
/** A fetch stand-in recording whether the wrapped implementation was reached. */
|
|
22
|
+
function recorder() {
|
|
23
|
+
const state = { reached: false };
|
|
24
|
+
const fn = vi.fn(async (_input: any, _init?: any) => {
|
|
25
|
+
state.reached = true;
|
|
26
|
+
return new Response(null, { status: 204 });
|
|
27
|
+
});
|
|
28
|
+
return { state, fn: fn as unknown as typeof globalThis.fetch };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
describe('guardFetch', () => {
|
|
32
|
+
// A marked scope must stop the request before it reaches the wire. The
|
|
33
|
+
// destination is external: loopback is exempt by design.
|
|
34
|
+
it('blocks external hosts when offline', async () => {
|
|
35
|
+
const rec = recorder();
|
|
36
|
+
const guarded = guardFetch(rec.fn);
|
|
37
|
+
|
|
38
|
+
const err = await withOffline(true, async () => {
|
|
39
|
+
try {
|
|
40
|
+
await guarded('https://example.invalid/v1/thing');
|
|
41
|
+
return null;
|
|
42
|
+
} catch (e) {
|
|
43
|
+
return e;
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
expect(err, 'expected an offline error, got none').not.toBeNull();
|
|
48
|
+
expect(isOfflineError(err)).toBe(true);
|
|
49
|
+
expect(rec.state.reached, 'request reached the transport despite offline scope').toBe(false);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
// Unmarked scopes must be entirely unaffected.
|
|
53
|
+
it('allows requests when not offline', async () => {
|
|
54
|
+
const rec = recorder();
|
|
55
|
+
const guarded = guardFetch(rec.fn);
|
|
56
|
+
|
|
57
|
+
const res = await guarded('https://example.invalid/v1/thing');
|
|
58
|
+
expect(res.status).toBe(204);
|
|
59
|
+
expect(rec.state.reached).toBe(true);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
// Loopback stays reachable when offline: --offline means "no network",
|
|
63
|
+
// not "cannot talk to myself".
|
|
64
|
+
it('allows loopback when offline', async () => {
|
|
65
|
+
for (const target of [
|
|
66
|
+
'http://127.0.0.1:8080/health',
|
|
67
|
+
'http://localhost:9000/health',
|
|
68
|
+
'http://[::1]:9000/health',
|
|
69
|
+
]) {
|
|
70
|
+
const rec = recorder();
|
|
71
|
+
const guarded = guardFetch(rec.fn);
|
|
72
|
+
|
|
73
|
+
await withOffline(true, async () => {
|
|
74
|
+
const res = await guarded(target);
|
|
75
|
+
expect(res.status, `${target}: unexpected status`).toBe(204);
|
|
76
|
+
});
|
|
77
|
+
expect(rec.state.reached, `${target}: loopback request was blocked`).toBe(true);
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
// A DNS name is remote even if it might resolve to loopback: resolving
|
|
82
|
+
// it is itself network access.
|
|
83
|
+
it('blocks DNS names when offline', async () => {
|
|
84
|
+
const rec = recorder();
|
|
85
|
+
const guarded = guardFetch(rec.fn);
|
|
86
|
+
|
|
87
|
+
const err = await withOffline(true, async () => {
|
|
88
|
+
try {
|
|
89
|
+
await guarded('http://my-host.internal/health');
|
|
90
|
+
return null;
|
|
91
|
+
} catch (e) {
|
|
92
|
+
return e;
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
expect(isOfflineError(err), `expected ErrOffline, got ${err}`).toBe(true);
|
|
97
|
+
expect(rec.state.reached, 'DNS-named host was allowed through').toBe(false);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
// Request objects carry the URL on `.url`, not as a bare string.
|
|
101
|
+
it('reads the target from a Request object', async () => {
|
|
102
|
+
const rec = recorder();
|
|
103
|
+
const guarded = guardFetch(rec.fn);
|
|
104
|
+
|
|
105
|
+
const err = await withOffline(true, async () => {
|
|
106
|
+
try {
|
|
107
|
+
await guarded(new Request('https://example.invalid/x'));
|
|
108
|
+
return null;
|
|
109
|
+
} catch (e) {
|
|
110
|
+
return e;
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
expect(isOfflineError(err)).toBe(true);
|
|
115
|
+
expect(rec.state.reached).toBe(false);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
// The refusal must be matchable and name the target, mirroring Go's
|
|
119
|
+
// "%s %s: %w" wrapping of ErrOffline.
|
|
120
|
+
it('rejects with a matchable, informative error', async () => {
|
|
121
|
+
const guarded = guardFetch(recorder().fn);
|
|
122
|
+
|
|
123
|
+
const err = await withOffline(true, async () => {
|
|
124
|
+
try {
|
|
125
|
+
await guarded('https://example.invalid/x', { method: 'POST' });
|
|
126
|
+
return null;
|
|
127
|
+
} catch (e) {
|
|
128
|
+
return e;
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
expect(err).toBeInstanceOf(Error);
|
|
133
|
+
expect((err as Error).name).toBe(ErrOffline);
|
|
134
|
+
expect((err as Error).message).toContain('POST');
|
|
135
|
+
expect((err as Error).message).toContain('https://example.invalid/x');
|
|
136
|
+
expect((err as Error).message).toContain('--offline');
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
// Wrapping must be idempotent, mirroring Go's Guard.
|
|
140
|
+
it('does not double-wrap', () => {
|
|
141
|
+
const once = guardFetch(recorder().fn);
|
|
142
|
+
expect(guardFetch(once)).toBe(once);
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
describe('withOffline / isOffline', () => {
|
|
147
|
+
// withOffline(false) must not mark the scope.
|
|
148
|
+
it('leaves the scope clean when false', async () => {
|
|
149
|
+
expect(isOffline()).toBe(false);
|
|
150
|
+
await withOffline(false, async () => {
|
|
151
|
+
expect(isOffline()).toBe(false);
|
|
152
|
+
});
|
|
153
|
+
expect(isOffline()).toBe(false);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('marks the scope when true, and unmarks it on exit', async () => {
|
|
157
|
+
await withOffline(true, async () => {
|
|
158
|
+
expect(isOffline()).toBe(true);
|
|
159
|
+
});
|
|
160
|
+
expect(isOffline()).toBe(false);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
// The marker must survive an await boundary — otherwise a guard running
|
|
164
|
+
// inside an async fetch implementation would not see it.
|
|
165
|
+
it('survives await boundaries', async () => {
|
|
166
|
+
await withOffline(true, async () => {
|
|
167
|
+
await new Promise((r) => setTimeout(r, 1));
|
|
168
|
+
expect(isOffline()).toBe(true);
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
describe('install', () => {
|
|
174
|
+
const orig = globalThis.fetch;
|
|
175
|
+
afterEach(() => {
|
|
176
|
+
globalThis.fetch = orig;
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
// install must make a bare `fetch(...)` call — the common case across kit
|
|
180
|
+
// and adopter code — enforce the policy, and must be idempotent.
|
|
181
|
+
it('guards globalThis.fetch and is idempotent', async () => {
|
|
182
|
+
const rec = recorder();
|
|
183
|
+
globalThis.fetch = rec.fn;
|
|
184
|
+
|
|
185
|
+
install();
|
|
186
|
+
const afterFirst = globalThis.fetch;
|
|
187
|
+
install();
|
|
188
|
+
expect(globalThis.fetch, 'install double-wrapped globalThis.fetch').toBe(afterFirst);
|
|
189
|
+
|
|
190
|
+
const err = await withOffline(true, async () => {
|
|
191
|
+
try {
|
|
192
|
+
await globalThis.fetch('https://example.invalid/x');
|
|
193
|
+
return null;
|
|
194
|
+
} catch (e) {
|
|
195
|
+
return e;
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
expect(isOfflineError(err), `global fetch not guarded after install: ${err}`).toBe(true);
|
|
200
|
+
expect(rec.state.reached).toBe(false);
|
|
201
|
+
});
|
|
202
|
+
});
|