toolsplice 0.0.0-stage → 0.0.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.
- package/LICENSE +21 -0
- package/README.md +104 -2
- package/dist/abortable.d.ts +6 -0
- package/dist/abortable.js +50 -0
- package/dist/adaptive-read.d.ts +50 -0
- package/dist/adaptive-read.js +780 -0
- package/dist/answer-wait.d.ts +7 -0
- package/dist/answer-wait.js +45 -0
- package/dist/cache-reads.d.ts +18 -0
- package/dist/cache-reads.js +89 -0
- package/dist/calibration-ledger.d.ts +37 -0
- package/dist/calibration-ledger.js +148 -0
- package/dist/calibration-marker.d.ts +4 -0
- package/dist/calibration-marker.js +77 -0
- package/dist/catalog-setup.d.ts +33 -0
- package/dist/catalog-setup.js +89 -0
- package/dist/catalog.d.ts +10 -0
- package/dist/catalog.js +42 -0
- package/dist/checkpoint-files.d.ts +15 -0
- package/dist/checkpoint-files.js +99 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +1454 -0
- package/dist/coalesce-reads.d.ts +6 -0
- package/dist/coalesce-reads.js +33 -0
- package/dist/codegen.d.ts +44 -0
- package/dist/codegen.js +479 -0
- package/dist/contract-caller.d.ts +23 -0
- package/dist/contract-caller.js +326 -0
- package/dist/contract-corrections.d.ts +35 -0
- package/dist/contract-corrections.js +159 -0
- package/dist/contract-schema.d.ts +7 -0
- package/dist/contract-schema.js +156 -0
- package/dist/contracts.d.ts +72 -0
- package/dist/contracts.js +370 -0
- package/dist/core.d.ts +44 -0
- package/dist/core.js +43 -0
- package/dist/db-final-answer.d.ts +9 -0
- package/dist/db-final-answer.js +62 -0
- package/dist/define.d.ts +78 -0
- package/dist/define.js +14 -0
- package/dist/doctor.d.ts +22 -0
- package/dist/doctor.js +91 -0
- package/dist/drift.d.ts +23 -0
- package/dist/drift.js +111 -0
- package/dist/execution.d.ts +38 -0
- package/dist/execution.js +66 -0
- package/dist/extract.d.ts +34 -0
- package/dist/extract.js +73 -0
- package/dist/final-answer-stores.d.ts +71 -0
- package/dist/final-answer-stores.js +72 -0
- package/dist/final-answer.d.ts +32 -0
- package/dist/final-answer.js +104 -0
- package/dist/impact.d.ts +48 -0
- package/dist/impact.js +71 -0
- package/dist/index.d.ts +51 -0
- package/dist/index.js +47 -0
- package/dist/local-tool.d.ts +18 -0
- package/dist/local-tool.js +32 -0
- package/dist/mcp-apps.d.ts +53 -0
- package/dist/mcp-apps.js +32 -0
- package/dist/mcp-event-delivery.d.ts +98 -0
- package/dist/mcp-event-delivery.js +211 -0
- package/dist/mcp-extensions.d.ts +46 -0
- package/dist/mcp-extensions.js +200 -0
- package/dist/mcp-peer.d.ts +45 -0
- package/dist/mcp-peer.js +207 -0
- package/dist/mcp-server-card.d.ts +21 -0
- package/dist/mcp-server-card.js +54 -0
- package/dist/ordered-transport.d.ts +12 -0
- package/dist/ordered-transport.js +106 -0
- package/dist/page-checkpoint.d.ts +71 -0
- package/dist/page-checkpoint.js +286 -0
- package/dist/page-read-gate.d.ts +15 -0
- package/dist/page-read-gate.js +48 -0
- package/dist/pattern.d.ts +3 -0
- package/dist/pattern.js +54 -0
- package/dist/postgres.d.ts +41 -0
- package/dist/postgres.js +264 -0
- package/dist/probe.d.ts +29 -0
- package/dist/probe.js +121 -0
- package/dist/proxy.d.ts +40 -0
- package/dist/proxy.js +436 -0
- package/dist/read-pages.d.ts +25 -0
- package/dist/read-pages.js +85 -0
- package/dist/read-policy.d.ts +6 -0
- package/dist/read-policy.js +16 -0
- package/dist/read-steps.d.ts +12 -0
- package/dist/read-steps.js +36 -0
- package/dist/result-session.d.ts +109 -0
- package/dist/result-session.js +620 -0
- package/dist/route-checkpoint.d.ts +3 -0
- package/dist/route-checkpoint.js +80 -0
- package/dist/route-driver-cli.d.ts +3 -0
- package/dist/route-driver-cli.js +43 -0
- package/dist/route-evaluation.d.ts +141 -0
- package/dist/route-evaluation.js +329 -0
- package/dist/row-groups.d.ts +17 -0
- package/dist/row-groups.js +79 -0
- package/dist/row-query.d.ts +62 -0
- package/dist/row-query.js +172 -0
- package/dist/rules.d.ts +30 -0
- package/dist/rules.js +72 -0
- package/dist/run-diagnostics.d.ts +75 -0
- package/dist/run-diagnostics.js +212 -0
- package/dist/runtime.d.ts +6 -0
- package/dist/runtime.js +26 -0
- package/dist/schema.d.ts +17 -0
- package/dist/schema.js +299 -0
- package/dist/search-fetch.d.ts +50 -0
- package/dist/search-fetch.js +264 -0
- package/dist/shape.d.ts +91 -0
- package/dist/shape.js +499 -0
- package/dist/skill-files.d.ts +9 -0
- package/dist/skill-files.js +49 -0
- package/dist/splice-diagnostics.d.ts +44 -0
- package/dist/splice-diagnostics.js +88 -0
- package/dist/splice-measure.d.ts +33 -0
- package/dist/splice-measure.js +55 -0
- package/dist/splice-project.d.ts +125 -0
- package/dist/splice-project.js +348 -0
- package/dist/splice-recording.d.ts +132 -0
- package/dist/splice-recording.js +481 -0
- package/dist/splice.d.ts +181 -0
- package/dist/splice.js +1263 -0
- package/dist/sqlite-checkpoint-store.d.ts +5 -0
- package/dist/sqlite-checkpoint-store.js +91 -0
- package/dist/sqlite-checkpoint-worker.d.ts +1 -0
- package/dist/sqlite-checkpoint-worker.js +115 -0
- package/dist/storage.d.ts +17 -0
- package/dist/storage.js +1 -0
- package/dist/store.d.ts +151 -0
- package/dist/store.js +735 -0
- package/dist/test-difference.d.ts +13 -0
- package/dist/test-difference.js +42 -0
- package/dist/testing.d.ts +122 -0
- package/dist/testing.js +261 -0
- package/dist/text-pages.d.ts +24 -0
- package/dist/text-pages.js +36 -0
- package/dist/tool-discovery.d.ts +59 -0
- package/dist/tool-discovery.js +136 -0
- package/dist/unevaluated.d.ts +7 -0
- package/dist/unevaluated.js +156 -0
- package/dist/v2.d.ts +49 -0
- package/dist/v2.js +413 -0
- package/dist/validate-output.d.ts +3 -0
- package/dist/validate-output.js +73 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +1 -0
- package/dist/workflow-json.d.ts +8 -0
- package/dist/workflow-json.js +74 -0
- package/docs/AGENT-FRAMEWORKS.md +431 -0
- package/docs/BENCHMARKS.md +43 -0
- package/docs/INTEGRATION-QUICKSTART.md +859 -0
- package/docs/LEARNING-AND-STORAGE.md +393 -0
- package/docs/MCP.md +204 -0
- package/docs/PROJECTS-AND-UPGRADES.md +173 -0
- package/docs/PYTHON-REFERENCE.md +348 -0
- package/docs/PYTHON.md +120 -0
- package/docs/RECORDING-AND-CORRECTIONS.md +205 -0
- package/docs/TESTING.md +259 -0
- package/examples/mcp-app/build.mjs +11 -0
- package/examples/mcp-app/view.mjs +22 -0
- package/examples/quickstart.mjs +43 -0
- package/examples/route-driver.mjs +67 -0
- package/integrations/ai.d.mts +36 -0
- package/integrations/ai.mjs +178 -0
- package/integrations/call-options.mjs +9 -0
- package/integrations/langchain.d.mts +31 -0
- package/integrations/langchain.mjs +114 -0
- package/integrations/managed.mjs +154 -0
- package/integrations/types.d.mts +13 -0
- package/package.json +139 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1454 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
3
|
+
import { ListToolsResultSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
4
|
+
import { validMcpHeaderSchema } from "./contract-schema.js";
|
|
5
|
+
import { collectToolCatalog } from "./catalog.js";
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { openSync, closeSync, linkSync, unlinkSync, readFileSync, writeFileSync, statSync, realpathSync } from "node:fs";
|
|
8
|
+
import { catalogToolNames, inspectCatalogMapping, parseCatalogBinding } from "./catalog-setup.js";
|
|
9
|
+
import { assessSpliceImpact } from "./impact.js";
|
|
10
|
+
import { runSpliceSuite, formatTestJUnit, suiteFromRecording } from "./testing.js";
|
|
11
|
+
import { delimiter, dirname, resolve, relative, isAbsolute, sep } from "node:path";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { existsSync, createReadStream } from "node:fs";
|
|
14
|
+
import { evaluateRoutes, readCalibrationLedger } from "./route-evaluation.js";
|
|
15
|
+
import { executeRouteDriver } from "./route-driver-cli.js";
|
|
16
|
+
import { parseArgs } from "node:util";
|
|
17
|
+
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
18
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
19
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
20
|
+
import { parseSpliceSpec, prepareSplice, emitSpliceModule, SpliceError, } from "./splice.js";
|
|
21
|
+
import { decode } from "./runtime.js";
|
|
22
|
+
import { explainSpliceError } from "./splice-diagnostics.js";
|
|
23
|
+
import { measureSpliceRecording } from "./splice-measure.js";
|
|
24
|
+
import { replaySpliceRecording } from "./splice-recording.js";
|
|
25
|
+
import { applyContractCorrection, parseContractCorrection, } from "./contract-corrections.js";
|
|
26
|
+
import { parseWorkflowJson, JSON_LIMIT } from "./workflow-json.js";
|
|
27
|
+
import { initializeSpliceProject, checkSpliceProject, } from "./splice-project.js";
|
|
28
|
+
import { createContractSnapshot, createContractFromCatalog, parseContractSnapshot, compareContractSnapshots, contractCheckFailed, } from "./contracts.js";
|
|
29
|
+
import { describeOutput, emitModule, emitBindings } from "./codegen.js";
|
|
30
|
+
import { diagnose, formatDoctor } from "./doctor.js";
|
|
31
|
+
import { exportFingerprint } from "./drift.js";
|
|
32
|
+
import { probe } from "./probe.js";
|
|
33
|
+
import { createProxy } from "./proxy.js";
|
|
34
|
+
import { toJsonSchema } from "./schema.js";
|
|
35
|
+
import { VERSION } from "./version.js";
|
|
36
|
+
import { ShapeStore } from "./store.js";
|
|
37
|
+
const USAGE = `toolsplice: check and generate MCP tool handoffs
|
|
38
|
+
|
|
39
|
+
Usage:
|
|
40
|
+
toolsplice splice <plan.json> [--fixture <file>] Check or dry-run an explicit tool-to-tool adapter; no tool calls
|
|
41
|
+
toolsplice replay <recording.json> [--json] Replay a recorded run entirely offline; exit 2 on mismatch
|
|
42
|
+
toolsplice discover [--with-tools] --url <url> [--out discovery.json] Negotiate the protocol and list server capabilities (SDK 2.x)
|
|
43
|
+
toolsplice catalog [--modern] --url <url> [--out catalog.json] Capture all tools/list pages; accepts -- <command> [args...] for stdio
|
|
44
|
+
toolsplice impact <suite> --follow source|target --url <url> [--json] [--max-reports N]
|
|
45
|
+
Check the current catalog and recheck when the upstream signals a change.
|
|
46
|
+
toolsplice impact <suite.json|directory> [--source-contract file | --source-catalog file] [--target-contract file | --target-catalog file] [--candidate-result file] [--case name] [--json]
|
|
47
|
+
toolsplice test --from-recording <file> [--save-case <suite.json>] [--restorations <file>]
|
|
48
|
+
toolsplice evaluate --ledger <checkpoint-dir> Inspect all attempts and known spend\n toolsplice evaluate --init <new-suite.mjs> Create a runnable local evaluation driver\n toolsplice evaluate <trials.json> [--out policy.json] [--json]\n toolsplice evaluate --driver <trusted-suite.mjs> [--plan | --checkpoint dir [--retry-incomplete]] [--save-trials trials.json] [--out policy.json]\n toolsplice measure <recording.json> [--restorations <file>] [--json]
|
|
49
|
+
toolsplice init <dir> --source-catalog <file> --source server:tool --target-catalog <file> --target server:tool --fixture <file> [--fixture-format mcp] [--bind /destination=/source ...] [--set /destination=<json>] [--input <file>] [--each <array-pointer> [--max-items N]] [--result-path <pointer> | --result-fields <json-object>]
|
|
50
|
+
toolsplice init <new-directory> Create and check an offline starter; optionally --from-recording <file>
|
|
51
|
+
toolsplice project <directory> [--allow-review] Check project inputs/fixtures and mapped arguments offline
|
|
52
|
+
toolsplice correct <baseline.json> --correction <file> Validate a pinned correction and its fixtures offline
|
|
53
|
+
toolsplice proxy [options] -- <command> [args...] Learn from normal agent traffic; enrich descriptions automatically
|
|
54
|
+
toolsplice proxy [options] --url <http url> Wrap a Streamable HTTP server
|
|
55
|
+
toolsplice config --name <name> -- <command> [...] Print a ready-to-use MCP client configuration
|
|
56
|
+
toolsplice config --from <file> --server <name> Wrap one existing stdio config; retain its env and cwd
|
|
57
|
+
toolsplice probe [options] -- <command> [args...] Call tools marked read-only (annotations are hints)
|
|
58
|
+
toolsplice doctor [server] [--json] Diagnose learned types, unsupported text and stale exports
|
|
59
|
+
toolsplice show [server] Summarize learned outputs
|
|
60
|
+
toolsplice emit-ts <server> [--out file] Write types, or a callable .ts module with --runtime
|
|
61
|
+
toolsplice schema <server> <tool> [--lenient] Show the learned JSON Schema
|
|
62
|
+
toolsplice snapshot <server> --out <file> Save a reviewable contract baseline (new file only)
|
|
63
|
+
toolsplice check <server> --baseline <file> Compare current learning to a baseline; exit 2 on change
|
|
64
|
+
toolsplice forget <server> Delete this server's local learning (does not call the server)
|
|
65
|
+
|
|
66
|
+
Options:
|
|
67
|
+
--store <dir> Learning store (default: .mcp-shape, relative to this working directory)
|
|
68
|
+
--database-env <name> Read PostgreSQL URL from this environment variable (optional backend)
|
|
69
|
+
--database-timeout <ms> PostgreSQL pool/lock/statement deadline (50–60000; default: 1000)
|
|
70
|
+
--namespace <name> PostgreSQL project/tenant namespace (default: default)
|
|
71
|
+
--no-migrate PostgreSQL: require an already migrated schema
|
|
72
|
+
--name <name> Explicit server identity; use distinct names for different installations/accounts
|
|
73
|
+
--enrich <mode> description (default), none, or schema (experimental)
|
|
74
|
+
--min-samples <n> Responses needed before enrichment (default: 1)
|
|
75
|
+
--max-description <n> Extra description character budget (default: 2000, minimum: 80)
|
|
76
|
+
--timeout <ms> Upstream call timeout (default: 600000)
|
|
77
|
+
--upstream-cwd <dir> Working directory for an upstream stdio process
|
|
78
|
+
--bearer-env <name> HTTP: read bearer token from this environment variable, never from an argument
|
|
79
|
+
--args <file> Probe calls: { "tool": [ {args}, ... ] }; explicit calls may write data
|
|
80
|
+
--examples <policy> none (default), safe (heuristic, opt-in), all (opt-in)
|
|
81
|
+
--source-contract <file> splice: portable contract; replay: candidate source contract
|
|
82
|
+
--target-contract <file> splice: portable contract; replay: candidate target contract
|
|
83
|
+
--source-catalog <file> splice: use a saved tools/list catalog for the source
|
|
84
|
+
--target-catalog <file> splice: use a saved tools/list catalog for the target
|
|
85
|
+
--fixture <file> splice: dry-run a saved source output; never execute tools
|
|
86
|
+
--fixture-format <kind> splice: decoded (default) or mcp (raw tool-result envelope)
|
|
87
|
+
--context <file> splice fixture: per-call application context as JSON
|
|
88
|
+
--restorations <file> replay: private JSON-pointer/value map for every redacted path
|
|
89
|
+
--from-recording <file> init: scaffold a successful saved run; no provider calls
|
|
90
|
+
--correction <file> correct: explicit schema replacements with positive/negative fixtures
|
|
91
|
+
--summary splice JSON: counts and byte size instead of mapped argument values
|
|
92
|
+
--allow-review splice: exit 0 for a reviewed plan; blocked plans still exit 2
|
|
93
|
+
--baseline <file> check: reviewed Toolsplice contract snapshot
|
|
94
|
+
--fail-on <policy> check: any (default), or breaking (also fails changes needing review)
|
|
95
|
+
--tool <name> snapshot: include a recorded tool (repeat for several; default: whole server)
|
|
96
|
+
--runtime emit-ts: generate callable bindings (use a .ts output, not .d.ts)
|
|
97
|
+
--out <file> Write config (new file only) or TypeScript output
|
|
98
|
+
--quiet Suppress proxy diagnostics (protocol stdout stays clean)
|
|
99
|
+
--json Doctor/check: machine-readable report
|
|
100
|
+
--check Doctor: exit 2 for stale exports or schema warnings
|
|
101
|
+
--help, -h Show this help
|
|
102
|
+
`;
|
|
103
|
+
const options = {
|
|
104
|
+
"database-env": { type: "string" },
|
|
105
|
+
"database-timeout": { type: "string" },
|
|
106
|
+
namespace: { type: "string" },
|
|
107
|
+
"no-migrate": { type: "boolean" },
|
|
108
|
+
store: { type: "string" },
|
|
109
|
+
name: { type: "string" },
|
|
110
|
+
enrich: { type: "string" },
|
|
111
|
+
"min-samples": { type: "string" },
|
|
112
|
+
"max-description": { type: "string" },
|
|
113
|
+
timeout: { type: "string" },
|
|
114
|
+
"upstream-cwd": { type: "string" },
|
|
115
|
+
url: { type: "string" },
|
|
116
|
+
"bearer-env": { type: "string" },
|
|
117
|
+
args: { type: "string" },
|
|
118
|
+
examples: { type: "string" },
|
|
119
|
+
"source-contract": { type: "string" },
|
|
120
|
+
"source-catalog": { type: "string" },
|
|
121
|
+
"target-catalog": { type: "string" },
|
|
122
|
+
"target-contract": { type: "string" },
|
|
123
|
+
fixture: { type: "string" },
|
|
124
|
+
"fixture-format": { type: "string" },
|
|
125
|
+
context: { type: "string" },
|
|
126
|
+
restorations: { type: "string" },
|
|
127
|
+
"from-recording": { type: "string" },
|
|
128
|
+
junit: { type: "string" },
|
|
129
|
+
"candidate-result": { type: "string" },
|
|
130
|
+
"result-path": { type: "string" },
|
|
131
|
+
"result-fields": { type: "string" },
|
|
132
|
+
each: { type: "string" },
|
|
133
|
+
"max-items": { type: "string" },
|
|
134
|
+
modern: { type: "boolean" },
|
|
135
|
+
"with-tools": { type: "boolean" },
|
|
136
|
+
follow: { type: "string" },
|
|
137
|
+
"max-reports": { type: "string" },
|
|
138
|
+
case: { type: "string" },
|
|
139
|
+
"save-case": { type: "string" },
|
|
140
|
+
driver: { type: "string" },
|
|
141
|
+
checkpoint: { type: "string" },
|
|
142
|
+
ledger: { type: "string" },
|
|
143
|
+
"retry-incomplete": { type: "boolean" },
|
|
144
|
+
init: { type: "string" },
|
|
145
|
+
plan: { type: "boolean" },
|
|
146
|
+
"save-trials": { type: "string" },
|
|
147
|
+
source: { type: "string" },
|
|
148
|
+
target: { type: "string" },
|
|
149
|
+
input: { type: "string" },
|
|
150
|
+
bind: { type: "string", multiple: true },
|
|
151
|
+
set: { type: "string", multiple: true },
|
|
152
|
+
correction: { type: "string" },
|
|
153
|
+
baseline: { type: "string" },
|
|
154
|
+
"fail-on": { type: "string" },
|
|
155
|
+
tool: { type: "string", multiple: true },
|
|
156
|
+
out: { type: "string" },
|
|
157
|
+
from: { type: "string" },
|
|
158
|
+
server: { type: "string" },
|
|
159
|
+
quiet: { type: "boolean" },
|
|
160
|
+
runtime: { type: "boolean" },
|
|
161
|
+
json: { type: "boolean" },
|
|
162
|
+
summary: { type: "boolean" },
|
|
163
|
+
"allow-review": { type: "boolean" },
|
|
164
|
+
check: { type: "boolean" },
|
|
165
|
+
lenient: { type: "boolean" },
|
|
166
|
+
help: { type: "boolean", short: "h" },
|
|
167
|
+
version: { type: "boolean", short: "v" },
|
|
168
|
+
};
|
|
169
|
+
function parse(argv) {
|
|
170
|
+
const delimiter = argv.indexOf("--");
|
|
171
|
+
const own = delimiter >= 0 ? argv.slice(0, delimiter) : argv;
|
|
172
|
+
const command = own[0] && !own[0].startsWith("-") ? own.shift() : "help";
|
|
173
|
+
const parsed = parseArgs({
|
|
174
|
+
args: own,
|
|
175
|
+
options,
|
|
176
|
+
strict: true,
|
|
177
|
+
allowPositionals: true,
|
|
178
|
+
});
|
|
179
|
+
return {
|
|
180
|
+
command,
|
|
181
|
+
positional: parsed.positionals,
|
|
182
|
+
flags: parsed.values,
|
|
183
|
+
upstream: delimiter >= 0 ? argv.slice(delimiter + 1) : [],
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
const str = (v) => typeof v === "string" ? v : undefined;
|
|
187
|
+
function integer(flags, name, fallback, min = 1) {
|
|
188
|
+
const raw = str(flags[name]);
|
|
189
|
+
const value = raw === undefined ? fallback : Number(raw);
|
|
190
|
+
if (raw === "" || !Number.isSafeInteger(value) || value < min)
|
|
191
|
+
throw new Error(`--${name} must be an integer >= ${min}`);
|
|
192
|
+
return value;
|
|
193
|
+
}
|
|
194
|
+
function upstreamConnection(p) {
|
|
195
|
+
const url = str(p.flags.url);
|
|
196
|
+
if (url) {
|
|
197
|
+
if (p.upstream.length)
|
|
198
|
+
throw new Error("Choose either --url or an upstream command, not both.");
|
|
199
|
+
const parsed = new URL(url);
|
|
200
|
+
if (!["http:", "https:"].includes(parsed.protocol) ||
|
|
201
|
+
parsed.username ||
|
|
202
|
+
parsed.password)
|
|
203
|
+
throw new Error("--url must be http(s), without embedded credentials.");
|
|
204
|
+
const tokenName = str(p.flags["bearer-env"]);
|
|
205
|
+
const token = tokenName ? process.env[tokenName] : undefined;
|
|
206
|
+
if (tokenName && !token)
|
|
207
|
+
throw new Error(`Environment variable ${tokenName} is empty or not set.`);
|
|
208
|
+
return { kind: "http", url: parsed,
|
|
209
|
+
options: token ? { requestInit: { headers: { Authorization: `Bearer ${token}` } } } : undefined };
|
|
210
|
+
}
|
|
211
|
+
if (p.flags["bearer-env"])
|
|
212
|
+
throw new Error("--bearer-env requires --url");
|
|
213
|
+
if (!p.upstream.length)
|
|
214
|
+
throw new Error("Missing upstream: pass -- <command> [args...] or --url <url>.");
|
|
215
|
+
const [command, ...args] = p.upstream;
|
|
216
|
+
const env = Object.fromEntries(Object.entries(process.env).filter((x) => x[1] !== undefined));
|
|
217
|
+
// GUI clients often have a minimal PATH even when this CLI was launched with an absolute Node.
|
|
218
|
+
if (p.flags["database-env"])
|
|
219
|
+
delete env[String(p.flags["database-env"])];
|
|
220
|
+
env.PATH = `${dirname(process.execPath)}${delimiter}${env.PATH ?? ""}`;
|
|
221
|
+
return { kind: "stdio", params: {
|
|
222
|
+
command,
|
|
223
|
+
args,
|
|
224
|
+
cwd: str(p.flags["upstream-cwd"]),
|
|
225
|
+
env,
|
|
226
|
+
stderr: "inherit",
|
|
227
|
+
} };
|
|
228
|
+
}
|
|
229
|
+
function upstreamTransport(p) {
|
|
230
|
+
const connection = upstreamConnection(p);
|
|
231
|
+
return connection.kind === "http" ? new StreamableHTTPClientTransport(connection.url, connection.options)
|
|
232
|
+
: new StdioClientTransport(connection.params);
|
|
233
|
+
}
|
|
234
|
+
function config(p) {
|
|
235
|
+
const name = str(p.flags.server) ?? str(p.flags.name);
|
|
236
|
+
if (!name)
|
|
237
|
+
throw new Error("config needs --name <name> (or --server <existing-name> with --from).");
|
|
238
|
+
let entry = {};
|
|
239
|
+
let document;
|
|
240
|
+
let upstream = p.upstream;
|
|
241
|
+
const from = str(p.flags.from);
|
|
242
|
+
if (from) {
|
|
243
|
+
if (upstream.length || p.flags.url)
|
|
244
|
+
throw new Error("--from cannot be combined with an upstream command or --url.");
|
|
245
|
+
const contents = JSON.parse(readFileSync(from, "utf8"));
|
|
246
|
+
document = contents;
|
|
247
|
+
const original = contents?.mcpServers?.[name];
|
|
248
|
+
if (!original ||
|
|
249
|
+
typeof original.command !== "string" ||
|
|
250
|
+
![undefined, "stdio"].includes(original.type))
|
|
251
|
+
throw new Error(`No stdio MCP entry named ${JSON.stringify(name)} in --from file.`);
|
|
252
|
+
if (original.args !== undefined &&
|
|
253
|
+
(!Array.isArray(original.args) ||
|
|
254
|
+
original.args.some((a) => typeof a !== "string")))
|
|
255
|
+
throw new Error("Existing entry.args must be a string array.");
|
|
256
|
+
if (original.args?.includes(fileURLToPath(import.meta.url)))
|
|
257
|
+
throw new Error("This entry is already wrapped by this toolsplice installation.");
|
|
258
|
+
const { command, args, ...rest } = original;
|
|
259
|
+
entry = { ...rest };
|
|
260
|
+
upstream = [command, ...(args ?? [])];
|
|
261
|
+
}
|
|
262
|
+
if (!upstream.length && !p.flags.url)
|
|
263
|
+
throw new Error("config needs an upstream command, --url, or --from.");
|
|
264
|
+
const cli = fileURLToPath(import.meta.url);
|
|
265
|
+
const executable = cli.endsWith(".ts")
|
|
266
|
+
? ["--import", import.meta.resolve("tsx"), cli]
|
|
267
|
+
: [cli];
|
|
268
|
+
const storageArgs = p.flags["database-env"]
|
|
269
|
+
? [
|
|
270
|
+
"--database-env",
|
|
271
|
+
String(p.flags["database-env"]),
|
|
272
|
+
"--namespace",
|
|
273
|
+
str(p.flags.namespace) ?? "default",
|
|
274
|
+
...(p.flags["no-migrate"] ? ["--no-migrate"] : []),
|
|
275
|
+
]
|
|
276
|
+
: ["--store", resolve(str(p.flags.store) ?? ".mcp-shape")];
|
|
277
|
+
const args = [
|
|
278
|
+
...executable,
|
|
279
|
+
"proxy",
|
|
280
|
+
"--name",
|
|
281
|
+
name,
|
|
282
|
+
...storageArgs,
|
|
283
|
+
"--examples",
|
|
284
|
+
str(p.flags.examples) ?? "none",
|
|
285
|
+
];
|
|
286
|
+
for (const [flag, value] of [
|
|
287
|
+
["--enrich", str(p.flags.enrich)],
|
|
288
|
+
["--min-samples", str(p.flags["min-samples"])],
|
|
289
|
+
["--max-description", str(p.flags["max-description"])],
|
|
290
|
+
["--timeout", str(p.flags.timeout)],
|
|
291
|
+
["--database-timeout", str(p.flags["database-timeout"])],
|
|
292
|
+
[
|
|
293
|
+
"--upstream-cwd",
|
|
294
|
+
str(p.flags["upstream-cwd"]) ??
|
|
295
|
+
(typeof entry.cwd === "string" ? entry.cwd : undefined),
|
|
296
|
+
],
|
|
297
|
+
["--url", str(p.flags.url)],
|
|
298
|
+
["--bearer-env", str(p.flags["bearer-env"])],
|
|
299
|
+
])
|
|
300
|
+
if (value)
|
|
301
|
+
args.push(flag, value);
|
|
302
|
+
if (upstream.length)
|
|
303
|
+
args.push("--", ...upstream);
|
|
304
|
+
const servers = document?.mcpServers;
|
|
305
|
+
const output = JSON.stringify({
|
|
306
|
+
...document,
|
|
307
|
+
mcpServers: {
|
|
308
|
+
...servers,
|
|
309
|
+
[name]: { ...entry, command: process.execPath, args },
|
|
310
|
+
},
|
|
311
|
+
}, null, 2) + "\n";
|
|
312
|
+
const out = str(p.flags.out);
|
|
313
|
+
if (out)
|
|
314
|
+
writeFileSync(out, output, { mode: 0o600, flag: "wx" });
|
|
315
|
+
else
|
|
316
|
+
process.stdout.write(output);
|
|
317
|
+
}
|
|
318
|
+
async function runSplice(p, requireServer) {
|
|
319
|
+
const path = p.positional[0];
|
|
320
|
+
if (!path)
|
|
321
|
+
throw new Error("splice needs a plan.json path.");
|
|
322
|
+
const plan = parseSpliceSpec(readFileSync(path, "utf8"));
|
|
323
|
+
const endpointContract = async (endpoint, side) => {
|
|
324
|
+
const contractFile = str(p.flags[`${side}-contract`]), catalogFile = str(p.flags[`${side}-catalog`]);
|
|
325
|
+
if (contractFile)
|
|
326
|
+
return parseContractSnapshot(readFileSync(contractFile, "utf8"));
|
|
327
|
+
if (catalogFile) {
|
|
328
|
+
let catalog;
|
|
329
|
+
try {
|
|
330
|
+
catalog = JSON.parse(readFileSync(catalogFile, "utf8"));
|
|
331
|
+
}
|
|
332
|
+
catch {
|
|
333
|
+
throw new Error("Catalog must be a readable JSON file.");
|
|
334
|
+
}
|
|
335
|
+
return createContractFromCatalog({ name: endpoint.server }, catalog, { tools: [endpoint.tool] });
|
|
336
|
+
}
|
|
337
|
+
return createContractSnapshot(await requireServer(endpoint.server), {
|
|
338
|
+
tools: [endpoint.tool],
|
|
339
|
+
});
|
|
340
|
+
};
|
|
341
|
+
const source = await endpointContract(plan.source, "source"), target = await endpointContract(plan.target, "target");
|
|
342
|
+
const prepared = prepareSplice(plan, source, target), fixture = str(p.flags.fixture), fixtureFormat = str(p.flags["fixture-format"]) ?? "decoded";
|
|
343
|
+
if (fixtureFormat !== "decoded" && fixtureFormat !== "mcp")
|
|
344
|
+
throw new Error("--fixture-format must be decoded or mcp.");
|
|
345
|
+
const contextFile = str(p.flags.context);
|
|
346
|
+
if (contextFile && !fixture)
|
|
347
|
+
throw new Error("--context requires --fixture.");
|
|
348
|
+
let context;
|
|
349
|
+
if (contextFile) {
|
|
350
|
+
try {
|
|
351
|
+
context = JSON.parse(readFileSync(contextFile, "utf8"));
|
|
352
|
+
}
|
|
353
|
+
catch {
|
|
354
|
+
throw new Error("Context must be a readable JSON file.");
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
let mappedArguments;
|
|
358
|
+
let fixtureFailure;
|
|
359
|
+
if (fixture && prepared.report.status !== "blocked") {
|
|
360
|
+
let value;
|
|
361
|
+
try {
|
|
362
|
+
value = JSON.parse(readFileSync(fixture, "utf8"));
|
|
363
|
+
}
|
|
364
|
+
catch {
|
|
365
|
+
throw new Error("Fixture must be a readable JSON file.");
|
|
366
|
+
}
|
|
367
|
+
if (fixtureFormat === "mcp") {
|
|
368
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
369
|
+
throw new Error("An MCP fixture must contain a tool-result object.");
|
|
370
|
+
try {
|
|
371
|
+
if ("resultType" in value &&
|
|
372
|
+
value.resultType !== undefined &&
|
|
373
|
+
value.resultType !== "complete")
|
|
374
|
+
throw new Error("Non-complete result.");
|
|
375
|
+
value = decode(value);
|
|
376
|
+
}
|
|
377
|
+
catch {
|
|
378
|
+
fixtureFailure = {
|
|
379
|
+
stage: "source",
|
|
380
|
+
issues: [
|
|
381
|
+
{
|
|
382
|
+
severity: "error",
|
|
383
|
+
code: "fixture-tool-error",
|
|
384
|
+
path: "/fixture",
|
|
385
|
+
message: "The saved MCP result reports a tool failure.",
|
|
386
|
+
},
|
|
387
|
+
],
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
if (!fixtureFailure)
|
|
392
|
+
try {
|
|
393
|
+
mappedArguments = await prepared.mapOutput(value, { context });
|
|
394
|
+
}
|
|
395
|
+
catch (error) {
|
|
396
|
+
if (!(error instanceof SpliceError))
|
|
397
|
+
throw error;
|
|
398
|
+
fixtureFailure = {
|
|
399
|
+
stage: error.stage,
|
|
400
|
+
issues: error.issues,
|
|
401
|
+
explanation: explainSpliceError(plan, error),
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
const report = {
|
|
406
|
+
...prepared.report,
|
|
407
|
+
preflightStatus: prepared.report.status,
|
|
408
|
+
status: fixtureFailure ? "blocked" : prepared.report.status,
|
|
409
|
+
issues: fixtureFailure
|
|
410
|
+
? [...prepared.report.issues, ...fixtureFailure.issues]
|
|
411
|
+
: prepared.report.issues,
|
|
412
|
+
...(fixtureFailure
|
|
413
|
+
? { fixture: { valid: false, ...fixtureFailure } }
|
|
414
|
+
: mappedArguments === undefined
|
|
415
|
+
? {}
|
|
416
|
+
: { fixture: { valid: true } }),
|
|
417
|
+
...(mappedArguments === undefined
|
|
418
|
+
? {}
|
|
419
|
+
: {
|
|
420
|
+
mappingSummary: {
|
|
421
|
+
rows: mappedArguments.length,
|
|
422
|
+
argumentBytes: mappedArguments.reduce((n, row) => n + Buffer.byteLength(JSON.stringify(row)), 0),
|
|
423
|
+
},
|
|
424
|
+
...(p.flags.summary ? {} : { mappedArguments }),
|
|
425
|
+
}),
|
|
426
|
+
};
|
|
427
|
+
const out = str(p.flags.out);
|
|
428
|
+
if (out && (!out.endsWith(".ts") || out.endsWith(".d.ts")))
|
|
429
|
+
throw new Error("splice --out needs a .ts source file.");
|
|
430
|
+
if (out && report.status !== "blocked")
|
|
431
|
+
writeFileSync(out, emitSpliceModule(plan, source, target), {
|
|
432
|
+
mode: 0o600,
|
|
433
|
+
flag: "wx",
|
|
434
|
+
});
|
|
435
|
+
if (p.flags.json)
|
|
436
|
+
process.stdout.write(JSON.stringify(report, null, 2) + "\n");
|
|
437
|
+
else {
|
|
438
|
+
process.stdout.write(`${JSON.stringify(plan.source.server + "/" + plan.source.tool)} → ${JSON.stringify(plan.target.server + "/" + plan.target.tool)}: ${report.status}\n`);
|
|
439
|
+
for (const issue of report.issues)
|
|
440
|
+
process.stdout.write(` [${issue.severity}] ${issue.code} ${JSON.stringify(issue.path)}: ${issue.message}\n`);
|
|
441
|
+
process.stdout.write(` At most ${report.maxTargetCalls} target call(s); no tools called by this command.\n`);
|
|
442
|
+
if (mappedArguments !== undefined)
|
|
443
|
+
process.stdout.write(` Fixture produced ${mappedArguments.length} validated argument object(s).\n`);
|
|
444
|
+
for (const issue of fixtureFailure?.explanation?.issues ?? [])
|
|
445
|
+
for (const field of issue.fields)
|
|
446
|
+
process.stdout.write(` Binding ${field.bindingIndex}: ${field.origin} ${JSON.stringify(field.pointer ?? "(literal)")}${field.rowIndex === undefined ? "" : ` in row ${field.rowIndex}`} → destination ${JSON.stringify(field.targetPointer)}.\n`);
|
|
447
|
+
if (out && report.status !== "blocked")
|
|
448
|
+
process.stdout.write(` Adapter written to ${JSON.stringify(out)}.\n`);
|
|
449
|
+
}
|
|
450
|
+
if (report.status === "blocked" ||
|
|
451
|
+
(report.status === "review" && !p.flags["allow-review"]))
|
|
452
|
+
process.exitCode = 2;
|
|
453
|
+
}
|
|
454
|
+
async function runOfflineWorkflow(p) {
|
|
455
|
+
if (p.flags.store ||
|
|
456
|
+
p.flags["database-env"] ||
|
|
457
|
+
p.upstream.length ||
|
|
458
|
+
p.flags.url)
|
|
459
|
+
throw new Error("replay/correct use artifact files only; no stores, upstream commands or connections.");
|
|
460
|
+
const file = p.positional[0];
|
|
461
|
+
if (!file || p.positional.length !== 1)
|
|
462
|
+
throw new Error(`${p.command} needs one artifact path.`);
|
|
463
|
+
const read = (path) => {
|
|
464
|
+
try {
|
|
465
|
+
return parseWorkflowJson(readFileSync(path, "utf8"));
|
|
466
|
+
}
|
|
467
|
+
catch {
|
|
468
|
+
throw new Error("Workflow artifact must be a readable bounded JSON file.");
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
let report;
|
|
472
|
+
if (p.command === "replay") {
|
|
473
|
+
if (p.flags.correction)
|
|
474
|
+
throw new Error("--correction is for correct, not replay.");
|
|
475
|
+
if (p.flags["source-catalog"] || p.flags["target-catalog"])
|
|
476
|
+
throw new Error("Candidate replay needs contract snapshots, not raw catalogs.");
|
|
477
|
+
const restorations = str(p.flags.restorations);
|
|
478
|
+
const replay = await replaySpliceRecording(read(file), {
|
|
479
|
+
...(restorations
|
|
480
|
+
? { restorations: read(restorations) }
|
|
481
|
+
: {}),
|
|
482
|
+
...(str(p.flags["source-contract"])
|
|
483
|
+
? {
|
|
484
|
+
sourceContract: parseContractSnapshot(read(str(p.flags["source-contract"]))),
|
|
485
|
+
}
|
|
486
|
+
: {}),
|
|
487
|
+
...(str(p.flags["target-contract"])
|
|
488
|
+
? {
|
|
489
|
+
targetContract: parseContractSnapshot(read(str(p.flags["target-contract"]))),
|
|
490
|
+
}
|
|
491
|
+
: {}),
|
|
492
|
+
...(p.flags["allow-review"] ? { allowReview: true } : {}),
|
|
493
|
+
});
|
|
494
|
+
const { result, ...summary } = replay;
|
|
495
|
+
report = {
|
|
496
|
+
...summary,
|
|
497
|
+
...(result
|
|
498
|
+
? {
|
|
499
|
+
resultSummary: {
|
|
500
|
+
count: result.length,
|
|
501
|
+
bytes: Buffer.byteLength(JSON.stringify(result)),
|
|
502
|
+
},
|
|
503
|
+
}
|
|
504
|
+
: {}),
|
|
505
|
+
};
|
|
506
|
+
if (!replay.matched ||
|
|
507
|
+
(replay.upgrade && replay.upgrade.status !== "passed"))
|
|
508
|
+
process.exitCode = 2;
|
|
509
|
+
if (p.flags.out)
|
|
510
|
+
writeFileSync(str(p.flags.out), JSON.stringify(report, null, 2) + "\n", {
|
|
511
|
+
mode: 0o600,
|
|
512
|
+
flag: "wx",
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
else {
|
|
516
|
+
if (p.flags.restorations)
|
|
517
|
+
throw new Error("--restorations is for replay, not correct.");
|
|
518
|
+
const manifestFile = str(p.flags.correction);
|
|
519
|
+
if (!manifestFile)
|
|
520
|
+
throw new Error("correct requires --correction <manifest.json>.");
|
|
521
|
+
const result = await applyContractCorrection(parseContractSnapshot(read(file)), parseContractCorrection(read(manifestFile)));
|
|
522
|
+
const out = str(p.flags.out);
|
|
523
|
+
if (out) {
|
|
524
|
+
const contents = JSON.stringify(result.corrected, null, 2) + "\n";
|
|
525
|
+
if (Buffer.byteLength(contents) > JSON_LIMIT)
|
|
526
|
+
throw new Error("Serialized corrected contract exceeds the 5 MiB limit.");
|
|
527
|
+
writeFileSync(out, contents, {
|
|
528
|
+
mode: 0o600,
|
|
529
|
+
flag: "wx",
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
report = {
|
|
533
|
+
status: out ? "written" : "validated",
|
|
534
|
+
baseFingerprint: result.original.fingerprint,
|
|
535
|
+
correctedFingerprint: result.corrected.fingerprint,
|
|
536
|
+
correction: result.corrected.correction,
|
|
537
|
+
fixtures: result.fixtures,
|
|
538
|
+
comparison: result.comparison,
|
|
539
|
+
networkCalls: 0,
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
if (p.flags.json)
|
|
543
|
+
process.stdout.write(JSON.stringify(report, null, 2) + "\n");
|
|
544
|
+
else if (p.command === "replay") {
|
|
545
|
+
process.stdout.write(`Replay ${report.matched ? "matched" : "did not match"} the saved outcome; ${report.consumedCalls}/${report.recordedCalls} recorded call(s) consumed, zero network calls.\n`);
|
|
546
|
+
if (report.upgrade)
|
|
547
|
+
process.stdout.write(`Candidate fixture check: ${report.upgrade.status}.\n`);
|
|
548
|
+
}
|
|
549
|
+
else
|
|
550
|
+
process.stdout.write(`Correction ${report.status}; all positive/negative fixtures passed, zero network calls.\n`);
|
|
551
|
+
}
|
|
552
|
+
async function runProject(p) {
|
|
553
|
+
if (p.flags.store ||
|
|
554
|
+
p.flags["database-env"] ||
|
|
555
|
+
p.upstream.length ||
|
|
556
|
+
p.flags.url)
|
|
557
|
+
throw new Error("init/project use local artifacts only; no stores or upstream connections.");
|
|
558
|
+
if (p.positional.length !== 1)
|
|
559
|
+
throw new Error(`${p.command} needs one directory.`);
|
|
560
|
+
if (p.flags["source-contract"] ||
|
|
561
|
+
p.flags["target-contract"] ||
|
|
562
|
+
p.flags["source-catalog"] ||
|
|
563
|
+
p.flags["target-catalog"])
|
|
564
|
+
throw new Error("Projects use their saved contract files; use replay with candidate contracts to check an upgrade.");
|
|
565
|
+
if (p.flags.out)
|
|
566
|
+
throw new Error("init/project write only the new project directory or print a check report.");
|
|
567
|
+
if (p.command === "project") {
|
|
568
|
+
if (p.flags["from-recording"] || p.flags.restorations)
|
|
569
|
+
throw new Error("--from-recording and --restorations are for init/replay.");
|
|
570
|
+
const report = await checkSpliceProject(p.positional[0]);
|
|
571
|
+
if (report.status === "blocked" ||
|
|
572
|
+
(report.status === "review" && !p.flags["allow-review"]))
|
|
573
|
+
process.exitCode = 2;
|
|
574
|
+
process.stdout.write(p.flags.json
|
|
575
|
+
? JSON.stringify(report, null, 2) + "\n"
|
|
576
|
+
: `Project ${report.status}; zero tool/network calls.\n`);
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
const from = str(p.flags["from-recording"]), restore = str(p.flags.restorations);
|
|
580
|
+
const read = (file) => {
|
|
581
|
+
try {
|
|
582
|
+
return parseWorkflowJson(readFileSync(file, "utf8"));
|
|
583
|
+
}
|
|
584
|
+
catch {
|
|
585
|
+
throw new Error("Project source must be a readable bounded JSON artifact.");
|
|
586
|
+
}
|
|
587
|
+
};
|
|
588
|
+
const result = await initializeSpliceProject(p.positional[0], {
|
|
589
|
+
...(from
|
|
590
|
+
? {
|
|
591
|
+
recording: read(from),
|
|
592
|
+
}
|
|
593
|
+
: {}),
|
|
594
|
+
...(restore
|
|
595
|
+
? { restorations: read(restore) }
|
|
596
|
+
: {}),
|
|
597
|
+
});
|
|
598
|
+
const report = {
|
|
599
|
+
...result,
|
|
600
|
+
nextArgs: ["project", result.directory, "--allow-review", "--json"],
|
|
601
|
+
networkCalls: 0,
|
|
602
|
+
toolCalls: 0,
|
|
603
|
+
};
|
|
604
|
+
process.stdout.write(p.flags.json
|
|
605
|
+
? JSON.stringify(report, null, 2) + "\n"
|
|
606
|
+
: `Created ${result.origin} starter in ${JSON.stringify(result.directory)}.\nCheck it with toolsplice project <directory> --allow-review --json. No tools were called.\n`);
|
|
607
|
+
}
|
|
608
|
+
const ROUTE_FILE_LIMIT = 96 * 1024 * 1024;
|
|
609
|
+
function explainRoute(row) {
|
|
610
|
+
if (row.holdout && !row.holdout.reasons.length)
|
|
611
|
+
return "passed fit and holdout";
|
|
612
|
+
const phase = row.holdout ? "holdout" : "fit";
|
|
613
|
+
const candidates = row.holdout ? [row.holdout] : row.fit;
|
|
614
|
+
return candidates.length
|
|
615
|
+
? phase + " " + candidates.map(c => c.route + " (" + c.reasons.join(", ") + ")").join(", ")
|
|
616
|
+
: "no candidate trials";
|
|
617
|
+
}
|
|
618
|
+
async function readRouteReceipt(file) {
|
|
619
|
+
if (!statSync(file).isFile())
|
|
620
|
+
throw new Error("Expected a local route-trial JSON file.");
|
|
621
|
+
const chunks = [];
|
|
622
|
+
let count = 0;
|
|
623
|
+
for await (const chunk of createReadStream(file)) {
|
|
624
|
+
count += chunk.length;
|
|
625
|
+
if (count > ROUTE_FILE_LIMIT)
|
|
626
|
+
throw new Error("Route receipt exceeds 96 MiB.");
|
|
627
|
+
chunks.push(chunk);
|
|
628
|
+
}
|
|
629
|
+
try {
|
|
630
|
+
return JSON.parse(Buffer.concat(chunks, count).toString("utf8"));
|
|
631
|
+
}
|
|
632
|
+
catch {
|
|
633
|
+
throw new Error("Invalid route-trial JSON.");
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
function readLocalJson(file) {
|
|
637
|
+
const stat = statSync(file);
|
|
638
|
+
if (!stat.isFile() || stat.size > JSON_LIMIT)
|
|
639
|
+
throw new Error("Expected a JSON file up to 5 MiB.");
|
|
640
|
+
return parseWorkflowJson(readFileSync(file, "utf8"));
|
|
641
|
+
}
|
|
642
|
+
function validateFlags(p, allowed) {
|
|
643
|
+
if (p.upstream.length || Object.keys(p.flags).some(key => !allowed.includes(key)))
|
|
644
|
+
throw new Error("Unsupported option for this offline command. See toolsplice --help.");
|
|
645
|
+
}
|
|
646
|
+
function endpoint(label, side) {
|
|
647
|
+
const split = label?.indexOf(":") ?? -1;
|
|
648
|
+
if (!label || split < 1 || split === label.length - 1)
|
|
649
|
+
throw new Error(`Choose the endpoint with --${side} server:tool.`);
|
|
650
|
+
return { server: label.slice(0, split), tool: label.slice(split + 1) };
|
|
651
|
+
}
|
|
652
|
+
async function initFromCatalogs(p) {
|
|
653
|
+
validateFlags(p, ["source", "target", "source-catalog", "target-catalog", "fixture", "fixture-format", "input", "bind", "set", "result-path", "result-fields", "each", "max-items", "json"]);
|
|
654
|
+
if (p.positional.length !== 1)
|
|
655
|
+
throw new Error("init requires one new project directory.");
|
|
656
|
+
const read = (flag) => {
|
|
657
|
+
const file = str(p.flags[flag]);
|
|
658
|
+
if (!file)
|
|
659
|
+
throw new Error(`Catalog setup requires --${flag} <file>.`);
|
|
660
|
+
return readLocalJson(file);
|
|
661
|
+
};
|
|
662
|
+
if (!p.flags.source && !p.flags.target && !p.flags.bind && !p.flags.set && p.flags["result-path"] === undefined && p.flags["result-fields"] === undefined && p.flags.each === undefined && p.flags["max-items"] === undefined) {
|
|
663
|
+
const sourceTools = catalogToolNames(read("source-catalog"));
|
|
664
|
+
const targetTools = catalogToolNames(read("target-catalog"));
|
|
665
|
+
process.stdout.write(JSON.stringify({ sourceTools, targetTools,
|
|
666
|
+
next: "Choose --source server:tool and --target server:tool, then supply --fixture <file>." }, null, 2) + "\n");
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
const config = {
|
|
670
|
+
source: endpoint(str(p.flags.source), "source"), target: { ...endpoint(str(p.flags.target), "target"),
|
|
671
|
+
...(p.flags["result-path"] !== undefined ? { resultPath: str(p.flags["result-path"]) } : {}),
|
|
672
|
+
...(p.flags["result-fields"] !== undefined ? { resultFields: parseWorkflowJson(str(p.flags["result-fields"])) } : {}) },
|
|
673
|
+
sourceCatalog: read("source-catalog"),
|
|
674
|
+
targetCatalog: read("target-catalog"),
|
|
675
|
+
fixture: read("fixture"), fixtureFormat: (str(p.flags["fixture-format"]) ?? "decoded"),
|
|
676
|
+
...(p.flags.each !== undefined ? { each: str(p.flags.each) } : {}),
|
|
677
|
+
...(p.flags["max-items"] !== undefined ? { maxItems: integer(p.flags, "max-items", 100) } : {}),
|
|
678
|
+
bindings: [
|
|
679
|
+
...(p.flags.bind ?? []).map(parseCatalogBinding),
|
|
680
|
+
...(p.flags.set ?? []).map(text => {
|
|
681
|
+
const index = text.indexOf("=");
|
|
682
|
+
if (index < 0)
|
|
683
|
+
throw new Error("Use --set '/destination=<JSON literal>'.");
|
|
684
|
+
return { to: text.slice(0, index), value: parseWorkflowJson(text.slice(index + 1)) };
|
|
685
|
+
}),
|
|
686
|
+
],
|
|
687
|
+
...(p.flags.input ? { input: read("input") } : {}),
|
|
688
|
+
};
|
|
689
|
+
if (!config.bindings.length) {
|
|
690
|
+
const preview = inspectCatalogMapping(config);
|
|
691
|
+
process.stdout.write(JSON.stringify({ ...preview, next: "Repeat with --bind '/destination=/source' for each mapping." }, null, 2) + "\n");
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
let result;
|
|
695
|
+
try {
|
|
696
|
+
result = await initializeSpliceProject(p.positional[0], { catalogs: config });
|
|
697
|
+
}
|
|
698
|
+
catch (error) {
|
|
699
|
+
if (error instanceof SpliceError) {
|
|
700
|
+
const issues = error.issues.map(issue => issue.code + " " + JSON.stringify(issue.path)).join(", ");
|
|
701
|
+
throw new Error(`Catalog mapping failed at ${error.stage}: ${issues}. Check the sample and bindings.`);
|
|
702
|
+
}
|
|
703
|
+
throw error;
|
|
704
|
+
}
|
|
705
|
+
process.stdout.write(p.flags.json ? JSON.stringify(result, null, 2) + "\n" :
|
|
706
|
+
`Created ${JSON.stringify(result.directory)}. Review tests.json, then run toolsplice test ${JSON.stringify(result.directory)}.\n`);
|
|
707
|
+
}
|
|
708
|
+
function readSuite(path) {
|
|
709
|
+
const read = readLocalJson;
|
|
710
|
+
const file = statSync(path).isDirectory() ? resolve(path, "tests.json") : path;
|
|
711
|
+
const suite = read(file);
|
|
712
|
+
if (!suite || typeof suite !== "object" || Array.isArray(suite))
|
|
713
|
+
throw new Error("Expected a test suite object.");
|
|
714
|
+
const base = realpathSync(dirname(file));
|
|
715
|
+
const readReference = (path) => {
|
|
716
|
+
const ref = realpathSync(resolve(base, path));
|
|
717
|
+
const name = relative(base, ref);
|
|
718
|
+
if (!name || name === ".." || name.startsWith(".." + sep) || isAbsolute(name))
|
|
719
|
+
throw new Error("Suite references must remain inside the suite directory.");
|
|
720
|
+
return read(ref);
|
|
721
|
+
};
|
|
722
|
+
for (const field of ["plan", "sourceContract", "targetContract"]) {
|
|
723
|
+
if (typeof suite[field] === "string")
|
|
724
|
+
suite[field] = readReference(suite[field]);
|
|
725
|
+
}
|
|
726
|
+
if (Array.isArray(suite.cases)) {
|
|
727
|
+
if (suite.cases.length > 100)
|
|
728
|
+
throw new Error("Suite exceeds 100 cases.");
|
|
729
|
+
let bytes = 0;
|
|
730
|
+
for (const c of suite.cases) {
|
|
731
|
+
if (!c || typeof c.sourceFixture !== "string")
|
|
732
|
+
continue;
|
|
733
|
+
if (c.mappingOnly !== true || Object.hasOwn(c, "sourceResult"))
|
|
734
|
+
throw new Error("Invalid mapping fixture reference.");
|
|
735
|
+
const fixture = readReference(c.sourceFixture);
|
|
736
|
+
bytes += Buffer.byteLength(JSON.stringify(fixture));
|
|
737
|
+
if (bytes > JSON_LIMIT)
|
|
738
|
+
throw new Error("Suite fixtures exceed 5 MiB.");
|
|
739
|
+
c.sourceResult = { structuredContent: fixture };
|
|
740
|
+
delete c.sourceFixture;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
return suite;
|
|
744
|
+
}
|
|
745
|
+
function writeCatalog(path, text, limit = JSON_LIMIT) {
|
|
746
|
+
if (Buffer.byteLength(text) > limit)
|
|
747
|
+
throw new Error(limit === JSON_LIMIT ? "Catalog artifact exceeds 5 MiB." : "Route artifact exceeds 96 MiB.");
|
|
748
|
+
const temp = resolve(dirname(path), ".toolsplice-" + randomUUID() + ".tmp");
|
|
749
|
+
const fd = openSync(temp, "wx", 0o600);
|
|
750
|
+
try {
|
|
751
|
+
try {
|
|
752
|
+
writeFileSync(fd, text);
|
|
753
|
+
}
|
|
754
|
+
finally {
|
|
755
|
+
closeSync(fd);
|
|
756
|
+
}
|
|
757
|
+
linkSync(temp, path);
|
|
758
|
+
}
|
|
759
|
+
finally {
|
|
760
|
+
unlinkSync(temp);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
async function modernConnection(p) {
|
|
764
|
+
const connection = upstreamConnection(p);
|
|
765
|
+
const sdk = await import("@modelcontextprotocol/client").catch(() => {
|
|
766
|
+
throw new Error("Install @modelcontextprotocol/client 2.x alongside toolsplice for modern discovery.");
|
|
767
|
+
});
|
|
768
|
+
const client = new sdk.Client({ name: "toolsplice", version: VERSION }, {
|
|
769
|
+
versionNegotiation: { mode: "auto" }, listMaxPages: 1000,
|
|
770
|
+
});
|
|
771
|
+
const transport = connection.kind === "http"
|
|
772
|
+
? new sdk.StreamableHTTPClientTransport(connection.url, connection.options)
|
|
773
|
+
: new (await import("@modelcontextprotocol/client/stdio")).StdioClientTransport(connection.params);
|
|
774
|
+
return { client, transport };
|
|
775
|
+
}
|
|
776
|
+
async function readModernCatalog(client, signal, timeout) {
|
|
777
|
+
if (!client.getServerCapabilities()?.tools)
|
|
778
|
+
return { tools: [] };
|
|
779
|
+
// Explicit pages enforce cursor and size limits before acquiring the next page.
|
|
780
|
+
const deadline = AbortSignal.any([signal, AbortSignal.timeout(timeout)]);
|
|
781
|
+
const catalog = await collectToolCatalog(cursor => client.request({
|
|
782
|
+
method: "tools/list", ...(cursor === undefined ? {} : { params: { cursor } }),
|
|
783
|
+
}, { signal: deadline, timeout }));
|
|
784
|
+
if (client.getProtocolEra() === "modern")
|
|
785
|
+
catalog.tools = catalog.tools.filter(tool => validMcpHeaderSchema(tool.inputSchema));
|
|
786
|
+
return catalog;
|
|
787
|
+
}
|
|
788
|
+
async function modernDiscovery(p, signal, timeout) {
|
|
789
|
+
const { client, transport } = await modernConnection(p);
|
|
790
|
+
try {
|
|
791
|
+
await client.connect(transport, { signal, timeout });
|
|
792
|
+
const catalog = p.command === "catalog" || p.flags["with-tools"]
|
|
793
|
+
? await readModernCatalog(client, signal, timeout) : undefined;
|
|
794
|
+
if (p.command === "catalog")
|
|
795
|
+
return catalog;
|
|
796
|
+
const discover = client.getDiscoverResult();
|
|
797
|
+
const version = client.getNegotiatedProtocolVersion();
|
|
798
|
+
return {
|
|
799
|
+
format: "toolsplice-discovery", formatVersion: 1,
|
|
800
|
+
method: discover ? "server/discover" : "initialize", negotiatedVersion: version,
|
|
801
|
+
supportedVersions: discover?.supportedVersions ?? [version],
|
|
802
|
+
serverInfo: client.getServerVersion() ?? null, capabilities: client.getServerCapabilities() ?? {},
|
|
803
|
+
...catalog, ...(discover ? { ttlMs: discover.ttlMs, cacheScope: discover.cacheScope } : {}),
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
finally {
|
|
807
|
+
await client.close().catch(() => { });
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
/** One CLI-owned, acknowledged subscription. A changed list is a level trigger. */
|
|
811
|
+
async function followCatalogImpact(p) {
|
|
812
|
+
class SubscriptionError extends Error {
|
|
813
|
+
}
|
|
814
|
+
const allowed = new Set(["follow", "max-reports", "url", "bearer-env", "upstream-cwd", "timeout", "json"]);
|
|
815
|
+
const side = str(p.flags.follow);
|
|
816
|
+
if (p.positional.length !== 1 || (side !== "source" && side !== "target") ||
|
|
817
|
+
Object.keys(p.flags).some(key => !allowed.has(key)))
|
|
818
|
+
throw new Error("impact --follow needs a suite, source or target, and an upstream connection.");
|
|
819
|
+
const limit = integer(p.flags, "max-reports", Number.MAX_SAFE_INTEGER);
|
|
820
|
+
const timeout = integer(p.flags, "timeout", 30_000);
|
|
821
|
+
if (timeout > 2_147_483_647)
|
|
822
|
+
throw new Error("--timeout exceeds the supported timer range.");
|
|
823
|
+
const suite = readSuite(p.positional[0]);
|
|
824
|
+
const { client, transport } = await modernConnection(p);
|
|
825
|
+
const stop = new AbortController();
|
|
826
|
+
const cancel = () => stop.abort();
|
|
827
|
+
process.once("SIGINT", cancel);
|
|
828
|
+
process.once("SIGTERM", cancel);
|
|
829
|
+
let pending = false;
|
|
830
|
+
let ended = false;
|
|
831
|
+
let wake;
|
|
832
|
+
client.setNotificationHandler("notifications/tools/list_changed", () => { pending = true; wake?.(); });
|
|
833
|
+
try {
|
|
834
|
+
await client.connect(transport, { signal: stop.signal, timeout });
|
|
835
|
+
if (!client.getServerCapabilities()?.tools?.listChanged || client.getProtocolEra() !== "modern")
|
|
836
|
+
throw new SubscriptionError("This endpoint needs modern tools.listChanged support. Capture a catalog for a one-time impact check.");
|
|
837
|
+
const sub = await client.listen({ toolsListChanged: true }, { signal: stop.signal, timeout });
|
|
838
|
+
try {
|
|
839
|
+
if (!sub.honoredFilter.toolsListChanged)
|
|
840
|
+
throw new SubscriptionError("The server declined tools list changes.");
|
|
841
|
+
// Attach exactly once. A race with a fresh sub.closed.then() per report retains waiters indefinitely.
|
|
842
|
+
void sub.closed.then(() => { ended = true; wake?.(); });
|
|
843
|
+
for (let index = 0; index < limit; index++) {
|
|
844
|
+
if (index > 0 && !pending && !ended)
|
|
845
|
+
await new Promise(resolve => { wake = resolve; });
|
|
846
|
+
wake = undefined;
|
|
847
|
+
if (stop.signal.aborted)
|
|
848
|
+
return;
|
|
849
|
+
if (ended && !pending)
|
|
850
|
+
throw new SubscriptionError("Catalog subscription ended. Rerun to subscribe and check the current catalog.");
|
|
851
|
+
pending = false;
|
|
852
|
+
const candidate = await readModernCatalog(client, stop.signal, timeout);
|
|
853
|
+
const report = await assessSpliceImpact(suite, side === "source" ? { sourceCatalog: candidate } : { targetCatalog: candidate });
|
|
854
|
+
const reason = index === 0 ? "initial" : "changed";
|
|
855
|
+
if (p.flags.json)
|
|
856
|
+
console.log(JSON.stringify({ reason, side, report }));
|
|
857
|
+
else {
|
|
858
|
+
console.log(reason, side, report.status);
|
|
859
|
+
const evaluated = report.candidate ?? report.baseline;
|
|
860
|
+
for (const c of evaluated.cases.filter(c => !c.passed))
|
|
861
|
+
console.log(JSON.stringify(c.name), c.reason, JSON.stringify(c.actual.issues));
|
|
862
|
+
for (const issue of report.unavailable)
|
|
863
|
+
console.log(issue.side, issue.reason);
|
|
864
|
+
}
|
|
865
|
+
if (report.status !== "fixtures-pass") {
|
|
866
|
+
process.exitCode = 2;
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
finally {
|
|
872
|
+
await sub.close().catch(() => { });
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
catch (error) {
|
|
876
|
+
if (!stop.signal.aborted) {
|
|
877
|
+
if (error instanceof SubscriptionError)
|
|
878
|
+
throw error;
|
|
879
|
+
throw new Error("Catalog subscription failed. Check the connection and rerun to check the current catalog.");
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
finally {
|
|
883
|
+
process.off("SIGINT", cancel);
|
|
884
|
+
process.off("SIGTERM", cancel);
|
|
885
|
+
await client.close().catch(() => { });
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
async function captureCatalog(p) {
|
|
889
|
+
const allowed = ["url", "upstream-cwd", "bearer-env", "timeout", "out", "modern"];
|
|
890
|
+
if (p.command === "discover")
|
|
891
|
+
allowed.push("with-tools");
|
|
892
|
+
if (p.positional.length || Object.keys(p.flags).some(key => !allowed.includes(key)))
|
|
893
|
+
throw new Error("catalog accepts a connection, --timeout and an optional --out file.");
|
|
894
|
+
const timeout = integer(p.flags, "timeout", 30_000);
|
|
895
|
+
if (timeout > 2_147_483_647)
|
|
896
|
+
throw new Error("--timeout exceeds the supported timer range.");
|
|
897
|
+
const client = new Client({ name: "toolsplice-catalog", version: VERSION });
|
|
898
|
+
const stop = new AbortController();
|
|
899
|
+
const signal = AbortSignal.any([stop.signal, AbortSignal.timeout(timeout)]);
|
|
900
|
+
const cancel = () => stop.abort();
|
|
901
|
+
process.once("SIGINT", cancel);
|
|
902
|
+
process.once("SIGTERM", cancel);
|
|
903
|
+
let catalog;
|
|
904
|
+
try {
|
|
905
|
+
if (p.command === "discover" || p.flags.modern) {
|
|
906
|
+
const result = await modernDiscovery(p, signal, timeout);
|
|
907
|
+
const output = JSON.stringify(result);
|
|
908
|
+
if (Buffer.byteLength(output) > JSON_LIMIT)
|
|
909
|
+
throw new Error("Discovery report exceeds 5 MiB.");
|
|
910
|
+
const file = str(p.flags.out);
|
|
911
|
+
if (file === undefined)
|
|
912
|
+
process.stdout.write(output + "\n");
|
|
913
|
+
else {
|
|
914
|
+
writeCatalog(file, output);
|
|
915
|
+
console.log(`Saved ${p.command} to ${JSON.stringify(file)}.`);
|
|
916
|
+
}
|
|
917
|
+
return;
|
|
918
|
+
}
|
|
919
|
+
await client.connect(upstreamTransport(p), { signal, timeout });
|
|
920
|
+
catalog = await collectToolCatalog(cursor => client.request({ method: "tools/list", params: cursor === undefined ? undefined : { cursor } }, ListToolsResultSchema, { signal, timeout }));
|
|
921
|
+
}
|
|
922
|
+
catch (error) {
|
|
923
|
+
if (p.command === "discover" || p.flags.modern) {
|
|
924
|
+
if (error instanceof Error && error.message.startsWith("Install @modelcontextprotocol/client"))
|
|
925
|
+
throw error;
|
|
926
|
+
throw new Error("Modern MCP discovery failed. Check the connection, credentials, output file and timeout.");
|
|
927
|
+
}
|
|
928
|
+
throw new Error("Could not capture a complete MCP tool catalog. Check the connection, credentials, pagination and timeout.");
|
|
929
|
+
}
|
|
930
|
+
finally {
|
|
931
|
+
process.off("SIGINT", cancel);
|
|
932
|
+
process.off("SIGTERM", cancel);
|
|
933
|
+
await client.close().catch(() => { });
|
|
934
|
+
}
|
|
935
|
+
const output = JSON.stringify(catalog);
|
|
936
|
+
const file = str(p.flags.out);
|
|
937
|
+
if (file === undefined)
|
|
938
|
+
process.stdout.write(output + "\n");
|
|
939
|
+
else {
|
|
940
|
+
writeCatalog(file, output);
|
|
941
|
+
console.log(`Saved ${catalog.tools.length} tools to ${JSON.stringify(file)}.`);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
async function testRecording(p) {
|
|
945
|
+
validateFlags(p, ["from-recording", "save-case", "restorations", "json"]);
|
|
946
|
+
if (p.positional.length)
|
|
947
|
+
throw new Error("Choose a suite path or --from-recording.");
|
|
948
|
+
const recording = readLocalJson(String(p.flags["from-recording"]));
|
|
949
|
+
const options = p.flags.restorations ? { restorations: readLocalJson(String(p.flags.restorations)) } : {};
|
|
950
|
+
const suite = suiteFromRecording(recording, options);
|
|
951
|
+
const replay = await replaySpliceRecording(recording, options);
|
|
952
|
+
const report = await runSpliceSuite(suite);
|
|
953
|
+
const matched = replay.matched && report.failed === 0;
|
|
954
|
+
const actual = report.cases[0].actual;
|
|
955
|
+
if (matched && p.flags["save-case"]) {
|
|
956
|
+
const data = JSON.stringify(suite) + "\n";
|
|
957
|
+
if (Buffer.byteLength(data) > JSON_LIMIT)
|
|
958
|
+
throw new Error("Saved suite exceeds 5 MiB.");
|
|
959
|
+
writeFileSync(String(p.flags["save-case"]), data, { mode: 0o600, flag: "wx" });
|
|
960
|
+
}
|
|
961
|
+
const issue = actual.issues[0];
|
|
962
|
+
const detail = issue ? ` (${issue.code} at ${JSON.stringify(issue.path)})` : "";
|
|
963
|
+
const description = matched ? `Reproduced the original ${actual.status === "failed" ? "failure" : "success"}` : "Recording did not reproduce";
|
|
964
|
+
process.stdout.write(p.flags.json ? JSON.stringify({ ...report, recordingMatched: matched }, null, 2) + "\n" :
|
|
965
|
+
`${description}. ${actual.stage ?? actual.status}${detail}. Destination calls in replay: ${actual.targetCalls}.\n`);
|
|
966
|
+
process.exitCode = matched ? 0 : 2;
|
|
967
|
+
}
|
|
968
|
+
async function main() {
|
|
969
|
+
const p = parse(process.argv.slice(2));
|
|
970
|
+
if (p.flags.version) {
|
|
971
|
+
process.stdout.write(VERSION + "\n");
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
if (p.flags.help || ["help", "--help"].includes(p.command)) {
|
|
975
|
+
process.stdout.write(USAGE + "\n toolsplice test <suite.json|directory> [--json] [--junit results.xml]\n Run offline regression cases; optional --source-contract/--target-contract candidates.\n");
|
|
976
|
+
return;
|
|
977
|
+
}
|
|
978
|
+
if (p.command === "init" && ["source-catalog", "target-catalog", "source", "target", "bind", "set", "input", "fixture", "fixture-format", "result-path", "result-fields", "each", "max-items"].some(k => k in p.flags))
|
|
979
|
+
return initFromCatalogs(p);
|
|
980
|
+
if (p.command === "evaluate") {
|
|
981
|
+
if (p.flags.ledger !== undefined) {
|
|
982
|
+
validateFlags(p, ["ledger", "json"]);
|
|
983
|
+
const directory = str(p.flags.ledger);
|
|
984
|
+
if (!directory || p.positional.length)
|
|
985
|
+
throw new Error("--ledger needs a checkpoint directory.");
|
|
986
|
+
process.stdout.write(JSON.stringify(readCalibrationLedger(directory), null, 2) + "\n");
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
989
|
+
if (p.flags.init !== undefined) {
|
|
990
|
+
validateFlags(p, ["init"]);
|
|
991
|
+
const target = str(p.flags.init);
|
|
992
|
+
if (!target?.endsWith(".mjs") || p.positional.length)
|
|
993
|
+
throw new Error("Choose a new .mjs driver path.");
|
|
994
|
+
writeCatalog(target, readFileSync(new URL("../examples/route-driver.mjs", import.meta.url), "utf8"));
|
|
995
|
+
process.stdout.write("Created the local evaluation driver.\n");
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
998
|
+
if (p.flags.plan) {
|
|
999
|
+
validateFlags(p, ["driver", "plan", "json"]);
|
|
1000
|
+
const driver = str(p.flags.driver);
|
|
1001
|
+
if (p.positional.length || !driver?.endsWith(".mjs"))
|
|
1002
|
+
throw new Error("--plan needs a trusted --driver local.mjs.");
|
|
1003
|
+
const plan = await executeRouteDriver(driver, "plan");
|
|
1004
|
+
process.stdout.write(JSON.stringify(plan, null, 2) + "\n");
|
|
1005
|
+
return;
|
|
1006
|
+
}
|
|
1007
|
+
validateFlags(p, ["driver", "save-trials", "out", "json", "checkpoint", "retry-incomplete"]);
|
|
1008
|
+
const driver = str(p.flags.driver), saved = str(p.flags["save-trials"]), out = str(p.flags.out);
|
|
1009
|
+
if (driver ? p.positional.length || !driver.endsWith(".mjs") : p.positional.length !== 1 || saved)
|
|
1010
|
+
throw new Error("Pass a trial receipt or an explicit --driver local.mjs.");
|
|
1011
|
+
const checkpoint = str(p.flags.checkpoint), retry = Boolean(p.flags["retry-incomplete"]);
|
|
1012
|
+
if ((p.flags.checkpoint !== undefined && (!checkpoint || !driver)) || (retry && !checkpoint))
|
|
1013
|
+
throw new Error("--checkpoint needs --driver; --retry-incomplete needs --checkpoint.");
|
|
1014
|
+
const outputs = [saved, out].filter((x) => x !== undefined);
|
|
1015
|
+
const targets = outputs.map(x => resolve(realpathSync(dirname(x)), relative(dirname(x), x)));
|
|
1016
|
+
const journal = checkpoint ? (existsSync(checkpoint) ? realpathSync(checkpoint) : resolve(checkpoint)) : undefined;
|
|
1017
|
+
if (journal && targets.some(x => x === journal || x.startsWith(journal + sep)))
|
|
1018
|
+
throw new Error("Choose output paths outside the checkpoint directory.");
|
|
1019
|
+
if (new Set(targets).size !== targets.length || targets.some(x => existsSync(x)))
|
|
1020
|
+
throw new Error("Choose distinct, unused output paths.");
|
|
1021
|
+
const evidence = driver
|
|
1022
|
+
? await executeRouteDriver(driver, "run", journal, retry)
|
|
1023
|
+
: await readRouteReceipt(p.positional[0]);
|
|
1024
|
+
const report = evaluateRoutes(evidence);
|
|
1025
|
+
if (saved)
|
|
1026
|
+
writeCatalog(saved, JSON.stringify(evidence) + "\n", ROUTE_FILE_LIMIT);
|
|
1027
|
+
if (out)
|
|
1028
|
+
writeCatalog(out, JSON.stringify(report.policy, null, 2) + "\n", ROUTE_FILE_LIMIT);
|
|
1029
|
+
process.stdout.write(p.flags.json ? JSON.stringify(report, null, 2) + "\n"
|
|
1030
|
+
: report.workloads.map(r => [r.workload, r.selected, explainRoute(r)].join(" ")).join("\n") + "\n");
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
if (p.command === "measure") {
|
|
1034
|
+
validateFlags(p, ["json", "restorations"]);
|
|
1035
|
+
if (p.positional.length !== 1)
|
|
1036
|
+
throw new Error("measure needs one successful payload recording.");
|
|
1037
|
+
const report = await measureSpliceRecording(readLocalJson(p.positional[0]), {
|
|
1038
|
+
...(p.flags.restorations ? { restorations: readLocalJson(String(p.flags.restorations)) } : {}),
|
|
1039
|
+
});
|
|
1040
|
+
process.stdout.write(p.flags.json ? JSON.stringify(report, null, 2) + "\n" :
|
|
1041
|
+
`Direct: ${report.direct.modelToolCalls} model-facing tool calls, ${report.direct.toolResultBytes} result bytes. Composite: 1 model-facing tool call, ${report.composite.toolResultBytes} result bytes. Recorded upstream calls: ${report.recordedUpstreamCalls.source} source, ${report.recordedUpstreamCalls.target} target.\n`);
|
|
1042
|
+
return;
|
|
1043
|
+
}
|
|
1044
|
+
if (p.command === "catalog" || p.command === "discover")
|
|
1045
|
+
return captureCatalog(p);
|
|
1046
|
+
if (p.command === "impact" && p.flags.follow !== undefined)
|
|
1047
|
+
return followCatalogImpact(p);
|
|
1048
|
+
if (p.command === "impact") {
|
|
1049
|
+
validateFlags(p, ["source-contract", "target-contract", "source-catalog", "target-catalog", "candidate-result", "case", "json"]);
|
|
1050
|
+
if (p.positional.length !== 1)
|
|
1051
|
+
throw new Error("impact needs one suite file or project directory.");
|
|
1052
|
+
const suite = readSuite(p.positional[0]);
|
|
1053
|
+
let caseName = str(p.flags.case);
|
|
1054
|
+
const sample = str(p.flags["candidate-result"]);
|
|
1055
|
+
if (caseName !== undefined && !sample)
|
|
1056
|
+
throw new Error("--case requires --candidate-result.");
|
|
1057
|
+
if (sample && caseName === undefined) {
|
|
1058
|
+
if (!Array.isArray(suite.cases) || suite.cases.length !== 1 || typeof suite.cases[0]?.name !== "string")
|
|
1059
|
+
throw new Error("Use --case <name> to assign the candidate response to one suite case.");
|
|
1060
|
+
caseName = suite.cases[0].name;
|
|
1061
|
+
}
|
|
1062
|
+
const report = await assessSpliceImpact(suite, {
|
|
1063
|
+
...(p.flags["source-catalog"] ? { sourceCatalog: readLocalJson(String(p.flags["source-catalog"])) } : {}),
|
|
1064
|
+
...(p.flags["target-catalog"] ? { targetCatalog: readLocalJson(String(p.flags["target-catalog"])) } : {}),
|
|
1065
|
+
...(p.flags["source-contract"] ? { sourceContract: parseContractSnapshot(readLocalJson(String(p.flags["source-contract"]))) } : {}),
|
|
1066
|
+
...(p.flags["target-contract"] ? { targetContract: parseContractSnapshot(readLocalJson(String(p.flags["target-contract"]))) } : {}),
|
|
1067
|
+
...(sample && caseName !== undefined ? { sourceResults: { [caseName]: readLocalJson(sample) } } : {}),
|
|
1068
|
+
});
|
|
1069
|
+
if (p.flags.json)
|
|
1070
|
+
process.stdout.write(JSON.stringify(report, null, 2) + "\n");
|
|
1071
|
+
else {
|
|
1072
|
+
const evaluated = report.candidate ?? report.baseline;
|
|
1073
|
+
console.log(`${report.status}. Baseline: ${report.baseline.passed}/${report.baseline.cases.length} passed. Candidate: ${report.candidate ? report.candidate.passed + "/" + report.candidate.cases.length + " passed" : "not run"}.`);
|
|
1074
|
+
for (const issue of report.unavailable)
|
|
1075
|
+
console.log(issue.side, issue.reason);
|
|
1076
|
+
for (const c of evaluated.cases.filter(c => !c.passed))
|
|
1077
|
+
console.log(JSON.stringify(c.name), c.reason, JSON.stringify(c.actual));
|
|
1078
|
+
}
|
|
1079
|
+
process.exitCode = report.status === "fixtures-pass" ? 0 : 2;
|
|
1080
|
+
return;
|
|
1081
|
+
}
|
|
1082
|
+
if (p.command === "test" && p.flags["from-recording"])
|
|
1083
|
+
return testRecording(p);
|
|
1084
|
+
if (p.command === "test") {
|
|
1085
|
+
const allowed = new Set(["json", "junit", "source-contract", "target-contract", "allow-review"]);
|
|
1086
|
+
if (p.positional.length !== 1 || p.upstream.length || Object.keys(p.flags).some(k => !allowed.has(k)))
|
|
1087
|
+
throw new Error("test needs one suite file/directory and only test/report/candidate options.");
|
|
1088
|
+
const suite = readSuite(p.positional[0]);
|
|
1089
|
+
const report = await runSpliceSuite(suite, {
|
|
1090
|
+
...(p.flags["source-contract"] ? { sourceContract: parseContractSnapshot(readLocalJson(String(p.flags["source-contract"]))) } : {}),
|
|
1091
|
+
...(p.flags["target-contract"] ? { targetContract: parseContractSnapshot(readLocalJson(String(p.flags["target-contract"]))) } : {}),
|
|
1092
|
+
...(p.flags["allow-review"] ? { allowReview: true } : {}),
|
|
1093
|
+
});
|
|
1094
|
+
if (p.flags.junit)
|
|
1095
|
+
writeFileSync(String(p.flags.junit), formatTestJUnit(report), { flag: "wx", mode: 0o600 });
|
|
1096
|
+
process.stdout.write(p.flags.json ? JSON.stringify(report, null, 2) + "\n" :
|
|
1097
|
+
`${report.passed} passed, ${report.failed} failed; zero live tool/network calls.\n` + report.cases.filter(c => !c.passed).map(c => `${JSON.stringify(c.name)}: ${c.reason}; ${JSON.stringify(c.actual)}\n`).join(""));
|
|
1098
|
+
process.exitCode = report.failed ? 2 : 0;
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
const examples = (str(p.flags.examples) ?? "none");
|
|
1102
|
+
if (!["none", "safe", "all"].includes(examples))
|
|
1103
|
+
throw new Error(`Unknown --examples policy: ${examples}`);
|
|
1104
|
+
const log = (message) => {
|
|
1105
|
+
if (!p.flags.quiet)
|
|
1106
|
+
process.stderr.write(`[toolsplice] ${message}\n`);
|
|
1107
|
+
};
|
|
1108
|
+
const storeWarnings = [];
|
|
1109
|
+
const databaseEnv = str(p.flags["database-env"]);
|
|
1110
|
+
if (p.flags["database-env"] !== undefined && !databaseEnv)
|
|
1111
|
+
throw new Error("--database-env must name an environment variable.");
|
|
1112
|
+
if (databaseEnv && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(databaseEnv))
|
|
1113
|
+
throw new Error("--database-env must name an environment variable.");
|
|
1114
|
+
if (databaseEnv && p.flags.store)
|
|
1115
|
+
throw new Error("Use either --store or --database-env.");
|
|
1116
|
+
if (!databaseEnv &&
|
|
1117
|
+
(p.flags.namespace !== undefined ||
|
|
1118
|
+
p.flags["no-migrate"] ||
|
|
1119
|
+
p.flags["database-timeout"] !== undefined))
|
|
1120
|
+
throw new Error("--namespace, --no-migrate and --database-timeout require --database-env.");
|
|
1121
|
+
if (p.flags.namespace !== undefined) {
|
|
1122
|
+
const name = String(p.flags.namespace);
|
|
1123
|
+
if (!name || name.includes("\0") || Buffer.byteLength(name) > 256)
|
|
1124
|
+
throw new Error("--namespace must be nonempty, contain no NUL and fit 256 UTF-8 bytes.");
|
|
1125
|
+
}
|
|
1126
|
+
const databaseTimeout = integer(p.flags, "database-timeout", 1000, 50);
|
|
1127
|
+
if (databaseTimeout > 60000)
|
|
1128
|
+
throw new Error("--database-timeout must be <= 60000.");
|
|
1129
|
+
const minSamples = integer(p.flags, "min-samples", 1);
|
|
1130
|
+
if (p.flags.timeout !== undefined)
|
|
1131
|
+
integer(p.flags, "timeout", 600_000);
|
|
1132
|
+
if (p.flags["max-description"] !== undefined)
|
|
1133
|
+
integer(p.flags, "max-description", 2000, 80);
|
|
1134
|
+
const enrich = (str(p.flags.enrich) ?? "description");
|
|
1135
|
+
if (!["description", "none", "schema"].includes(enrich))
|
|
1136
|
+
throw new Error(`Unknown --enrich mode: ${enrich}`);
|
|
1137
|
+
if (p.command === "config") {
|
|
1138
|
+
config(p);
|
|
1139
|
+
return;
|
|
1140
|
+
}
|
|
1141
|
+
if (["replay", "correct"].includes(p.command)) {
|
|
1142
|
+
await runOfflineWorkflow(p);
|
|
1143
|
+
return;
|
|
1144
|
+
}
|
|
1145
|
+
if (["init", "project"].includes(p.command)) {
|
|
1146
|
+
await runProject(p);
|
|
1147
|
+
return;
|
|
1148
|
+
}
|
|
1149
|
+
if (p.command === "splice" &&
|
|
1150
|
+
[
|
|
1151
|
+
"source-contract",
|
|
1152
|
+
"target-contract",
|
|
1153
|
+
"source-catalog",
|
|
1154
|
+
"target-catalog",
|
|
1155
|
+
].some((key) => p.flags[key] !== undefined)) {
|
|
1156
|
+
for (const side of ["source", "target"]) {
|
|
1157
|
+
if ([
|
|
1158
|
+
str(p.flags[`${side}-contract`]),
|
|
1159
|
+
str(p.flags[`${side}-catalog`]),
|
|
1160
|
+
].filter(Boolean).length !== 1)
|
|
1161
|
+
throw new Error("Use both --source-contract and --target-contract, or supply exactly one contract/catalog file for each endpoint.");
|
|
1162
|
+
}
|
|
1163
|
+
if (p.flags.store || databaseEnv)
|
|
1164
|
+
throw new Error("Use contract files or a learning store, not both.");
|
|
1165
|
+
await runSplice(p);
|
|
1166
|
+
return;
|
|
1167
|
+
}
|
|
1168
|
+
const storeLocation = databaseEnv
|
|
1169
|
+
? `postgres:${str(p.flags.namespace) ?? "default"}`
|
|
1170
|
+
: resolve(str(p.flags.store) ?? ".mcp-shape");
|
|
1171
|
+
let store;
|
|
1172
|
+
if (databaseEnv) {
|
|
1173
|
+
const connectionString = process.env[databaseEnv];
|
|
1174
|
+
if (!connectionString)
|
|
1175
|
+
throw new Error(`Storage environment variable ${databaseEnv} is not set.`);
|
|
1176
|
+
const { PostgresShapeStore } = await import("./postgres.js");
|
|
1177
|
+
store = new PostgresShapeStore({
|
|
1178
|
+
connectionString,
|
|
1179
|
+
namespace: str(p.flags.namespace),
|
|
1180
|
+
migrate: !p.flags["no-migrate"],
|
|
1181
|
+
timeoutMs: databaseTimeout,
|
|
1182
|
+
});
|
|
1183
|
+
}
|
|
1184
|
+
else
|
|
1185
|
+
store = new ShapeStore(storeLocation, {
|
|
1186
|
+
onWarning: (message) => {
|
|
1187
|
+
storeWarnings.push(message);
|
|
1188
|
+
log(message);
|
|
1189
|
+
},
|
|
1190
|
+
});
|
|
1191
|
+
let keepOpen = false;
|
|
1192
|
+
try {
|
|
1193
|
+
const requireServer = async (name) => {
|
|
1194
|
+
if (!name)
|
|
1195
|
+
throw new Error(`${p.command} needs a server name (see doctor or show).`);
|
|
1196
|
+
if (!(await store.has(name)))
|
|
1197
|
+
throw new Error(`Nothing learned for ${JSON.stringify(name)}. Use the proxy or probe first.`);
|
|
1198
|
+
return store.load(name);
|
|
1199
|
+
};
|
|
1200
|
+
switch (p.command) {
|
|
1201
|
+
case "proxy": {
|
|
1202
|
+
const transport = upstreamTransport(p);
|
|
1203
|
+
const startup = new AbortController();
|
|
1204
|
+
let proxy;
|
|
1205
|
+
let closing = false;
|
|
1206
|
+
const close = async () => {
|
|
1207
|
+
if (closing)
|
|
1208
|
+
return;
|
|
1209
|
+
closing = true;
|
|
1210
|
+
startup.abort();
|
|
1211
|
+
if (proxy)
|
|
1212
|
+
await proxy.close();
|
|
1213
|
+
else
|
|
1214
|
+
await transport.close().catch(() => { });
|
|
1215
|
+
await store.close?.();
|
|
1216
|
+
};
|
|
1217
|
+
// Install these before spawning/initializing an upstream process: slow or broken startup
|
|
1218
|
+
// must not leave its child behind when the host cancels this CLI.
|
|
1219
|
+
process.once("SIGINT", () => {
|
|
1220
|
+
void close();
|
|
1221
|
+
});
|
|
1222
|
+
process.once("SIGTERM", () => {
|
|
1223
|
+
void close();
|
|
1224
|
+
});
|
|
1225
|
+
process.stdin.once("end", () => {
|
|
1226
|
+
void close();
|
|
1227
|
+
});
|
|
1228
|
+
try {
|
|
1229
|
+
proxy = await createProxy(transport, {
|
|
1230
|
+
store,
|
|
1231
|
+
serverName: str(p.flags.name),
|
|
1232
|
+
enrich,
|
|
1233
|
+
minSamples,
|
|
1234
|
+
examples,
|
|
1235
|
+
log,
|
|
1236
|
+
signal: startup.signal,
|
|
1237
|
+
callTimeoutMs: integer(p.flags, "timeout", 600_000),
|
|
1238
|
+
maxDescriptionLength: integer(p.flags, "max-description", 2000, 80),
|
|
1239
|
+
});
|
|
1240
|
+
if (closing) {
|
|
1241
|
+
await proxy.close();
|
|
1242
|
+
return;
|
|
1243
|
+
}
|
|
1244
|
+
proxy.server.onclose = () => {
|
|
1245
|
+
void close();
|
|
1246
|
+
};
|
|
1247
|
+
await proxy.server.connect(new StdioServerTransport());
|
|
1248
|
+
keepOpen = !closing;
|
|
1249
|
+
log(`Proxying ${JSON.stringify(proxy.serverName)} (enrich: ${enrich}; examples: ${examples})`);
|
|
1250
|
+
}
|
|
1251
|
+
catch (error) {
|
|
1252
|
+
if (!startup.signal.aborted) {
|
|
1253
|
+
await close();
|
|
1254
|
+
throw error;
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
case "probe": {
|
|
1260
|
+
const argsFile = str(p.flags.args);
|
|
1261
|
+
const args = argsFile
|
|
1262
|
+
? JSON.parse(readFileSync(argsFile, "utf8"))
|
|
1263
|
+
: undefined;
|
|
1264
|
+
if (args !== undefined &&
|
|
1265
|
+
(!args ||
|
|
1266
|
+
Array.isArray(args) ||
|
|
1267
|
+
typeof args !== "object" ||
|
|
1268
|
+
Object.values(args).some((v) => !Array.isArray(v) ||
|
|
1269
|
+
v.some((a) => !a || typeof a !== "object" || Array.isArray(a)))))
|
|
1270
|
+
throw new Error("--args must contain an object of tool names to arrays of argument objects.");
|
|
1271
|
+
const transport = upstreamTransport(p);
|
|
1272
|
+
const abort = new AbortController();
|
|
1273
|
+
const cancel = () => {
|
|
1274
|
+
abort.abort();
|
|
1275
|
+
void transport.close().catch(() => { });
|
|
1276
|
+
};
|
|
1277
|
+
process.once("SIGINT", cancel);
|
|
1278
|
+
process.once("SIGTERM", cancel);
|
|
1279
|
+
let report;
|
|
1280
|
+
try {
|
|
1281
|
+
report = await probe(transport, {
|
|
1282
|
+
store,
|
|
1283
|
+
serverName: str(p.flags.name),
|
|
1284
|
+
args,
|
|
1285
|
+
examples,
|
|
1286
|
+
timeoutMs: integer(p.flags, "timeout", 60_000),
|
|
1287
|
+
signal: abort.signal,
|
|
1288
|
+
});
|
|
1289
|
+
}
|
|
1290
|
+
catch (error) {
|
|
1291
|
+
if (abort.signal.aborted)
|
|
1292
|
+
return;
|
|
1293
|
+
throw error;
|
|
1294
|
+
}
|
|
1295
|
+
finally {
|
|
1296
|
+
process.removeListener("SIGINT", cancel);
|
|
1297
|
+
process.removeListener("SIGTERM", cancel);
|
|
1298
|
+
}
|
|
1299
|
+
const width = Math.max(4, ...report.rows.map((r) => r.tool.length));
|
|
1300
|
+
process.stdout.write(`Probed ${JSON.stringify(report.serverName)}\n`);
|
|
1301
|
+
for (const row of report.rows)
|
|
1302
|
+
process.stdout.write(` ${row.tool.padEnd(width)} ${row.status.padEnd(7)} ${row.status === "called" ? row.kinds.join(", ") : row.reason}\n`);
|
|
1303
|
+
if (report.rows.some((r) => r.status === "failed"))
|
|
1304
|
+
process.exitCode = 2;
|
|
1305
|
+
return;
|
|
1306
|
+
}
|
|
1307
|
+
case "doctor": {
|
|
1308
|
+
const names = p.positional.length ? p.positional : await store.list();
|
|
1309
|
+
const reports = await Promise.all(names.map(async (n) => diagnose(await requireServer(n), minSamples)));
|
|
1310
|
+
const storage = (await store.diagnostics?.()) ?? [];
|
|
1311
|
+
if (p.flags.json)
|
|
1312
|
+
process.stdout.write(JSON.stringify({
|
|
1313
|
+
store: storeLocation,
|
|
1314
|
+
servers: reports,
|
|
1315
|
+
warnings: storeWarnings,
|
|
1316
|
+
storage,
|
|
1317
|
+
}, null, 2) + "\n");
|
|
1318
|
+
else if (!reports.length)
|
|
1319
|
+
process.stdout.write(`No learning in ${storeLocation}. Generate an MCP config with config, then use its tools normally.\n`);
|
|
1320
|
+
else
|
|
1321
|
+
for (const report of reports)
|
|
1322
|
+
process.stdout.write(formatDoctor(report));
|
|
1323
|
+
if (!p.flags.json && storage.length) {
|
|
1324
|
+
for (const item of storage)
|
|
1325
|
+
process.stdout.write(`Storage: ${item.kind}, owner ${item.owner}${item.pid ? ` (PID ${item.pid})` : ""}: ${item.file}\n`);
|
|
1326
|
+
process.stdout.write("Inspect abandoned artifacts before removing them; active writers are never automatically unlocked.\n");
|
|
1327
|
+
}
|
|
1328
|
+
const abandoned = storage.some((s) => s.owner !== "running");
|
|
1329
|
+
if (p.flags.check &&
|
|
1330
|
+
(abandoned ||
|
|
1331
|
+
storeWarnings.length > 0 ||
|
|
1332
|
+
reports.some((r) => r.export === "stale" || r.totals.warning > 0)))
|
|
1333
|
+
process.exitCode = 2;
|
|
1334
|
+
return;
|
|
1335
|
+
}
|
|
1336
|
+
case "show": {
|
|
1337
|
+
const names = p.positional.length ? p.positional : await store.list();
|
|
1338
|
+
if (!names.length)
|
|
1339
|
+
throw new Error(`Nothing learned yet in ${storeLocation}`);
|
|
1340
|
+
for (const name of names) {
|
|
1341
|
+
const server = await requireServer(name);
|
|
1342
|
+
process.stdout.write(`${server.name}${server.version ? ` v${server.version}` : ""}\n`);
|
|
1343
|
+
for (const tool of Object.values(server.tools)) {
|
|
1344
|
+
const kinds = Object.entries(tool.kinds)
|
|
1345
|
+
.filter(([, n]) => n > 0)
|
|
1346
|
+
.map(([k, n]) => `${k}×${n}`)
|
|
1347
|
+
.join(" ");
|
|
1348
|
+
process.stdout.write(` ${tool.name} [${tool.calls} call(s)${kinds ? `: ${kinds}` : ""}]\n`);
|
|
1349
|
+
const summary = describeOutput(tool);
|
|
1350
|
+
if (summary)
|
|
1351
|
+
process.stdout.write(` ${summary}\n`);
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
return;
|
|
1355
|
+
}
|
|
1356
|
+
case "splice": {
|
|
1357
|
+
await runSplice(p, requireServer);
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
case "snapshot": {
|
|
1361
|
+
const server = await requireServer(p.positional[0]);
|
|
1362
|
+
const tools = Array.isArray(p.flags.tool) ? p.flags.tool : undefined;
|
|
1363
|
+
const snapshot = createContractSnapshot(server, tools === undefined ? {} : { tools });
|
|
1364
|
+
const out = str(p.flags.out), contents = JSON.stringify(snapshot, null, 2) + "\n";
|
|
1365
|
+
if (Buffer.byteLength(contents) > 5 * 1024 * 1024)
|
|
1366
|
+
throw new Error("Serialized contract snapshot exceeds the 5 MiB limit; select fewer tools with --tool.");
|
|
1367
|
+
if (out)
|
|
1368
|
+
writeFileSync(out, contents, { mode: 0o600, flag: "wx" });
|
|
1369
|
+
else
|
|
1370
|
+
process.stdout.write(contents);
|
|
1371
|
+
return;
|
|
1372
|
+
}
|
|
1373
|
+
case "check": {
|
|
1374
|
+
const baselinePath = str(p.flags.baseline);
|
|
1375
|
+
if (!baselinePath)
|
|
1376
|
+
throw new Error("check requires --baseline <file>.");
|
|
1377
|
+
const failOn = str(p.flags["fail-on"]) ?? "any";
|
|
1378
|
+
if (failOn !== "any" && failOn !== "breaking")
|
|
1379
|
+
throw new Error("--fail-on must be any or breaking.");
|
|
1380
|
+
const baseline = parseContractSnapshot(readFileSync(baselinePath, "utf8"));
|
|
1381
|
+
const server = await requireServer(p.positional[0]);
|
|
1382
|
+
const names = baseline.selection === "subset"
|
|
1383
|
+
? baseline.tools
|
|
1384
|
+
.map((t) => t.name)
|
|
1385
|
+
.filter((n) => Object.hasOwn(server.tools, n))
|
|
1386
|
+
: undefined;
|
|
1387
|
+
const report = compareContractSnapshots(baseline, createContractSnapshot(server, names === undefined ? {} : { tools: names }));
|
|
1388
|
+
if (p.flags.json)
|
|
1389
|
+
process.stdout.write(JSON.stringify(report, null, 2) + "\n");
|
|
1390
|
+
else {
|
|
1391
|
+
process.stdout.write(`${JSON.stringify(report.server)}: contract ${report.status}\n`);
|
|
1392
|
+
for (const change of report.changes)
|
|
1393
|
+
process.stdout.write(` [${change.severity}] ${JSON.stringify(change.path)}: ${change.message}\n`);
|
|
1394
|
+
if (report.truncated)
|
|
1395
|
+
process.stdout.write(" Additional changes omitted; review is required.\n");
|
|
1396
|
+
process.stdout.write(report.note + "\n");
|
|
1397
|
+
}
|
|
1398
|
+
if (contractCheckFailed(report, failOn))
|
|
1399
|
+
process.exitCode = 2;
|
|
1400
|
+
return;
|
|
1401
|
+
}
|
|
1402
|
+
case "emit-ts": {
|
|
1403
|
+
const server = await requireServer(p.positional[0]);
|
|
1404
|
+
const out = str(p.flags.out);
|
|
1405
|
+
if (p.flags.runtime &&
|
|
1406
|
+
out &&
|
|
1407
|
+
(!out.endsWith(".ts") || out.endsWith(".d.ts")))
|
|
1408
|
+
throw new Error("--runtime output must be a .ts source file, not .d.ts.");
|
|
1409
|
+
const code = p.flags.runtime
|
|
1410
|
+
? emitBindings(server)
|
|
1411
|
+
: emitModule(server);
|
|
1412
|
+
if (out)
|
|
1413
|
+
writeFileSync(out, code, { mode: 0o600 });
|
|
1414
|
+
else
|
|
1415
|
+
process.stdout.write(code);
|
|
1416
|
+
const fingerprint = exportFingerprint(server);
|
|
1417
|
+
await store.transact(server.name, (latest) => {
|
|
1418
|
+
latest.exportedAt = new Date().toISOString();
|
|
1419
|
+
// Stamp the exact contract that was exported, even if another process learned more meanwhile.
|
|
1420
|
+
latest.exportedFingerprint = fingerprint;
|
|
1421
|
+
});
|
|
1422
|
+
return;
|
|
1423
|
+
}
|
|
1424
|
+
case "schema": {
|
|
1425
|
+
const toolName = p.positional[1];
|
|
1426
|
+
const server = await requireServer(p.positional[0]);
|
|
1427
|
+
if (!toolName || !Object.hasOwn(server.tools, toolName))
|
|
1428
|
+
throw new Error("schema needs a recorded <server> <tool>.");
|
|
1429
|
+
const tool = server.tools[toolName];
|
|
1430
|
+
process.stdout.write(JSON.stringify(toJsonSchema(tool.shape, {
|
|
1431
|
+
mode: p.flags.lenient ? "lenient" : "docs",
|
|
1432
|
+
}), null, 2) + "\n");
|
|
1433
|
+
return;
|
|
1434
|
+
}
|
|
1435
|
+
case "forget": {
|
|
1436
|
+
const server = await requireServer(p.positional[0]);
|
|
1437
|
+
await store.remove(server.name);
|
|
1438
|
+
process.stdout.write(`Removed local learning for ${JSON.stringify(server.name)}.\n`);
|
|
1439
|
+
return;
|
|
1440
|
+
}
|
|
1441
|
+
default:
|
|
1442
|
+
throw new Error(`Unknown command ${JSON.stringify(p.command)}. Run toolsplice --help.`);
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
finally {
|
|
1446
|
+
if (!keepOpen)
|
|
1447
|
+
await store.close?.();
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
main().catch((error) => {
|
|
1451
|
+
// No stacks or upstream response bodies: stderr is often captured in agent logs.
|
|
1452
|
+
process.stderr.write(`toolsplice: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
1453
|
+
process.exitCode = 1;
|
|
1454
|
+
});
|