@hop-top/kit 0.5.0-alpha.0 → 0.5.0-alpha.10
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 +262 -0
- package/LICENSE +1 -1
- package/LICENSE-cobra.txt +174 -0
- package/NOTICE +15 -0
- package/README.md +55 -259
- package/dist/aim-DZHwwiIc.d.ts +139 -0
- package/dist/aim.d.ts +1 -116
- package/dist/aim.js +13 -414
- package/dist/alias-D9_qFlyP.d.ts +174 -0
- package/dist/alias.d.ts +2 -73
- package/dist/alias.js +27 -207
- package/dist/api-DAexsu2H.d.ts +77 -0
- package/dist/api.d.ts +1 -62
- package/dist/api.js +10 -164
- package/dist/auth-2-jfgiHn.d.ts +34 -0
- package/dist/auth.d.ts +1 -26
- package/dist/auth.js +6 -40
- package/dist/chunk-2JV3A7OP.js +1894 -0
- package/dist/chunk-3FIKGFKI.js +54 -0
- package/dist/chunk-4UE5TCMQ.js +104 -0
- package/dist/chunk-6HFAEZ52.js +29 -0
- package/dist/chunk-6SVOHNIC.js +17 -0
- package/dist/chunk-72XZWQX7.js +504 -0
- package/dist/chunk-ABQSE7AI.js +513 -0
- package/dist/chunk-BDNNPRX6.js +41 -0
- package/dist/chunk-BLS2OBIQ.js +263 -0
- package/dist/chunk-BRNEKPWX.js +37 -0
- package/dist/chunk-CSJWB6D3.js +151 -0
- package/dist/chunk-GGWJRWWA.js +309 -0
- package/dist/chunk-GHPJJV5L.js +613 -0
- package/dist/chunk-IXVQ62NZ.js +334 -0
- package/dist/chunk-JKMQSAJP.js +174 -0
- package/dist/chunk-JZ22ZUFA.js +1131 -0
- package/dist/chunk-K7VCKJ27.js +814 -0
- package/dist/chunk-KVG7YCTS.js +115 -0
- package/dist/chunk-L23O2FFE.js +51 -0
- package/dist/chunk-MQXYDYRD.js +968 -0
- package/dist/chunk-MUIQVU6E.js +251 -0
- package/dist/chunk-NLMS7HGP.js +178 -0
- package/dist/chunk-POR5L2DG.js +247 -0
- package/dist/chunk-PSFYJGDG.js +1445 -0
- package/dist/chunk-QJVSKKRQ.js +369 -0
- package/dist/chunk-QPUCXQXT.js +67 -0
- package/dist/chunk-QQQYCWSC.js +240 -0
- package/dist/chunk-R5U7XKVJ.js +16 -0
- package/dist/chunk-SNVGDYX7.js +187 -0
- package/dist/chunk-T46YPHKN.js +669 -0
- package/dist/chunk-UKZIAQA7.js +26 -0
- package/dist/chunk-WBVO43HU.js +355 -0
- package/dist/chunk-WUOAQVOA.js +86 -0
- package/dist/chunk-WWUKGJB5.js +90 -0
- package/dist/chunk-XJTRY453.js +868 -0
- package/dist/chunk-YGYQUFGY.js +219 -0
- package/dist/chunk-YOBAUCVN.js +583 -0
- package/dist/cli-C5B5tnpA.d.ts +400 -0
- package/dist/cli.d.ts +7 -309
- package/dist/cli.js +70 -885
- package/dist/completion-csVun6SP.d.ts +112 -0
- package/dist/completion-values-By-mnjNt.d.ts +142 -0
- package/dist/completion-values.d.ts +1 -0
- package/dist/completion-values.js +29 -0
- package/dist/completion.d.ts +3 -0
- package/dist/completion.js +34 -0
- package/dist/compliance-AxFf-uMy.d.ts +60 -0
- package/dist/compliance.d.ts +1 -0
- package/dist/compliance.js +17 -0
- package/dist/config-CaK60ByQ.d.ts +241 -0
- package/dist/config.d.ts +1 -97
- package/dist/config.js +8 -78
- package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
- package/dist/errcorrect.d.ts +1 -37
- package/dist/errcorrect.js +8 -68
- package/dist/error-Do8Qji43.d.ts +231 -0
- package/dist/id/index.d.ts +2 -83
- package/dist/id/index.js +14 -65
- package/dist/index-BKJZClJx.d.ts +1486 -0
- package/dist/index-C3Zw4wDJ.d.ts +359 -0
- package/dist/index-DCe1boBz.d.ts +328 -0
- package/dist/index-VLDcI5NF.d.ts +95 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +132 -0
- package/dist/llm-DYuR7_uX.d.ts +1069 -0
- package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
- package/dist/llm-anthropic.d.ts +2 -0
- package/dist/llm-anthropic.js +13 -0
- package/dist/llm-openai-DyFrucmV.d.ts +87 -0
- package/dist/llm-openai.d.ts +2 -0
- package/dist/llm-openai.js +19 -0
- package/dist/llm.d.ts +1 -188
- package/dist/llm.js +101 -356
- package/dist/log-CkaxMX3U.d.ts +115 -0
- package/dist/log.d.ts +2 -0
- package/dist/log.js +14 -0
- package/dist/mcp/index.d.ts +4 -0
- package/dist/mcp/index.js +184 -0
- package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
- package/dist/netpolicy.d.ts +1 -0
- package/dist/netpolicy.js +25 -0
- package/dist/output-CjZWmL8s.d.ts +420 -0
- package/dist/output.d.ts +3 -213
- package/dist/output.js +137 -447
- package/dist/parity-CvMuYcVI.d.ts +61 -0
- package/dist/progress-CAzyxeWl.d.ts +38 -0
- package/dist/progress.d.ts +1 -30
- package/dist/progress.js +6 -55
- package/dist/provenance-SMFHm5gx.d.ts +30 -0
- package/dist/provenance.d.ts +1 -24
- package/dist/provenance.js +6 -31
- package/dist/routellm-B0nv59mH.d.ts +111 -0
- package/dist/routellm.d.ts +2 -64
- package/dist/routellm.js +13 -255
- package/dist/rpc-D31Lg0Kc.d.ts +32 -0
- package/dist/rpc.d.ts +2 -25
- package/dist/rpc.js +4 -98
- package/dist/safety-CUaYEjZc.d.ts +30 -0
- package/dist/safety.d.ts +1 -24
- package/dist/safety.js +6 -43
- package/dist/scope-BrhYB4ij.d.ts +141 -0
- package/dist/scope.d.ts +1 -121
- package/dist/scope.js +20 -377
- package/dist/serve-D8yWMrTc.d.ts +646 -0
- package/dist/serve.d.ts +3 -0
- package/dist/serve.js +75 -0
- package/dist/sqlstore.js +6 -39
- package/dist/stream-CrjeCp0M.d.ts +44 -0
- package/dist/stream.d.ts +1 -35
- package/dist/stream.js +8 -51
- package/dist/telemetry/index.d.ts +1 -315
- package/dist/telemetry/index.js +26 -599
- package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
- package/dist/toolspec.d.ts +2 -0
- package/dist/toolspec.js +37 -0
- package/dist/tui/index.d.ts +6 -298
- package/dist/tui/index.js +18 -322
- package/dist/upgrade-p_zh3pvV.d.ts +102 -0
- package/dist/upgrade.d.ts +1 -95
- package/dist/upgrade.js +6 -114
- package/dist/xdg-DB7Shoib.d.ts +179 -0
- package/dist/xdg.d.ts +1 -169
- package/dist/xdg.js +14 -128
- package/package.json +236 -46
- package/src/README.md +15 -0
- package/src/alias.conformance.test.ts +250 -0
- package/src/alias.test.ts +206 -2
- package/src/alias.ts +196 -21
- package/src/cli.help-command.test.ts +105 -0
- package/src/cli.offline.test.ts +93 -0
- package/src/cli.parity.test.ts +192 -0
- package/src/cli.test.ts +95 -1
- package/src/cli.ts +195 -25
- package/src/completion-scripts.ts +16 -0
- package/src/completion-values.test.ts +76 -16
- package/src/completion-values.ts +170 -66
- package/src/completion.conformance.test.ts +297 -0
- package/src/completion.test.ts +256 -145
- package/src/completion.ts +767 -121
- package/src/compliance.test.ts +196 -2
- package/src/compliance.ts +440 -20
- package/src/config-merge.test.ts +425 -0
- package/src/config.test.ts +228 -1
- package/src/config.ts +429 -16
- package/src/gen/crud_pb.ts +7 -7
- package/src/id/README.md +38 -0
- package/src/id/contract.test.ts +1 -1
- package/src/id/index.test.ts +1 -1
- package/src/id/index.ts +3 -2
- package/src/index.test.ts +71 -0
- package/src/index.ts +46 -0
- package/src/llm-anthropic.conformance.test.ts +1135 -0
- package/src/llm-anthropic.test.ts +152 -0
- package/src/llm-anthropic.ts +940 -0
- package/src/llm-choice-hermetic.test.ts +335 -0
- package/src/llm-config.test.ts +232 -0
- package/src/llm-config.ts +106 -0
- package/src/llm-endpoint.ts +254 -0
- package/src/llm-error.ts +17 -0
- package/src/llm-errors.ts +152 -0
- package/src/llm-file.ts +126 -0
- package/src/llm-http.ts +317 -0
- package/src/llm-keys.ts +167 -0
- package/src/llm-media.conformance.test.ts +87 -0
- package/src/llm-media.test.ts +279 -0
- package/src/llm-media.ts +322 -0
- package/src/llm-openai.conformance.test.ts +407 -0
- package/src/llm-openai.test.ts +510 -0
- package/src/llm-openai.ts +708 -0
- package/src/llm-payload.ts +155 -0
- package/src/llm-quote.ts +46 -0
- package/src/llm-routellm.conformance.test.ts +44 -0
- package/src/llm-toolnames.conformance.test.ts +112 -0
- package/src/llm-toolnames.test.ts +132 -0
- package/src/llm-toolnames.ts +298 -0
- package/src/llm-uri.ts +99 -0
- package/src/llm.test.ts +43 -15
- package/src/llm.toolcall.test.ts +175 -0
- package/src/llm.ts +602 -190
- package/src/log.parity.test.ts +105 -0
- package/src/log.test.ts +270 -1
- package/src/log.ts +228 -49
- package/src/mcp/README.md +63 -0
- package/src/mcp/args-separator.test.ts +164 -0
- package/src/mcp/args.test.ts +223 -0
- package/src/mcp/args.ts +160 -0
- package/src/mcp/audit.test.ts +520 -0
- package/src/mcp/audit.ts +70 -0
- package/src/mcp/bridge.test.ts +222 -0
- package/src/mcp/bridge.ts +291 -0
- package/src/mcp/conformance.test.ts +357 -0
- package/src/mcp/dispatch.ts +359 -0
- package/src/mcp/identity.test.ts +166 -0
- package/src/mcp/identity.ts +72 -0
- package/src/mcp/index.ts +176 -0
- package/src/mcp/legacy-notify.test.ts +59 -0
- package/src/mcp/legacy.ts +367 -0
- package/src/mcp/mcp.test.ts +707 -0
- package/src/mcp/modern-confirm.test.ts +520 -0
- package/src/mcp/modern-confirm.ts +484 -0
- package/src/mcp/modern.ts +788 -0
- package/src/mcp/stdio.test.ts +313 -0
- package/src/mcp/stdio.ts +254 -0
- package/src/mcp/tasks.ts +82 -0
- package/src/mcp/testtree.ts +250 -0
- package/src/mcp/toolname.test.ts +147 -0
- package/src/mcp/types.ts +689 -0
- package/src/netpolicy.test.ts +280 -0
- package/src/netpolicy.ts +256 -0
- package/src/output/README.md +46 -0
- package/src/output/builtins.ts +5 -5
- package/src/output/dispatch.ts +10 -2
- package/src/output/error.ts +459 -0
- package/src/output/formatter.ts +29 -5
- package/src/output/formatters/README.md +50 -0
- 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 +64 -3
- package/src/published-types.test.ts +133 -0
- package/src/routellm.test.ts +209 -28
- package/src/routellm.toolcall.test.ts +521 -0
- package/src/routellm.ts +213 -177
- package/src/router/README.md +44 -0
- package/src/router/server.test.ts +41 -0
- package/src/router/server.ts +11 -0
- package/src/safety.test.ts +19 -9
- package/src/scope-defaults.json +29 -29
- package/src/serve.test.ts +1257 -0
- package/src/serve.ts +1665 -0
- package/src/telemetry/README.md +48 -0
- package/src/telemetry/client.test.ts +31 -0
- package/src/telemetry/client.ts +12 -6
- package/src/telemetry/offline.test.ts +64 -0
- package/src/toolspec-internal.ts +279 -0
- package/src/toolspec-manifest.test.ts +167 -0
- package/src/toolspec-manifest.ts +410 -0
- package/src/toolspec-spec-schemas.ts +12 -0
- package/src/toolspec-spec.test.ts +273 -0
- package/src/toolspec-spec.ts +458 -0
- package/src/toolspec.from-command.test.ts +350 -0
- package/src/toolspec.test.ts +2 -2
- package/src/toolspec.ts +222 -0
- package/src/triton/README.md +34 -0
- package/src/tui/README.md +42 -0
- package/src/tui/parity.test.ts +142 -0
- package/src/tui/parity.ts +59 -13
- package/src/wizard.test.ts +7 -7
- package/test/llm/conformance-helpers.ts +100 -0
- package/test/output/csv.test.ts +164 -0
- package/test/output/dispatch.test.ts +1 -2
- package/test/output/error.test.ts +277 -0
- package/test/output/smoke-capture.ts +2 -2
- package/test/output/smoke.test.ts +2 -2
- package/test/output/taxonomy-contract.test.ts +148 -0
- package/test/setup-env.ts +16 -0
- package/test/toolspec/fixture.ts +79 -0
- package/tsconfig.json +3 -1
- package/tsconfig.test.json +10 -0
- package/vitest.config.ts +9 -0
package/src/mcp/types.ts
ADDED
|
@@ -0,0 +1,689 @@
|
|
|
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
|
+
import { mcpInputSchema, mcpToolDescription } from './args.js';
|
|
26
|
+
import type { McpHttpRequest } from './dispatch.js';
|
|
27
|
+
|
|
28
|
+
// --- protocol constants -------------------------------------------------
|
|
29
|
+
|
|
30
|
+
/** Reserved `params._meta` / result `_meta` keys (from the v2 SDK). */
|
|
31
|
+
export const META_KEY_PROTOCOL_VERSION = PROTOCOL_VERSION_META_KEY;
|
|
32
|
+
export const META_KEY_CLIENT_INFO = CLIENT_INFO_META_KEY;
|
|
33
|
+
export const META_KEY_CLIENT_CAPABILITIES = CLIENT_CAPABILITIES_META_KEY;
|
|
34
|
+
export const META_KEY_SERVER_INFO = SERVER_INFO_META_KEY;
|
|
35
|
+
|
|
36
|
+
/** Header names carrying the modern routing signals. */
|
|
37
|
+
export const HEADER_MCP_PROTOCOL_VERSION = 'MCP-Protocol-Version';
|
|
38
|
+
export const HEADER_MCP_METHOD = 'Mcp-Method';
|
|
39
|
+
export const HEADER_MCP_NAME = 'Mcp-Name';
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* JSON-RPC error codes. The base codes and the two spec-reserved
|
|
43
|
+
* 2026-07-28 additions come from the SDK's ProtocolErrorCode;
|
|
44
|
+
* HeaderMismatch (-32020) is spec-reserved but absent from the SDK
|
|
45
|
+
* enum, so it is pinned here.
|
|
46
|
+
*
|
|
47
|
+
* The explicit enum-member annotations keep the declaration output a
|
|
48
|
+
* type reference. Inferred, it is `declare const X = ProtocolErrorCode.Y`,
|
|
49
|
+
* and the declaration bundler drops the `ProtocolErrorCode` import an
|
|
50
|
+
* initializer needs, leaving consumers an unresolved name (TS2304).
|
|
51
|
+
*/
|
|
52
|
+
export const MCP_ERR_PARSE: ProtocolErrorCode.ParseError = ProtocolErrorCode.ParseError;
|
|
53
|
+
export const MCP_ERR_INVALID_REQUEST: ProtocolErrorCode.InvalidRequest = ProtocolErrorCode.InvalidRequest;
|
|
54
|
+
export const MCP_ERR_METHOD_NOT_FOUND: ProtocolErrorCode.MethodNotFound = ProtocolErrorCode.MethodNotFound;
|
|
55
|
+
export const MCP_ERR_INVALID_PARAMS: ProtocolErrorCode.InvalidParams = ProtocolErrorCode.InvalidParams;
|
|
56
|
+
export const MCP_ERR_INTERNAL: ProtocolErrorCode.InternalError = ProtocolErrorCode.InternalError;
|
|
57
|
+
export const MCP_ERR_HEADER_MISMATCH = -32020;
|
|
58
|
+
export const MCP_ERR_MISSING_CLIENT_CAPABILITY: ProtocolErrorCode.MissingRequiredClientCapability =
|
|
59
|
+
ProtocolErrorCode.MissingRequiredClientCapability;
|
|
60
|
+
export const MCP_ERR_UNSUPPORTED_VERSION: ProtocolErrorCode.UnsupportedProtocolVersion =
|
|
61
|
+
ProtocolErrorCode.UnsupportedProtocolVersion;
|
|
62
|
+
|
|
63
|
+
/** The two protocol revisions this surface serves. */
|
|
64
|
+
export const MCP_SPEC_2024_11_05 = '2024-11-05';
|
|
65
|
+
export const MCP_SPEC_2026_07_28 = '2026-07-28';
|
|
66
|
+
|
|
67
|
+
export type McpSpecVersion =
|
|
68
|
+
| typeof MCP_SPEC_2024_11_05
|
|
69
|
+
| typeof MCP_SPEC_2026_07_28;
|
|
70
|
+
|
|
71
|
+
/** resultType discriminator values on modern result envelopes. */
|
|
72
|
+
export const RESULT_TYPE_COMPLETE = 'complete';
|
|
73
|
+
export const RESULT_TYPE_INPUT_REQUIRED = 'input_required';
|
|
74
|
+
|
|
75
|
+
/** cacheScope values on modern cacheable list results. */
|
|
76
|
+
export type McpCacheScope = 'public' | 'private';
|
|
77
|
+
|
|
78
|
+
/** Default server identity, matching Go's cmdsurface defaults. */
|
|
79
|
+
export const DEFAULT_MCP_SERVER_NAME = 'cmdsurface';
|
|
80
|
+
export const DEFAULT_MCP_SERVER_VERSION = '0.0.0';
|
|
81
|
+
export const DEFAULT_MCP_PATH = '/mcp';
|
|
82
|
+
/** Default string joining a leaf path into its MCP tool name. */
|
|
83
|
+
export const DEFAULT_TOOL_NAME_SEPARATOR = '.';
|
|
84
|
+
|
|
85
|
+
// --- safety gate --------------------------------------------------------
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Surfaces a leaf may be invoked through. Mirrors Go's Surface type;
|
|
89
|
+
* both MCP spec revisions share the single "mcp" surface — one
|
|
90
|
+
* mount, one exposure decision.
|
|
91
|
+
*/
|
|
92
|
+
export type Surface = 'cli' | 'lib' | 'mcp' | 'rest' | 'rpc' | 'ws' | 'bus';
|
|
93
|
+
|
|
94
|
+
export const SURFACE_CLI: Surface = 'cli';
|
|
95
|
+
export const SURFACE_LIB: Surface = 'lib';
|
|
96
|
+
export const SURFACE_MCP: Surface = 'mcp';
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* SafetyClass is the bridge's read of a leaf's safety annotations —
|
|
100
|
+
* the input the policy gate consults. Mirrors Go's SafetyClass.
|
|
101
|
+
*/
|
|
102
|
+
export interface SafetyClass {
|
|
103
|
+
/** Set for the destructive kit/side-effect tiers. */
|
|
104
|
+
destructive?: boolean;
|
|
105
|
+
/** Set when kit/auth-required is "true". */
|
|
106
|
+
authRequired?: boolean;
|
|
107
|
+
/** Set when kit/requires-confirmation is "true". */
|
|
108
|
+
requiresConfirmation?: boolean;
|
|
109
|
+
permissions?: string[];
|
|
110
|
+
exitCodes?: string[];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Policy gates which Surface may invoke a leaf of a given
|
|
115
|
+
* SafetyClass. Ported from Go's cmdsurface Policy — NOT from
|
|
116
|
+
* src/safety.ts, which implements the unrelated Factor 10 CLI
|
|
117
|
+
* `--force` guard and has no bearing on surface exposure.
|
|
118
|
+
*/
|
|
119
|
+
export interface Policy {
|
|
120
|
+
/**
|
|
121
|
+
* Surfaces on which destructive leaves MAY be invoked. CLI and Lib
|
|
122
|
+
* are always allowed regardless. Empty = block all remote
|
|
123
|
+
* destructive invocation (the default).
|
|
124
|
+
*/
|
|
125
|
+
allowDestructiveOn?: Surface[];
|
|
126
|
+
/** Surfaces a leaf is exposed on when its config omits `enabled`. */
|
|
127
|
+
defaultEnabled?: Surface[];
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* The conservative default policy: no remote surface may invoke a
|
|
132
|
+
* destructive command; default enablement is CLI + Lib + MCP.
|
|
133
|
+
* `allowDestructiveOn` is deliberately empty — empty means block-all,
|
|
134
|
+
* not allow-all.
|
|
135
|
+
*/
|
|
136
|
+
export function defaultPolicy(): Policy {
|
|
137
|
+
return {
|
|
138
|
+
allowDestructiveOn: [],
|
|
139
|
+
defaultEnabled: [SURFACE_CLI, SURFACE_LIB, SURFACE_MCP],
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Reports whether `cls` may be invoked via surface `s` under `p`.
|
|
145
|
+
*
|
|
146
|
+
* 1. cli and lib are always allowed (local runtime).
|
|
147
|
+
* 2. Non-destructive commands are allowed on every other surface.
|
|
148
|
+
* 3. Destructive commands are allowed only when `s` is listed in
|
|
149
|
+
* `allowDestructiveOn`.
|
|
150
|
+
*
|
|
151
|
+
* Surface enablement (per-leaf opt-in) is gated separately; this
|
|
152
|
+
* enforces only the destructive ceiling.
|
|
153
|
+
*/
|
|
154
|
+
export function policyAllowed(
|
|
155
|
+
p: Policy,
|
|
156
|
+
cls: SafetyClass,
|
|
157
|
+
s: Surface,
|
|
158
|
+
): boolean {
|
|
159
|
+
if (s === SURFACE_CLI || s === SURFACE_LIB) return true;
|
|
160
|
+
if (!cls.destructive) return true;
|
|
161
|
+
return (p.allowDestructiveOn ?? []).includes(s);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Error a bridge raises when the policy gate blocks a leaf. */
|
|
165
|
+
export class DestructiveBlockedError extends Error {
|
|
166
|
+
constructor(pathLabel: string, surface: Surface) {
|
|
167
|
+
super(
|
|
168
|
+
`cmdsurface: destructive command blocked on this surface: ${pathLabel} on ${surface}`,
|
|
169
|
+
);
|
|
170
|
+
this.name = 'DestructiveBlockedError';
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Error a bridge raises when a leaf path resolves to nothing. */
|
|
175
|
+
export class UnknownCommandError extends Error {
|
|
176
|
+
constructor(message = 'unknown command') {
|
|
177
|
+
super(message);
|
|
178
|
+
this.name = 'UnknownCommandError';
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Error a bridge raises when a leaf is not exposed on the surface. */
|
|
183
|
+
export class SurfaceNotEnabledError extends Error {
|
|
184
|
+
constructor(message = 'surface not enabled') {
|
|
185
|
+
super(message);
|
|
186
|
+
this.name = 'SurfaceNotEnabledError';
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// --- bridge -------------------------------------------------------------
|
|
191
|
+
|
|
192
|
+
/** A JSON Schema property object describing one flag. */
|
|
193
|
+
export interface FlagSchema {
|
|
194
|
+
type: string;
|
|
195
|
+
description: string;
|
|
196
|
+
items?: { type: string; enum?: string[] };
|
|
197
|
+
/** Allowed values, when the flag declares choices. */
|
|
198
|
+
enum?: string[];
|
|
199
|
+
/** The flag's default, when it is a value of `type`. */
|
|
200
|
+
default?: unknown;
|
|
201
|
+
/** Least array length; set on the positional "args" property. */
|
|
202
|
+
minItems?: number;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** One declared positional argument of a leaf, in declared order. */
|
|
206
|
+
export interface LeafArg {
|
|
207
|
+
name: string;
|
|
208
|
+
/** False/absent for an optional argument. */
|
|
209
|
+
required?: boolean;
|
|
210
|
+
/**
|
|
211
|
+
* True for a `<name...>` / `[name...]` argument: it takes every
|
|
212
|
+
* remaining operand. Informational; the published "args" array
|
|
213
|
+
* carries no maxItems either way.
|
|
214
|
+
*/
|
|
215
|
+
variadic?: boolean;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* One invocable leaf command exposed as an MCP tool. `path` is the
|
|
220
|
+
* leaf's command path; the MCP tool name is the dotted join.
|
|
221
|
+
*/
|
|
222
|
+
export interface Leaf {
|
|
223
|
+
/** Command path, e.g. ["widget","add"] → tool "widget.add". */
|
|
224
|
+
path: string[];
|
|
225
|
+
/** Short description, used as the tool description. */
|
|
226
|
+
description: string;
|
|
227
|
+
/** JSON Schema properties derived from the leaf's flags. */
|
|
228
|
+
properties: Record<string, FlagSchema>;
|
|
229
|
+
/** Names of required flags, in declaration order. */
|
|
230
|
+
required?: string[];
|
|
231
|
+
/**
|
|
232
|
+
* Declared positional arguments, in order. Published as one "args"
|
|
233
|
+
* string-array property and split back out of tools/call arguments
|
|
234
|
+
* into `Invocation.args` (see mcp/args).
|
|
235
|
+
*/
|
|
236
|
+
args?: LeafArg[];
|
|
237
|
+
/** Safety annotations consulted by the policy gate. */
|
|
238
|
+
class?: SafetyClass;
|
|
239
|
+
/** Surfaces this leaf is exposed on. */
|
|
240
|
+
enabled?: Partial<Record<Surface, boolean>>;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* How the surface established a caller, as recorded in
|
|
245
|
+
* `InvocationMeta.established`. Mirrors Go's `cmdsurface.Establishment`:
|
|
246
|
+
* `verified` means the mount's verifier accepted a credential the
|
|
247
|
+
* request presented. Absent means nothing was established; any caller
|
|
248
|
+
* the request claims is a claim, not an identity.
|
|
249
|
+
*/
|
|
250
|
+
export type McpEstablishment = 'verified';
|
|
251
|
+
|
|
252
|
+
/** Metadata attached to one invocation, forwarded to audit sinks. */
|
|
253
|
+
export interface InvocationMeta {
|
|
254
|
+
surface: Surface;
|
|
255
|
+
requestedAt: Date;
|
|
256
|
+
/**
|
|
257
|
+
* The principal the mount's verifier established. Never taken from
|
|
258
|
+
* the request body or headers.
|
|
259
|
+
*/
|
|
260
|
+
caller?: string;
|
|
261
|
+
/** The tenant the verifier established, when it named one. */
|
|
262
|
+
tenant?: string;
|
|
263
|
+
/** Set only when the verifier established the caller. */
|
|
264
|
+
established?: McpEstablishment;
|
|
265
|
+
/**
|
|
266
|
+
* Free-form audit bag; the modern path records spec + client info.
|
|
267
|
+
* `scopes` (comma-joined) comes only from the verifier.
|
|
268
|
+
*/
|
|
269
|
+
extra?: Record<string, string>;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** One leaf invocation. */
|
|
273
|
+
export interface Invocation {
|
|
274
|
+
path: string[];
|
|
275
|
+
/** Positional arguments in declared order, from the "args" property. */
|
|
276
|
+
args?: string[];
|
|
277
|
+
flags?: Record<string, unknown>;
|
|
278
|
+
meta: InvocationMeta;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** The result of invoking a leaf. */
|
|
282
|
+
export interface InvokeResult {
|
|
283
|
+
stdout: string;
|
|
284
|
+
stderr?: string;
|
|
285
|
+
exitCode: number;
|
|
286
|
+
/** Structured payload; becomes structuredContent on the modern path. */
|
|
287
|
+
data?: unknown;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* The command-tree abstraction the MCP surface serves. Adopters
|
|
292
|
+
* implement this over their own command framework (see
|
|
293
|
+
* `commanderBridge` for a commander adapter); the surface itself
|
|
294
|
+
* never touches commander, so it stays framework-free.
|
|
295
|
+
*/
|
|
296
|
+
export interface McpBridge {
|
|
297
|
+
/** Every leaf known to the bridge, in stable enumeration order. */
|
|
298
|
+
leaves(): Leaf[];
|
|
299
|
+
/**
|
|
300
|
+
* Invokes one leaf. MUST apply the policy gate and throw
|
|
301
|
+
* DestructiveBlockedError when it blocks, so both eras inherit the
|
|
302
|
+
* identical destructive ceiling from one code path.
|
|
303
|
+
*/
|
|
304
|
+
invoke(inv: Invocation): Promise<InvokeResult> | InvokeResult;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// --- caller verification ------------------------------------------------
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* The caller a verifier established for one request. Mirrors the Go
|
|
311
|
+
* surfaces' `Meta` identity: `caller` is the stable principal (a user
|
|
312
|
+
* id, a service account, a client id), `tenant` the account it acts
|
|
313
|
+
* in, `scopes` what it was granted. All optional: a verifier may
|
|
314
|
+
* accept a credential that names no principal.
|
|
315
|
+
*/
|
|
316
|
+
export interface McpIdentity {
|
|
317
|
+
caller?: string;
|
|
318
|
+
tenant?: string;
|
|
319
|
+
scopes?: string[];
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Establishes who is calling. The mount calls it once per `tools/call`
|
|
324
|
+
* with the request as received; it checks a credential the request
|
|
325
|
+
* presents (a bearer token, a signed header) and returns the caller,
|
|
326
|
+
* or `null`/`undefined` to refuse. Throwing refuses too.
|
|
327
|
+
*
|
|
328
|
+
* Only an identity a verifier returns authenticates a call: a
|
|
329
|
+
* `kit/auth-required` leaf is refused with 401 unless it does. An
|
|
330
|
+
* `Authorization` header is presence, not verification, and a caller
|
|
331
|
+
* or scopes the request claims in its body never become identity.
|
|
332
|
+
*/
|
|
333
|
+
export type McpVerifier = (
|
|
334
|
+
req: McpHttpRequest,
|
|
335
|
+
) =>
|
|
336
|
+
| McpIdentity
|
|
337
|
+
| null
|
|
338
|
+
| undefined
|
|
339
|
+
| Promise<McpIdentity | null | undefined>;
|
|
340
|
+
|
|
341
|
+
/** The challenge a 401 carries in WWW-Authenticate, as Go's api.DefaultAuthChallenge. */
|
|
342
|
+
export const MCP_AUTH_CHALLENGE = 'Bearer';
|
|
343
|
+
|
|
344
|
+
// --- refusal audit ------------------------------------------------------
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* One refusal the surface decided before adopter code ran: the record
|
|
348
|
+
* Go's bridge sinks receive from the MCP surface, reduced to the
|
|
349
|
+
* fields the surface has (a `cmdsurface.Invocation` subset plus the
|
|
350
|
+
* error). No caller, arguments or flags travel on it, so there is
|
|
351
|
+
* nothing to redact.
|
|
352
|
+
*/
|
|
353
|
+
export interface McpAuditRecord {
|
|
354
|
+
/** The resolved leaf path, e.g. `["widget","delete"]`. */
|
|
355
|
+
path: string[];
|
|
356
|
+
surface: 'mcp';
|
|
357
|
+
/** When the refusal was decided. */
|
|
358
|
+
requestedAt: Date;
|
|
359
|
+
/** The protocol revision serving the request. */
|
|
360
|
+
specVersion: string;
|
|
361
|
+
/**
|
|
362
|
+
* Go's sentinel error message for the event, verbatim (see the
|
|
363
|
+
* `MCP_AUDIT_*` constants in `mcp/audit`).
|
|
364
|
+
*/
|
|
365
|
+
error: string;
|
|
366
|
+
/**
|
|
367
|
+
* Always `mcp_spec_version`; `mcp_confirm_rejection` on a rejected
|
|
368
|
+
* `requestState`. Keys are the Go snake_case strings so the records
|
|
369
|
+
* forward to the same audit backends.
|
|
370
|
+
*/
|
|
371
|
+
extra: Record<string, string>;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* The mount-level audit hook. Called synchronously once per refusal,
|
|
376
|
+
* after the refusal is decided and before the response is returned.
|
|
377
|
+
* Best-effort: a throwing hook never changes the wire response.
|
|
378
|
+
*/
|
|
379
|
+
export type McpAuditHook = (record: McpAuditRecord) => void;
|
|
380
|
+
|
|
381
|
+
// --- mount options ------------------------------------------------------
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Mount options, mirroring Go's MountMCP option set. Defaults match
|
|
385
|
+
* Go exactly: both eras, path "/mcp", empty origin allowlist, cache
|
|
386
|
+
* hints ttlMs=0 / cacheScope="private".
|
|
387
|
+
*/
|
|
388
|
+
export interface McpMountOptions {
|
|
389
|
+
/** Mount path. Default "/mcp". */
|
|
390
|
+
path?: string;
|
|
391
|
+
/** Server identity in serverInfo. */
|
|
392
|
+
serverInfo?: { name: string; version: string };
|
|
393
|
+
/**
|
|
394
|
+
* Which eras this mount serves. Absent = both. An explicit empty
|
|
395
|
+
* array, or an unrecognized version, is a mount-time error.
|
|
396
|
+
*/
|
|
397
|
+
specVersions?: McpSpecVersion[];
|
|
398
|
+
/** ttlMs + cacheScope on modern cacheable list results. */
|
|
399
|
+
cacheHints?: { ttlMs?: number; cacheScope?: McpCacheScope };
|
|
400
|
+
/** Exact-match Origin allowlist; absent = no Origin check. */
|
|
401
|
+
originAllowlist?: string[];
|
|
402
|
+
/** HMAC key enabling the MRTR confirmation flow. Must be non-empty. */
|
|
403
|
+
confirmationKey?: Uint8Array | string;
|
|
404
|
+
/** Policy gate. Default: defaultPolicy(). */
|
|
405
|
+
policy?: Policy;
|
|
406
|
+
/**
|
|
407
|
+
* Establishes the caller of each `tools/call`. Without one no call
|
|
408
|
+
* is established, so every `kit/auth-required` leaf is refused.
|
|
409
|
+
*/
|
|
410
|
+
verifier?: McpVerifier;
|
|
411
|
+
/**
|
|
412
|
+
* Joins a leaf path into its tool name, and splits a called name
|
|
413
|
+
* back. Default ".". `"_"` names the leaf `widget add` `widget_add`,
|
|
414
|
+
* for hosts that admit only `^[A-Za-z0-9_-]{1,64}$`. Empty is a
|
|
415
|
+
* mount-time error, and so is any separator but the default that a
|
|
416
|
+
* command name contains: the name would not map back to one leaf.
|
|
417
|
+
*/
|
|
418
|
+
toolNameSeparator?: string;
|
|
419
|
+
/**
|
|
420
|
+
* Receives one {@link McpAuditRecord} per refusal the surface
|
|
421
|
+
* decides: auth refused, confirmation required / declined / state
|
|
422
|
+
* rejected, destructive ceiling. The counterpart of Go's bridge
|
|
423
|
+
* sinks for the MCP surface. Best-effort: it runs after the refusal
|
|
424
|
+
* is decided, before the response is returned, and a throw is
|
|
425
|
+
* swallowed.
|
|
426
|
+
*/
|
|
427
|
+
audit?: McpAuditHook;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** Resolved, validated mount configuration. */
|
|
431
|
+
export interface ResolvedMcpConfig {
|
|
432
|
+
path: string;
|
|
433
|
+
serverName: string;
|
|
434
|
+
serverVersion: string;
|
|
435
|
+
legacyEnabled: boolean;
|
|
436
|
+
modernEnabled: boolean;
|
|
437
|
+
cacheTtlMs: number;
|
|
438
|
+
cacheScope: McpCacheScope;
|
|
439
|
+
originAllowlist: string[];
|
|
440
|
+
confirmationKey?: Uint8Array;
|
|
441
|
+
policy: Policy;
|
|
442
|
+
verifier?: McpVerifier;
|
|
443
|
+
toolNameSeparator: string;
|
|
444
|
+
audit?: McpAuditHook;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Validates and resolves mount options. Reproduces Go's two
|
|
449
|
+
* mount-time errors rather than silently absorbing them: an explicit
|
|
450
|
+
* empty spec-version set, and a negative ttl or unrecognized scope.
|
|
451
|
+
*/
|
|
452
|
+
export function resolveMcpConfig(
|
|
453
|
+
opts: McpMountOptions = {},
|
|
454
|
+
): ResolvedMcpConfig {
|
|
455
|
+
let legacyEnabled = true;
|
|
456
|
+
let modernEnabled = true;
|
|
457
|
+
|
|
458
|
+
if (opts.specVersions !== undefined) {
|
|
459
|
+
if (opts.specVersions.length === 0) {
|
|
460
|
+
throw new Error(
|
|
461
|
+
'cmdsurface: specVersions: at least one spec version required',
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
legacyEnabled = false;
|
|
465
|
+
modernEnabled = false;
|
|
466
|
+
for (const v of opts.specVersions) {
|
|
467
|
+
if (v === MCP_SPEC_2024_11_05) legacyEnabled = true;
|
|
468
|
+
else if (v === MCP_SPEC_2026_07_28) modernEnabled = true;
|
|
469
|
+
else {
|
|
470
|
+
throw new Error(
|
|
471
|
+
`cmdsurface: specVersions: unrecognized version "${v}"`,
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
let cacheTtlMs = 0;
|
|
478
|
+
let cacheScope: McpCacheScope = 'private';
|
|
479
|
+
if (opts.cacheHints !== undefined) {
|
|
480
|
+
const ttl = opts.cacheHints.ttlMs ?? 0;
|
|
481
|
+
if (ttl < 0) {
|
|
482
|
+
throw new Error('cmdsurface: cacheHints: negative ttl');
|
|
483
|
+
}
|
|
484
|
+
// Truncate to whole milliseconds, matching Go's
|
|
485
|
+
// time.Duration.Milliseconds().
|
|
486
|
+
cacheTtlMs = Math.trunc(ttl);
|
|
487
|
+
const scope = opts.cacheHints.cacheScope ?? 'private';
|
|
488
|
+
if (scope !== 'public' && scope !== 'private') {
|
|
489
|
+
throw new Error(
|
|
490
|
+
`cmdsurface: cacheHints: unknown cache scope ${String(scope)}`,
|
|
491
|
+
);
|
|
492
|
+
}
|
|
493
|
+
cacheScope = scope;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
let confirmationKey: Uint8Array | undefined;
|
|
497
|
+
if (opts.confirmationKey !== undefined) {
|
|
498
|
+
const key =
|
|
499
|
+
typeof opts.confirmationKey === 'string'
|
|
500
|
+
? new TextEncoder().encode(opts.confirmationKey)
|
|
501
|
+
: opts.confirmationKey;
|
|
502
|
+
if (key.length === 0) {
|
|
503
|
+
throw new Error('cmdsurface: confirmationKey: empty key');
|
|
504
|
+
}
|
|
505
|
+
confirmationKey = key;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
const toolNameSeparator = opts.toolNameSeparator ?? DEFAULT_TOOL_NAME_SEPARATOR;
|
|
509
|
+
if (toolNameSeparator === '') {
|
|
510
|
+
throw new Error('cmdsurface: toolNameSeparator: empty separator');
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
return {
|
|
514
|
+
path: opts.path ?? DEFAULT_MCP_PATH,
|
|
515
|
+
serverName: opts.serverInfo?.name ?? DEFAULT_MCP_SERVER_NAME,
|
|
516
|
+
serverVersion: opts.serverInfo?.version ?? DEFAULT_MCP_SERVER_VERSION,
|
|
517
|
+
legacyEnabled,
|
|
518
|
+
modernEnabled,
|
|
519
|
+
cacheTtlMs,
|
|
520
|
+
cacheScope,
|
|
521
|
+
originAllowlist: opts.originAllowlist ?? [],
|
|
522
|
+
confirmationKey,
|
|
523
|
+
policy: opts.policy ?? defaultPolicy(),
|
|
524
|
+
verifier: opts.verifier,
|
|
525
|
+
toolNameSeparator,
|
|
526
|
+
audit: opts.audit,
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// --- tool naming --------------------------------------------------------
|
|
531
|
+
|
|
532
|
+
/** Renders a leaf path as an MCP tool name, joined with `separator`. */
|
|
533
|
+
export function toolName(
|
|
534
|
+
path: string[],
|
|
535
|
+
separator: string = DEFAULT_TOOL_NAME_SEPARATOR,
|
|
536
|
+
): string {
|
|
537
|
+
return path.join(separator);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/** Splits an MCP tool name back into a leaf path on `separator`. */
|
|
541
|
+
export function pathFromToolName(
|
|
542
|
+
name: string,
|
|
543
|
+
separator: string = DEFAULT_TOOL_NAME_SEPARATOR,
|
|
544
|
+
): string[] {
|
|
545
|
+
if (name === '') return [];
|
|
546
|
+
return name.split(separator);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Refuses, for any separator but the default, a leaf whose command
|
|
551
|
+
* name contains it: its tool name would not split back to one leaf.
|
|
552
|
+
*/
|
|
553
|
+
export function checkToolNameSeparator(leaves: Leaf[], separator: string): void {
|
|
554
|
+
if (separator === DEFAULT_TOOL_NAME_SEPARATOR) return;
|
|
555
|
+
for (const leaf of leaves) {
|
|
556
|
+
for (const seg of leaf.path) {
|
|
557
|
+
if (seg.includes(separator)) {
|
|
558
|
+
throw new Error(
|
|
559
|
+
`cmdsurface: toolNameSeparator: command ${JSON.stringify(seg)} in ` +
|
|
560
|
+
`${JSON.stringify(leaf.path.join(' '))} contains separator ${JSON.stringify(separator)}`,
|
|
561
|
+
);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** Renders one leaf as an MCP tool descriptor (shared by both eras). */
|
|
568
|
+
export function buildToolEnvelope(
|
|
569
|
+
leaf: Leaf,
|
|
570
|
+
separator: string = DEFAULT_TOOL_NAME_SEPARATOR,
|
|
571
|
+
): Record<string, unknown> {
|
|
572
|
+
return {
|
|
573
|
+
name: toolName(leaf.path, separator),
|
|
574
|
+
description: mcpToolDescription(leaf),
|
|
575
|
+
inputSchema: mcpInputSchema(leaf),
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Renders a bridge result as the tools/call content block list.
|
|
581
|
+
* Shared verbatim by both eras so content layout cannot drift:
|
|
582
|
+
* stdout text block, "[stderr] " block when present, JSON text block
|
|
583
|
+
* when `data` is present.
|
|
584
|
+
*/
|
|
585
|
+
export function renderCallResult(
|
|
586
|
+
res: InvokeResult,
|
|
587
|
+
): Record<string, unknown> {
|
|
588
|
+
const content: Array<Record<string, unknown>> = [
|
|
589
|
+
{ type: 'text', text: res.stdout },
|
|
590
|
+
];
|
|
591
|
+
if (res.stderr) {
|
|
592
|
+
content.push({ type: 'text', text: `[stderr] ${res.stderr}` });
|
|
593
|
+
}
|
|
594
|
+
if (res.data !== undefined && res.data !== null) {
|
|
595
|
+
content.push({ type: 'text', text: canonicalJSONStringify(res.data) });
|
|
596
|
+
}
|
|
597
|
+
return { content, isError: res.exitCode !== 0 };
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/** A tools/call result envelope flagged isError with one text block. */
|
|
601
|
+
export function errorResultBlock(msg: string): Record<string, unknown> {
|
|
602
|
+
return {
|
|
603
|
+
content: [{ type: 'text', text: msg }],
|
|
604
|
+
isError: true,
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// --- canonical JSON -----------------------------------------------------
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* A pre-serialized JSON fragment emitted verbatim. Used to echo a
|
|
612
|
+
* request `id` back exactly as received (including `null`, which Go
|
|
613
|
+
* round-trips byte-for-byte through json.RawMessage).
|
|
614
|
+
*/
|
|
615
|
+
export class RawJSON {
|
|
616
|
+
constructor(readonly raw: string) {}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* Serializes a value the way Go's encoding/json does for the shapes
|
|
621
|
+
* this surface emits, so wire output is byte-identical to the Go
|
|
622
|
+
* reference rather than merely structurally equal — the fixtures
|
|
623
|
+
* compare bytes, with no decode/re-encode step.
|
|
624
|
+
*
|
|
625
|
+
* Go's rule is not "sort everything": `encoding/json` emits STRUCT
|
|
626
|
+
* fields in declaration order and MAP keys in sorted order. This
|
|
627
|
+
* surface builds result bodies as map[string]any (sorted) inside a
|
|
628
|
+
* jsonRPCResponse struct (declaration order), so the encoder mirrors
|
|
629
|
+
* exactly that split: plain objects are sorted, and the response
|
|
630
|
+
* envelope is emitted through `encodeEnvelope` below, which pins
|
|
631
|
+
* field order. Sorting is by UTF-16 code unit (the JS default),
|
|
632
|
+
* which agrees with Go's byte-wise sort over the ASCII keys emitted
|
|
633
|
+
* here.
|
|
634
|
+
*/
|
|
635
|
+
export function canonicalJSONStringify(value: unknown): string {
|
|
636
|
+
if (value instanceof RawJSON) return value.raw;
|
|
637
|
+
if (value === null || typeof value !== 'object') {
|
|
638
|
+
return JSON.stringify(value) as string;
|
|
639
|
+
}
|
|
640
|
+
if (Array.isArray(value)) {
|
|
641
|
+
return `[${value.map(canonicalJSONStringify).join(',')}]`;
|
|
642
|
+
}
|
|
643
|
+
const src = value as Record<string, unknown>;
|
|
644
|
+
const parts: string[] = [];
|
|
645
|
+
for (const key of Object.keys(src).sort()) {
|
|
646
|
+
const v = src[key];
|
|
647
|
+
if (v === undefined) continue;
|
|
648
|
+
parts.push(`${JSON.stringify(key)}:${canonicalJSONStringify(v)}`);
|
|
649
|
+
}
|
|
650
|
+
return `{${parts.join(',')}}`;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/** A JSON-RPC error object, emitted in Go struct-field order. */
|
|
654
|
+
export interface JsonRpcErrorObject {
|
|
655
|
+
code: number;
|
|
656
|
+
message: string;
|
|
657
|
+
data?: unknown;
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* Encodes one JSON-RPC response envelope with Go's struct field
|
|
662
|
+
* order — `jsonrpc`, `id`, then `result` or `error` — and a trailing
|
|
663
|
+
* newline, matching json.Encoder.Encode. `id` is omitted entirely
|
|
664
|
+
* when absent (Go's `omitempty` on a nil json.RawMessage) but
|
|
665
|
+
* emitted as `null` when the request carried an explicit null id.
|
|
666
|
+
*/
|
|
667
|
+
export function encodeEnvelope(env: {
|
|
668
|
+
id?: RawJSON;
|
|
669
|
+
result?: unknown;
|
|
670
|
+
error?: JsonRpcErrorObject;
|
|
671
|
+
}): string {
|
|
672
|
+
const parts: string[] = ['"jsonrpc":"2.0"'];
|
|
673
|
+
if (env.id !== undefined) {
|
|
674
|
+
parts.push(`"id":${env.id.raw}`);
|
|
675
|
+
}
|
|
676
|
+
if (env.error !== undefined) {
|
|
677
|
+
const errParts: string[] = [
|
|
678
|
+
`"code":${JSON.stringify(env.error.code)}`,
|
|
679
|
+
`"message":${JSON.stringify(env.error.message)}`,
|
|
680
|
+
];
|
|
681
|
+
if (env.error.data !== undefined) {
|
|
682
|
+
errParts.push(`"data":${canonicalJSONStringify(env.error.data)}`);
|
|
683
|
+
}
|
|
684
|
+
parts.push(`"error":{${errParts.join(',')}}`);
|
|
685
|
+
} else if (env.result !== undefined) {
|
|
686
|
+
parts.push(`"result":${canonicalJSONStringify(env.result)}`);
|
|
687
|
+
}
|
|
688
|
+
return `{${parts.join(',')}}\n`;
|
|
689
|
+
}
|