toolsplice 0.0.0-stage → 0.0.1
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 +372 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +923 -0
- package/dist/codegen.d.ts +44 -0
- package/dist/codegen.js +479 -0
- package/dist/contract-caller.d.ts +22 -0
- package/dist/contract-caller.js +307 -0
- package/dist/contract-corrections.d.ts +35 -0
- package/dist/contract-corrections.js +159 -0
- package/dist/contract-schema.d.ts +5 -0
- package/dist/contract-schema.js +126 -0
- package/dist/contracts.d.ts +71 -0
- package/dist/contracts.js +366 -0
- package/dist/core.d.ts +14 -0
- package/dist/core.js +16 -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/index.d.ts +20 -0
- package/dist/index.js +19 -0
- package/dist/ordered-transport.d.ts +12 -0
- package/dist/ordered-transport.js +106 -0
- package/dist/pattern.d.ts +2 -0
- package/dist/pattern.js +32 -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 +134 -0
- package/dist/proxy.d.ts +40 -0
- package/dist/proxy.js +436 -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/shape.d.ts +91 -0
- package/dist/shape.js +499 -0
- package/dist/splice-diagnostics.d.ts +40 -0
- package/dist/splice-diagnostics.js +80 -0
- package/dist/splice-project.d.ts +119 -0
- package/dist/splice-project.js +296 -0
- package/dist/splice-recording.d.ts +105 -0
- package/dist/splice-recording.js +464 -0
- package/dist/splice.d.ts +84 -0
- package/dist/splice.js +1065 -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/v2.d.ts +49 -0
- package/dist/v2.js +396 -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/PROJECTS-AND-UPGRADES.md +115 -0
- package/docs/RECORDING-AND-CORRECTIONS.md +176 -0
- package/package.json +95 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,923 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { delimiter, dirname, resolve } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { parseArgs } from "node:util";
|
|
6
|
+
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
7
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
8
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
9
|
+
import { parseSpliceSpec, prepareSplice, emitSpliceModule, SpliceError, } from "./splice.js";
|
|
10
|
+
import { decode } from "./runtime.js";
|
|
11
|
+
import { explainSpliceError } from "./splice-diagnostics.js";
|
|
12
|
+
import { replaySpliceRecording } from "./splice-recording.js";
|
|
13
|
+
import { applyContractCorrection, parseContractCorrection, } from "./contract-corrections.js";
|
|
14
|
+
import { parseWorkflowJson, JSON_LIMIT } from "./workflow-json.js";
|
|
15
|
+
import { initializeSpliceProject, checkSpliceProject, } from "./splice-project.js";
|
|
16
|
+
import { createContractSnapshot, createContractFromCatalog, parseContractSnapshot, compareContractSnapshots, contractCheckFailed, } from "./contracts.js";
|
|
17
|
+
import { describeOutput, emitModule, emitBindings } from "./codegen.js";
|
|
18
|
+
import { diagnose, formatDoctor } from "./doctor.js";
|
|
19
|
+
import { exportFingerprint } from "./drift.js";
|
|
20
|
+
import { probe } from "./probe.js";
|
|
21
|
+
import { createProxy } from "./proxy.js";
|
|
22
|
+
import { toJsonSchema } from "./schema.js";
|
|
23
|
+
import { VERSION } from "./version.js";
|
|
24
|
+
import { ShapeStore } from "./store.js";
|
|
25
|
+
const USAGE = `toolsplice: check and generate MCP tool handoffs
|
|
26
|
+
|
|
27
|
+
Usage:
|
|
28
|
+
toolsplice splice <plan.json> [--fixture <file>] Check or dry-run an explicit tool-to-tool adapter; no tool calls
|
|
29
|
+
toolsplice replay <recording.json> [--json] Replay a recorded run entirely offline; exit 2 on mismatch
|
|
30
|
+
toolsplice init <new-directory> Create and check an offline starter; optionally --from-recording <file>
|
|
31
|
+
toolsplice project <directory> [--allow-review] Check project inputs/fixtures and mapped arguments offline
|
|
32
|
+
toolsplice correct <baseline.json> --correction <file> Validate a pinned correction and its fixtures offline
|
|
33
|
+
toolsplice proxy [options] -- <command> [args...] Learn from normal agent traffic; enrich descriptions automatically
|
|
34
|
+
toolsplice proxy [options] --url <http url> Wrap a Streamable HTTP server
|
|
35
|
+
toolsplice config --name <name> -- <command> [...] Print a ready-to-use MCP client configuration
|
|
36
|
+
toolsplice config --from <file> --server <name> Wrap one existing stdio config; retain its env and cwd
|
|
37
|
+
toolsplice probe [options] -- <command> [args...] Call tools marked read-only (annotations are hints)
|
|
38
|
+
toolsplice doctor [server] [--json] Diagnose learned types, unsupported text and stale exports
|
|
39
|
+
toolsplice show [server] Summarize learned outputs
|
|
40
|
+
toolsplice emit-ts <server> [--out file] Write types, or a callable .ts module with --runtime
|
|
41
|
+
toolsplice schema <server> <tool> [--lenient] Show the learned JSON Schema
|
|
42
|
+
toolsplice snapshot <server> --out <file> Save a reviewable contract baseline (new file only)
|
|
43
|
+
toolsplice check <server> --baseline <file> Compare current learning to a baseline; exit 2 on change
|
|
44
|
+
toolsplice forget <server> Delete this server's local learning (does not call the server)
|
|
45
|
+
|
|
46
|
+
Options:
|
|
47
|
+
--store <dir> Learning store (default: .mcp-shape, relative to this working directory)
|
|
48
|
+
--database-env <name> Read PostgreSQL URL from this environment variable (optional backend)
|
|
49
|
+
--database-timeout <ms> PostgreSQL pool/lock/statement deadline (50–60000; default: 1000)
|
|
50
|
+
--namespace <name> PostgreSQL project/tenant namespace (default: default)
|
|
51
|
+
--no-migrate PostgreSQL: require an already migrated schema
|
|
52
|
+
--name <name> Explicit server identity; use distinct names for different installations/accounts
|
|
53
|
+
--enrich <mode> description (default), none, or schema (experimental)
|
|
54
|
+
--min-samples <n> Responses needed before enrichment (default: 1)
|
|
55
|
+
--max-description <n> Extra description character budget (default: 2000, minimum: 80)
|
|
56
|
+
--timeout <ms> Upstream call timeout (default: 600000)
|
|
57
|
+
--upstream-cwd <dir> Working directory for an upstream stdio process
|
|
58
|
+
--bearer-env <name> HTTP: read bearer token from this environment variable, never from an argument
|
|
59
|
+
--args <file> Probe calls: { "tool": [ {args}, ... ] }; explicit calls may write data
|
|
60
|
+
--examples <policy> none (default), safe (heuristic, opt-in), all (opt-in)
|
|
61
|
+
--source-contract <file> splice: portable contract; replay: candidate source contract
|
|
62
|
+
--target-contract <file> splice: portable contract; replay: candidate target contract
|
|
63
|
+
--source-catalog <file> splice: use a saved tools/list catalog for the source
|
|
64
|
+
--target-catalog <file> splice: use a saved tools/list catalog for the target
|
|
65
|
+
--fixture <file> splice: dry-run a saved source output; never execute tools
|
|
66
|
+
--fixture-format <kind> splice: decoded (default) or mcp (raw tool-result envelope)
|
|
67
|
+
--context <file> splice fixture: per-call application context as JSON
|
|
68
|
+
--restorations <file> replay: private JSON-pointer/value map for every redacted path
|
|
69
|
+
--from-recording <file> init: scaffold a successful saved run; no provider calls
|
|
70
|
+
--correction <file> correct: explicit schema replacements with positive/negative fixtures
|
|
71
|
+
--summary splice JSON: counts and byte size instead of mapped argument values
|
|
72
|
+
--allow-review splice: exit 0 for a reviewed plan; blocked plans still exit 2
|
|
73
|
+
--baseline <file> check: reviewed Toolsplice contract snapshot
|
|
74
|
+
--fail-on <policy> check: any (default), or breaking (also fails changes needing review)
|
|
75
|
+
--tool <name> snapshot: include a recorded tool (repeat for several; default: whole server)
|
|
76
|
+
--runtime emit-ts: generate callable bindings (use a .ts output, not .d.ts)
|
|
77
|
+
--out <file> Write config (new file only) or TypeScript output
|
|
78
|
+
--quiet Suppress proxy diagnostics (protocol stdout stays clean)
|
|
79
|
+
--json Doctor/check: machine-readable report
|
|
80
|
+
--check Doctor: exit 2 for stale exports or schema warnings
|
|
81
|
+
--help, -h Show this help
|
|
82
|
+
`;
|
|
83
|
+
const options = {
|
|
84
|
+
"database-env": { type: "string" },
|
|
85
|
+
"database-timeout": { type: "string" },
|
|
86
|
+
namespace: { type: "string" },
|
|
87
|
+
"no-migrate": { type: "boolean" },
|
|
88
|
+
store: { type: "string" },
|
|
89
|
+
name: { type: "string" },
|
|
90
|
+
enrich: { type: "string" },
|
|
91
|
+
"min-samples": { type: "string" },
|
|
92
|
+
"max-description": { type: "string" },
|
|
93
|
+
timeout: { type: "string" },
|
|
94
|
+
"upstream-cwd": { type: "string" },
|
|
95
|
+
url: { type: "string" },
|
|
96
|
+
"bearer-env": { type: "string" },
|
|
97
|
+
args: { type: "string" },
|
|
98
|
+
examples: { type: "string" },
|
|
99
|
+
"source-contract": { type: "string" },
|
|
100
|
+
"source-catalog": { type: "string" },
|
|
101
|
+
"target-catalog": { type: "string" },
|
|
102
|
+
"target-contract": { type: "string" },
|
|
103
|
+
fixture: { type: "string" },
|
|
104
|
+
"fixture-format": { type: "string" },
|
|
105
|
+
context: { type: "string" },
|
|
106
|
+
restorations: { type: "string" },
|
|
107
|
+
"from-recording": { type: "string" },
|
|
108
|
+
correction: { type: "string" },
|
|
109
|
+
baseline: { type: "string" },
|
|
110
|
+
"fail-on": { type: "string" },
|
|
111
|
+
tool: { type: "string", multiple: true },
|
|
112
|
+
out: { type: "string" },
|
|
113
|
+
from: { type: "string" },
|
|
114
|
+
server: { type: "string" },
|
|
115
|
+
quiet: { type: "boolean" },
|
|
116
|
+
runtime: { type: "boolean" },
|
|
117
|
+
json: { type: "boolean" },
|
|
118
|
+
summary: { type: "boolean" },
|
|
119
|
+
"allow-review": { type: "boolean" },
|
|
120
|
+
check: { type: "boolean" },
|
|
121
|
+
lenient: { type: "boolean" },
|
|
122
|
+
help: { type: "boolean", short: "h" },
|
|
123
|
+
version: { type: "boolean", short: "v" },
|
|
124
|
+
};
|
|
125
|
+
function parse(argv) {
|
|
126
|
+
const delimiter = argv.indexOf("--");
|
|
127
|
+
const own = delimiter >= 0 ? argv.slice(0, delimiter) : argv;
|
|
128
|
+
const command = own[0] && !own[0].startsWith("-") ? own.shift() : "help";
|
|
129
|
+
const parsed = parseArgs({
|
|
130
|
+
args: own,
|
|
131
|
+
options,
|
|
132
|
+
strict: true,
|
|
133
|
+
allowPositionals: true,
|
|
134
|
+
});
|
|
135
|
+
return {
|
|
136
|
+
command,
|
|
137
|
+
positional: parsed.positionals,
|
|
138
|
+
flags: parsed.values,
|
|
139
|
+
upstream: delimiter >= 0 ? argv.slice(delimiter + 1) : [],
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
const str = (v) => typeof v === "string" ? v : undefined;
|
|
143
|
+
function integer(flags, name, fallback, min = 1) {
|
|
144
|
+
const raw = str(flags[name]);
|
|
145
|
+
const value = raw === undefined ? fallback : Number(raw);
|
|
146
|
+
if (raw === "" || !Number.isSafeInteger(value) || value < min)
|
|
147
|
+
throw new Error(`--${name} must be an integer >= ${min}`);
|
|
148
|
+
return value;
|
|
149
|
+
}
|
|
150
|
+
function upstreamTransport(p) {
|
|
151
|
+
const url = str(p.flags.url);
|
|
152
|
+
if (url) {
|
|
153
|
+
if (p.upstream.length)
|
|
154
|
+
throw new Error("Choose either --url or an upstream command, not both.");
|
|
155
|
+
const parsed = new URL(url);
|
|
156
|
+
if (!["http:", "https:"].includes(parsed.protocol) ||
|
|
157
|
+
parsed.username ||
|
|
158
|
+
parsed.password)
|
|
159
|
+
throw new Error("--url must be http(s), without embedded credentials.");
|
|
160
|
+
const tokenName = str(p.flags["bearer-env"]);
|
|
161
|
+
const token = tokenName ? process.env[tokenName] : undefined;
|
|
162
|
+
if (tokenName && !token)
|
|
163
|
+
throw new Error(`Environment variable ${tokenName} is empty or not set.`);
|
|
164
|
+
return new StreamableHTTPClientTransport(parsed, token
|
|
165
|
+
? { requestInit: { headers: { Authorization: `Bearer ${token}` } } }
|
|
166
|
+
: undefined);
|
|
167
|
+
}
|
|
168
|
+
if (p.flags["bearer-env"])
|
|
169
|
+
throw new Error("--bearer-env requires --url");
|
|
170
|
+
if (!p.upstream.length)
|
|
171
|
+
throw new Error("Missing upstream: pass -- <command> [args...] or --url <url>.");
|
|
172
|
+
const [command, ...args] = p.upstream;
|
|
173
|
+
const env = Object.fromEntries(Object.entries(process.env).filter((x) => x[1] !== undefined));
|
|
174
|
+
// GUI clients often have a minimal PATH even when this CLI was launched with an absolute Node.
|
|
175
|
+
if (p.flags["database-env"])
|
|
176
|
+
delete env[String(p.flags["database-env"])];
|
|
177
|
+
env.PATH = `${dirname(process.execPath)}${delimiter}${env.PATH ?? ""}`;
|
|
178
|
+
return new StdioClientTransport({
|
|
179
|
+
command,
|
|
180
|
+
args,
|
|
181
|
+
cwd: str(p.flags["upstream-cwd"]),
|
|
182
|
+
env,
|
|
183
|
+
stderr: "inherit",
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
function config(p) {
|
|
187
|
+
const name = str(p.flags.server) ?? str(p.flags.name);
|
|
188
|
+
if (!name)
|
|
189
|
+
throw new Error("config needs --name <name> (or --server <existing-name> with --from).");
|
|
190
|
+
let entry = {};
|
|
191
|
+
let document;
|
|
192
|
+
let upstream = p.upstream;
|
|
193
|
+
const from = str(p.flags.from);
|
|
194
|
+
if (from) {
|
|
195
|
+
if (upstream.length || p.flags.url)
|
|
196
|
+
throw new Error("--from cannot be combined with an upstream command or --url.");
|
|
197
|
+
const contents = JSON.parse(readFileSync(from, "utf8"));
|
|
198
|
+
document = contents;
|
|
199
|
+
const original = contents?.mcpServers?.[name];
|
|
200
|
+
if (!original ||
|
|
201
|
+
typeof original.command !== "string" ||
|
|
202
|
+
![undefined, "stdio"].includes(original.type))
|
|
203
|
+
throw new Error(`No stdio MCP entry named ${JSON.stringify(name)} in --from file.`);
|
|
204
|
+
if (original.args !== undefined &&
|
|
205
|
+
(!Array.isArray(original.args) ||
|
|
206
|
+
original.args.some((a) => typeof a !== "string")))
|
|
207
|
+
throw new Error("Existing entry.args must be a string array.");
|
|
208
|
+
if (original.args?.includes(fileURLToPath(import.meta.url)))
|
|
209
|
+
throw new Error("This entry is already wrapped by this toolsplice installation.");
|
|
210
|
+
const { command, args, ...rest } = original;
|
|
211
|
+
entry = { ...rest };
|
|
212
|
+
upstream = [command, ...(args ?? [])];
|
|
213
|
+
}
|
|
214
|
+
if (!upstream.length && !p.flags.url)
|
|
215
|
+
throw new Error("config needs an upstream command, --url, or --from.");
|
|
216
|
+
const cli = fileURLToPath(import.meta.url);
|
|
217
|
+
const executable = cli.endsWith(".ts")
|
|
218
|
+
? ["--import", import.meta.resolve("tsx"), cli]
|
|
219
|
+
: [cli];
|
|
220
|
+
const storageArgs = p.flags["database-env"]
|
|
221
|
+
? [
|
|
222
|
+
"--database-env",
|
|
223
|
+
String(p.flags["database-env"]),
|
|
224
|
+
"--namespace",
|
|
225
|
+
str(p.flags.namespace) ?? "default",
|
|
226
|
+
...(p.flags["no-migrate"] ? ["--no-migrate"] : []),
|
|
227
|
+
]
|
|
228
|
+
: ["--store", resolve(str(p.flags.store) ?? ".mcp-shape")];
|
|
229
|
+
const args = [
|
|
230
|
+
...executable,
|
|
231
|
+
"proxy",
|
|
232
|
+
"--name",
|
|
233
|
+
name,
|
|
234
|
+
...storageArgs,
|
|
235
|
+
"--examples",
|
|
236
|
+
str(p.flags.examples) ?? "none",
|
|
237
|
+
];
|
|
238
|
+
for (const [flag, value] of [
|
|
239
|
+
["--enrich", str(p.flags.enrich)],
|
|
240
|
+
["--min-samples", str(p.flags["min-samples"])],
|
|
241
|
+
["--max-description", str(p.flags["max-description"])],
|
|
242
|
+
["--timeout", str(p.flags.timeout)],
|
|
243
|
+
["--database-timeout", str(p.flags["database-timeout"])],
|
|
244
|
+
[
|
|
245
|
+
"--upstream-cwd",
|
|
246
|
+
str(p.flags["upstream-cwd"]) ??
|
|
247
|
+
(typeof entry.cwd === "string" ? entry.cwd : undefined),
|
|
248
|
+
],
|
|
249
|
+
["--url", str(p.flags.url)],
|
|
250
|
+
["--bearer-env", str(p.flags["bearer-env"])],
|
|
251
|
+
])
|
|
252
|
+
if (value)
|
|
253
|
+
args.push(flag, value);
|
|
254
|
+
if (upstream.length)
|
|
255
|
+
args.push("--", ...upstream);
|
|
256
|
+
const servers = document?.mcpServers;
|
|
257
|
+
const output = JSON.stringify({
|
|
258
|
+
...document,
|
|
259
|
+
mcpServers: {
|
|
260
|
+
...servers,
|
|
261
|
+
[name]: { ...entry, command: process.execPath, args },
|
|
262
|
+
},
|
|
263
|
+
}, null, 2) + "\n";
|
|
264
|
+
const out = str(p.flags.out);
|
|
265
|
+
if (out)
|
|
266
|
+
writeFileSync(out, output, { mode: 0o600, flag: "wx" });
|
|
267
|
+
else
|
|
268
|
+
process.stdout.write(output);
|
|
269
|
+
}
|
|
270
|
+
async function runSplice(p, requireServer) {
|
|
271
|
+
const path = p.positional[0];
|
|
272
|
+
if (!path)
|
|
273
|
+
throw new Error("splice needs a plan.json path.");
|
|
274
|
+
const plan = parseSpliceSpec(readFileSync(path, "utf8"));
|
|
275
|
+
const endpointContract = async (endpoint, side) => {
|
|
276
|
+
const contractFile = str(p.flags[`${side}-contract`]), catalogFile = str(p.flags[`${side}-catalog`]);
|
|
277
|
+
if (contractFile)
|
|
278
|
+
return parseContractSnapshot(readFileSync(contractFile, "utf8"));
|
|
279
|
+
if (catalogFile) {
|
|
280
|
+
let catalog;
|
|
281
|
+
try {
|
|
282
|
+
catalog = JSON.parse(readFileSync(catalogFile, "utf8"));
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
throw new Error("Catalog must be a readable JSON file.");
|
|
286
|
+
}
|
|
287
|
+
return createContractFromCatalog({ name: endpoint.server }, catalog, { tools: [endpoint.tool] });
|
|
288
|
+
}
|
|
289
|
+
return createContractSnapshot(await requireServer(endpoint.server), {
|
|
290
|
+
tools: [endpoint.tool],
|
|
291
|
+
});
|
|
292
|
+
};
|
|
293
|
+
const source = await endpointContract(plan.source, "source"), target = await endpointContract(plan.target, "target");
|
|
294
|
+
const prepared = prepareSplice(plan, source, target), fixture = str(p.flags.fixture), fixtureFormat = str(p.flags["fixture-format"]) ?? "decoded";
|
|
295
|
+
if (fixtureFormat !== "decoded" && fixtureFormat !== "mcp")
|
|
296
|
+
throw new Error("--fixture-format must be decoded or mcp.");
|
|
297
|
+
const contextFile = str(p.flags.context);
|
|
298
|
+
if (contextFile && !fixture)
|
|
299
|
+
throw new Error("--context requires --fixture.");
|
|
300
|
+
let context;
|
|
301
|
+
if (contextFile) {
|
|
302
|
+
try {
|
|
303
|
+
context = JSON.parse(readFileSync(contextFile, "utf8"));
|
|
304
|
+
}
|
|
305
|
+
catch {
|
|
306
|
+
throw new Error("Context must be a readable JSON file.");
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
let mappedArguments;
|
|
310
|
+
let fixtureFailure;
|
|
311
|
+
if (fixture && prepared.report.status !== "blocked") {
|
|
312
|
+
let value;
|
|
313
|
+
try {
|
|
314
|
+
value = JSON.parse(readFileSync(fixture, "utf8"));
|
|
315
|
+
}
|
|
316
|
+
catch {
|
|
317
|
+
throw new Error("Fixture must be a readable JSON file.");
|
|
318
|
+
}
|
|
319
|
+
if (fixtureFormat === "mcp") {
|
|
320
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
321
|
+
throw new Error("An MCP fixture must contain a tool-result object.");
|
|
322
|
+
try {
|
|
323
|
+
if ("resultType" in value &&
|
|
324
|
+
value.resultType !== undefined &&
|
|
325
|
+
value.resultType !== "complete")
|
|
326
|
+
throw new Error("Non-complete result.");
|
|
327
|
+
value = decode(value);
|
|
328
|
+
}
|
|
329
|
+
catch {
|
|
330
|
+
fixtureFailure = {
|
|
331
|
+
stage: "source",
|
|
332
|
+
issues: [
|
|
333
|
+
{
|
|
334
|
+
severity: "error",
|
|
335
|
+
code: "fixture-tool-error",
|
|
336
|
+
path: "/fixture",
|
|
337
|
+
message: "The saved MCP result reports a tool failure.",
|
|
338
|
+
},
|
|
339
|
+
],
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
if (!fixtureFailure)
|
|
344
|
+
try {
|
|
345
|
+
mappedArguments = await prepared.mapOutput(value, { context });
|
|
346
|
+
}
|
|
347
|
+
catch (error) {
|
|
348
|
+
if (!(error instanceof SpliceError))
|
|
349
|
+
throw error;
|
|
350
|
+
fixtureFailure = {
|
|
351
|
+
stage: error.stage,
|
|
352
|
+
issues: error.issues,
|
|
353
|
+
explanation: explainSpliceError(plan, error),
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
const report = {
|
|
358
|
+
...prepared.report,
|
|
359
|
+
preflightStatus: prepared.report.status,
|
|
360
|
+
status: fixtureFailure ? "blocked" : prepared.report.status,
|
|
361
|
+
issues: fixtureFailure
|
|
362
|
+
? [...prepared.report.issues, ...fixtureFailure.issues]
|
|
363
|
+
: prepared.report.issues,
|
|
364
|
+
...(fixtureFailure
|
|
365
|
+
? { fixture: { valid: false, ...fixtureFailure } }
|
|
366
|
+
: mappedArguments === undefined
|
|
367
|
+
? {}
|
|
368
|
+
: { fixture: { valid: true } }),
|
|
369
|
+
...(mappedArguments === undefined
|
|
370
|
+
? {}
|
|
371
|
+
: {
|
|
372
|
+
mappingSummary: {
|
|
373
|
+
rows: mappedArguments.length,
|
|
374
|
+
argumentBytes: mappedArguments.reduce((n, row) => n + Buffer.byteLength(JSON.stringify(row)), 0),
|
|
375
|
+
},
|
|
376
|
+
...(p.flags.summary ? {} : { mappedArguments }),
|
|
377
|
+
}),
|
|
378
|
+
};
|
|
379
|
+
const out = str(p.flags.out);
|
|
380
|
+
if (out && (!out.endsWith(".ts") || out.endsWith(".d.ts")))
|
|
381
|
+
throw new Error("splice --out needs a .ts source file.");
|
|
382
|
+
if (out && report.status !== "blocked")
|
|
383
|
+
writeFileSync(out, emitSpliceModule(plan, source, target), {
|
|
384
|
+
mode: 0o600,
|
|
385
|
+
flag: "wx",
|
|
386
|
+
});
|
|
387
|
+
if (p.flags.json)
|
|
388
|
+
process.stdout.write(JSON.stringify(report, null, 2) + "\n");
|
|
389
|
+
else {
|
|
390
|
+
process.stdout.write(`${JSON.stringify(plan.source.server + "/" + plan.source.tool)} → ${JSON.stringify(plan.target.server + "/" + plan.target.tool)}: ${report.status}\n`);
|
|
391
|
+
for (const issue of report.issues)
|
|
392
|
+
process.stdout.write(` [${issue.severity}] ${issue.code} ${JSON.stringify(issue.path)}: ${issue.message}\n`);
|
|
393
|
+
process.stdout.write(` At most ${report.maxTargetCalls} target call(s); no tools called by this command.\n`);
|
|
394
|
+
if (mappedArguments !== undefined)
|
|
395
|
+
process.stdout.write(` Fixture produced ${mappedArguments.length} validated argument object(s).\n`);
|
|
396
|
+
for (const issue of fixtureFailure?.explanation?.issues ?? [])
|
|
397
|
+
for (const field of issue.fields)
|
|
398
|
+
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`);
|
|
399
|
+
if (out && report.status !== "blocked")
|
|
400
|
+
process.stdout.write(` Adapter written to ${JSON.stringify(out)}.\n`);
|
|
401
|
+
}
|
|
402
|
+
if (report.status === "blocked" ||
|
|
403
|
+
(report.status === "review" && !p.flags["allow-review"]))
|
|
404
|
+
process.exitCode = 2;
|
|
405
|
+
}
|
|
406
|
+
async function runOfflineWorkflow(p) {
|
|
407
|
+
if (p.flags.store ||
|
|
408
|
+
p.flags["database-env"] ||
|
|
409
|
+
p.upstream.length ||
|
|
410
|
+
p.flags.url)
|
|
411
|
+
throw new Error("replay/correct use artifact files only; no stores, upstream commands or connections.");
|
|
412
|
+
const file = p.positional[0];
|
|
413
|
+
if (!file || p.positional.length !== 1)
|
|
414
|
+
throw new Error(`${p.command} needs one artifact path.`);
|
|
415
|
+
const read = (path) => {
|
|
416
|
+
try {
|
|
417
|
+
return parseWorkflowJson(readFileSync(path, "utf8"));
|
|
418
|
+
}
|
|
419
|
+
catch {
|
|
420
|
+
throw new Error("Workflow artifact must be a readable bounded JSON file.");
|
|
421
|
+
}
|
|
422
|
+
};
|
|
423
|
+
let report;
|
|
424
|
+
if (p.command === "replay") {
|
|
425
|
+
if (p.flags.correction)
|
|
426
|
+
throw new Error("--correction is for correct, not replay.");
|
|
427
|
+
if (p.flags["source-catalog"] || p.flags["target-catalog"])
|
|
428
|
+
throw new Error("Candidate replay needs contract snapshots, not raw catalogs.");
|
|
429
|
+
const restorations = str(p.flags.restorations);
|
|
430
|
+
const replay = await replaySpliceRecording(read(file), {
|
|
431
|
+
...(restorations
|
|
432
|
+
? { restorations: read(restorations) }
|
|
433
|
+
: {}),
|
|
434
|
+
...(str(p.flags["source-contract"])
|
|
435
|
+
? {
|
|
436
|
+
sourceContract: parseContractSnapshot(read(str(p.flags["source-contract"]))),
|
|
437
|
+
}
|
|
438
|
+
: {}),
|
|
439
|
+
...(str(p.flags["target-contract"])
|
|
440
|
+
? {
|
|
441
|
+
targetContract: parseContractSnapshot(read(str(p.flags["target-contract"]))),
|
|
442
|
+
}
|
|
443
|
+
: {}),
|
|
444
|
+
...(p.flags["allow-review"] ? { allowReview: true } : {}),
|
|
445
|
+
});
|
|
446
|
+
const { result, ...summary } = replay;
|
|
447
|
+
report = {
|
|
448
|
+
...summary,
|
|
449
|
+
...(result
|
|
450
|
+
? {
|
|
451
|
+
resultSummary: {
|
|
452
|
+
count: result.length,
|
|
453
|
+
bytes: Buffer.byteLength(JSON.stringify(result)),
|
|
454
|
+
},
|
|
455
|
+
}
|
|
456
|
+
: {}),
|
|
457
|
+
};
|
|
458
|
+
if (!replay.matched ||
|
|
459
|
+
(replay.upgrade && replay.upgrade.status !== "passed"))
|
|
460
|
+
process.exitCode = 2;
|
|
461
|
+
if (p.flags.out)
|
|
462
|
+
writeFileSync(str(p.flags.out), JSON.stringify(report, null, 2) + "\n", {
|
|
463
|
+
mode: 0o600,
|
|
464
|
+
flag: "wx",
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
else {
|
|
468
|
+
if (p.flags.restorations)
|
|
469
|
+
throw new Error("--restorations is for replay, not correct.");
|
|
470
|
+
const manifestFile = str(p.flags.correction);
|
|
471
|
+
if (!manifestFile)
|
|
472
|
+
throw new Error("correct requires --correction <manifest.json>.");
|
|
473
|
+
const result = await applyContractCorrection(parseContractSnapshot(read(file)), parseContractCorrection(read(manifestFile)));
|
|
474
|
+
const out = str(p.flags.out);
|
|
475
|
+
if (out) {
|
|
476
|
+
const contents = JSON.stringify(result.corrected, null, 2) + "\n";
|
|
477
|
+
if (Buffer.byteLength(contents) > JSON_LIMIT)
|
|
478
|
+
throw new Error("Serialized corrected contract exceeds the 5 MiB limit.");
|
|
479
|
+
writeFileSync(out, contents, {
|
|
480
|
+
mode: 0o600,
|
|
481
|
+
flag: "wx",
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
report = {
|
|
485
|
+
status: out ? "written" : "validated",
|
|
486
|
+
baseFingerprint: result.original.fingerprint,
|
|
487
|
+
correctedFingerprint: result.corrected.fingerprint,
|
|
488
|
+
correction: result.corrected.correction,
|
|
489
|
+
fixtures: result.fixtures,
|
|
490
|
+
comparison: result.comparison,
|
|
491
|
+
networkCalls: 0,
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
if (p.flags.json)
|
|
495
|
+
process.stdout.write(JSON.stringify(report, null, 2) + "\n");
|
|
496
|
+
else if (p.command === "replay") {
|
|
497
|
+
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`);
|
|
498
|
+
if (report.upgrade)
|
|
499
|
+
process.stdout.write(`Candidate fixture check: ${report.upgrade.status}.\n`);
|
|
500
|
+
}
|
|
501
|
+
else
|
|
502
|
+
process.stdout.write(`Correction ${report.status}; all positive/negative fixtures passed, zero network calls.\n`);
|
|
503
|
+
}
|
|
504
|
+
async function runProject(p) {
|
|
505
|
+
if (p.flags.store ||
|
|
506
|
+
p.flags["database-env"] ||
|
|
507
|
+
p.upstream.length ||
|
|
508
|
+
p.flags.url)
|
|
509
|
+
throw new Error("init/project use local artifacts only; no stores or upstream connections.");
|
|
510
|
+
if (p.positional.length !== 1)
|
|
511
|
+
throw new Error(`${p.command} needs one directory.`);
|
|
512
|
+
if (p.flags["source-contract"] ||
|
|
513
|
+
p.flags["target-contract"] ||
|
|
514
|
+
p.flags["source-catalog"] ||
|
|
515
|
+
p.flags["target-catalog"])
|
|
516
|
+
throw new Error("Projects use their saved contract files; use replay with candidate contracts to check an upgrade.");
|
|
517
|
+
if (p.flags.out)
|
|
518
|
+
throw new Error("init/project write only the new project directory or print a check report.");
|
|
519
|
+
if (p.command === "project") {
|
|
520
|
+
if (p.flags["from-recording"] || p.flags.restorations)
|
|
521
|
+
throw new Error("--from-recording and --restorations are for init/replay.");
|
|
522
|
+
const report = await checkSpliceProject(p.positional[0]);
|
|
523
|
+
if (report.status === "blocked" ||
|
|
524
|
+
(report.status === "review" && !p.flags["allow-review"]))
|
|
525
|
+
process.exitCode = 2;
|
|
526
|
+
process.stdout.write(p.flags.json
|
|
527
|
+
? JSON.stringify(report, null, 2) + "\n"
|
|
528
|
+
: `Project ${report.status}; zero tool/network calls.\n`);
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
const from = str(p.flags["from-recording"]), restore = str(p.flags.restorations);
|
|
532
|
+
const read = (file) => {
|
|
533
|
+
try {
|
|
534
|
+
return parseWorkflowJson(readFileSync(file, "utf8"));
|
|
535
|
+
}
|
|
536
|
+
catch {
|
|
537
|
+
throw new Error("Project source must be a readable bounded JSON artifact.");
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
const result = await initializeSpliceProject(p.positional[0], {
|
|
541
|
+
...(from
|
|
542
|
+
? {
|
|
543
|
+
recording: read(from),
|
|
544
|
+
}
|
|
545
|
+
: {}),
|
|
546
|
+
...(restore
|
|
547
|
+
? { restorations: read(restore) }
|
|
548
|
+
: {}),
|
|
549
|
+
});
|
|
550
|
+
const report = {
|
|
551
|
+
...result,
|
|
552
|
+
nextArgs: ["project", result.directory, "--allow-review", "--json"],
|
|
553
|
+
networkCalls: 0,
|
|
554
|
+
toolCalls: 0,
|
|
555
|
+
};
|
|
556
|
+
process.stdout.write(p.flags.json
|
|
557
|
+
? JSON.stringify(report, null, 2) + "\n"
|
|
558
|
+
: `Created ${result.origin} starter in ${JSON.stringify(result.directory)}.\nCheck it with toolsplice project <directory> --allow-review --json. No tools were called.\n`);
|
|
559
|
+
}
|
|
560
|
+
async function main() {
|
|
561
|
+
const p = parse(process.argv.slice(2));
|
|
562
|
+
if (p.flags.version) {
|
|
563
|
+
process.stdout.write(VERSION + "\n");
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
if (p.flags.help || ["help", "--help"].includes(p.command)) {
|
|
567
|
+
process.stdout.write(USAGE);
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
const examples = (str(p.flags.examples) ?? "none");
|
|
571
|
+
if (!["none", "safe", "all"].includes(examples))
|
|
572
|
+
throw new Error(`Unknown --examples policy: ${examples}`);
|
|
573
|
+
const log = (message) => {
|
|
574
|
+
if (!p.flags.quiet)
|
|
575
|
+
process.stderr.write(`[toolsplice] ${message}\n`);
|
|
576
|
+
};
|
|
577
|
+
const storeWarnings = [];
|
|
578
|
+
const databaseEnv = str(p.flags["database-env"]);
|
|
579
|
+
if (p.flags["database-env"] !== undefined && !databaseEnv)
|
|
580
|
+
throw new Error("--database-env must name an environment variable.");
|
|
581
|
+
if (databaseEnv && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(databaseEnv))
|
|
582
|
+
throw new Error("--database-env must name an environment variable.");
|
|
583
|
+
if (databaseEnv && p.flags.store)
|
|
584
|
+
throw new Error("Use either --store or --database-env.");
|
|
585
|
+
if (!databaseEnv &&
|
|
586
|
+
(p.flags.namespace !== undefined ||
|
|
587
|
+
p.flags["no-migrate"] ||
|
|
588
|
+
p.flags["database-timeout"] !== undefined))
|
|
589
|
+
throw new Error("--namespace, --no-migrate and --database-timeout require --database-env.");
|
|
590
|
+
if (p.flags.namespace !== undefined) {
|
|
591
|
+
const name = String(p.flags.namespace);
|
|
592
|
+
if (!name || name.includes("\0") || Buffer.byteLength(name) > 256)
|
|
593
|
+
throw new Error("--namespace must be nonempty, contain no NUL and fit 256 UTF-8 bytes.");
|
|
594
|
+
}
|
|
595
|
+
const databaseTimeout = integer(p.flags, "database-timeout", 1000, 50);
|
|
596
|
+
if (databaseTimeout > 60000)
|
|
597
|
+
throw new Error("--database-timeout must be <= 60000.");
|
|
598
|
+
const minSamples = integer(p.flags, "min-samples", 1);
|
|
599
|
+
if (p.flags.timeout !== undefined)
|
|
600
|
+
integer(p.flags, "timeout", 600_000);
|
|
601
|
+
if (p.flags["max-description"] !== undefined)
|
|
602
|
+
integer(p.flags, "max-description", 2000, 80);
|
|
603
|
+
const enrich = (str(p.flags.enrich) ?? "description");
|
|
604
|
+
if (!["description", "none", "schema"].includes(enrich))
|
|
605
|
+
throw new Error(`Unknown --enrich mode: ${enrich}`);
|
|
606
|
+
if (p.command === "config") {
|
|
607
|
+
config(p);
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
if (["replay", "correct"].includes(p.command)) {
|
|
611
|
+
await runOfflineWorkflow(p);
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
if (["init", "project"].includes(p.command)) {
|
|
615
|
+
await runProject(p);
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
if (p.command === "splice" &&
|
|
619
|
+
[
|
|
620
|
+
"source-contract",
|
|
621
|
+
"target-contract",
|
|
622
|
+
"source-catalog",
|
|
623
|
+
"target-catalog",
|
|
624
|
+
].some((key) => p.flags[key] !== undefined)) {
|
|
625
|
+
for (const side of ["source", "target"]) {
|
|
626
|
+
if ([
|
|
627
|
+
str(p.flags[`${side}-contract`]),
|
|
628
|
+
str(p.flags[`${side}-catalog`]),
|
|
629
|
+
].filter(Boolean).length !== 1)
|
|
630
|
+
throw new Error("Use both --source-contract and --target-contract, or supply exactly one contract/catalog file for each endpoint.");
|
|
631
|
+
}
|
|
632
|
+
if (p.flags.store || databaseEnv)
|
|
633
|
+
throw new Error("Use contract files or a learning store, not both.");
|
|
634
|
+
await runSplice(p);
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
637
|
+
const storeLocation = databaseEnv
|
|
638
|
+
? `postgres:${str(p.flags.namespace) ?? "default"}`
|
|
639
|
+
: resolve(str(p.flags.store) ?? ".mcp-shape");
|
|
640
|
+
let store;
|
|
641
|
+
if (databaseEnv) {
|
|
642
|
+
const connectionString = process.env[databaseEnv];
|
|
643
|
+
if (!connectionString)
|
|
644
|
+
throw new Error(`Storage environment variable ${databaseEnv} is not set.`);
|
|
645
|
+
const { PostgresShapeStore } = await import("./postgres.js");
|
|
646
|
+
store = new PostgresShapeStore({
|
|
647
|
+
connectionString,
|
|
648
|
+
namespace: str(p.flags.namespace),
|
|
649
|
+
migrate: !p.flags["no-migrate"],
|
|
650
|
+
timeoutMs: databaseTimeout,
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
else
|
|
654
|
+
store = new ShapeStore(storeLocation, {
|
|
655
|
+
onWarning: (message) => {
|
|
656
|
+
storeWarnings.push(message);
|
|
657
|
+
log(message);
|
|
658
|
+
},
|
|
659
|
+
});
|
|
660
|
+
let keepOpen = false;
|
|
661
|
+
try {
|
|
662
|
+
const requireServer = async (name) => {
|
|
663
|
+
if (!name)
|
|
664
|
+
throw new Error(`${p.command} needs a server name (see doctor or show).`);
|
|
665
|
+
if (!(await store.has(name)))
|
|
666
|
+
throw new Error(`Nothing learned for ${JSON.stringify(name)}. Use the proxy or probe first.`);
|
|
667
|
+
return store.load(name);
|
|
668
|
+
};
|
|
669
|
+
switch (p.command) {
|
|
670
|
+
case "proxy": {
|
|
671
|
+
const transport = upstreamTransport(p);
|
|
672
|
+
const startup = new AbortController();
|
|
673
|
+
let proxy;
|
|
674
|
+
let closing = false;
|
|
675
|
+
const close = async () => {
|
|
676
|
+
if (closing)
|
|
677
|
+
return;
|
|
678
|
+
closing = true;
|
|
679
|
+
startup.abort();
|
|
680
|
+
if (proxy)
|
|
681
|
+
await proxy.close();
|
|
682
|
+
else
|
|
683
|
+
await transport.close().catch(() => { });
|
|
684
|
+
await store.close?.();
|
|
685
|
+
};
|
|
686
|
+
// Install these before spawning/initializing an upstream process: slow or broken startup
|
|
687
|
+
// must not leave its child behind when the host cancels this CLI.
|
|
688
|
+
process.once("SIGINT", () => {
|
|
689
|
+
void close();
|
|
690
|
+
});
|
|
691
|
+
process.once("SIGTERM", () => {
|
|
692
|
+
void close();
|
|
693
|
+
});
|
|
694
|
+
process.stdin.once("end", () => {
|
|
695
|
+
void close();
|
|
696
|
+
});
|
|
697
|
+
try {
|
|
698
|
+
proxy = await createProxy(transport, {
|
|
699
|
+
store,
|
|
700
|
+
serverName: str(p.flags.name),
|
|
701
|
+
enrich,
|
|
702
|
+
minSamples,
|
|
703
|
+
examples,
|
|
704
|
+
log,
|
|
705
|
+
signal: startup.signal,
|
|
706
|
+
callTimeoutMs: integer(p.flags, "timeout", 600_000),
|
|
707
|
+
maxDescriptionLength: integer(p.flags, "max-description", 2000, 80),
|
|
708
|
+
});
|
|
709
|
+
if (closing) {
|
|
710
|
+
await proxy.close();
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
proxy.server.onclose = () => {
|
|
714
|
+
void close();
|
|
715
|
+
};
|
|
716
|
+
await proxy.server.connect(new StdioServerTransport());
|
|
717
|
+
keepOpen = !closing;
|
|
718
|
+
log(`Proxying ${JSON.stringify(proxy.serverName)} (enrich: ${enrich}; examples: ${examples})`);
|
|
719
|
+
}
|
|
720
|
+
catch (error) {
|
|
721
|
+
if (!startup.signal.aborted) {
|
|
722
|
+
await close();
|
|
723
|
+
throw error;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
case "probe": {
|
|
729
|
+
const argsFile = str(p.flags.args);
|
|
730
|
+
const args = argsFile
|
|
731
|
+
? JSON.parse(readFileSync(argsFile, "utf8"))
|
|
732
|
+
: undefined;
|
|
733
|
+
if (args !== undefined &&
|
|
734
|
+
(!args ||
|
|
735
|
+
Array.isArray(args) ||
|
|
736
|
+
typeof args !== "object" ||
|
|
737
|
+
Object.values(args).some((v) => !Array.isArray(v) ||
|
|
738
|
+
v.some((a) => !a || typeof a !== "object" || Array.isArray(a)))))
|
|
739
|
+
throw new Error("--args must contain an object of tool names to arrays of argument objects.");
|
|
740
|
+
const transport = upstreamTransport(p);
|
|
741
|
+
const abort = new AbortController();
|
|
742
|
+
const cancel = () => {
|
|
743
|
+
abort.abort();
|
|
744
|
+
void transport.close().catch(() => { });
|
|
745
|
+
};
|
|
746
|
+
process.once("SIGINT", cancel);
|
|
747
|
+
process.once("SIGTERM", cancel);
|
|
748
|
+
let report;
|
|
749
|
+
try {
|
|
750
|
+
report = await probe(transport, {
|
|
751
|
+
store,
|
|
752
|
+
serverName: str(p.flags.name),
|
|
753
|
+
args,
|
|
754
|
+
examples,
|
|
755
|
+
timeoutMs: integer(p.flags, "timeout", 60_000),
|
|
756
|
+
signal: abort.signal,
|
|
757
|
+
});
|
|
758
|
+
}
|
|
759
|
+
catch (error) {
|
|
760
|
+
if (abort.signal.aborted)
|
|
761
|
+
return;
|
|
762
|
+
throw error;
|
|
763
|
+
}
|
|
764
|
+
finally {
|
|
765
|
+
process.removeListener("SIGINT", cancel);
|
|
766
|
+
process.removeListener("SIGTERM", cancel);
|
|
767
|
+
}
|
|
768
|
+
const width = Math.max(4, ...report.rows.map((r) => r.tool.length));
|
|
769
|
+
process.stdout.write(`Probed ${JSON.stringify(report.serverName)}\n`);
|
|
770
|
+
for (const row of report.rows)
|
|
771
|
+
process.stdout.write(` ${row.tool.padEnd(width)} ${row.status.padEnd(7)} ${row.status === "called" ? row.kinds.join(", ") : row.reason}\n`);
|
|
772
|
+
if (report.rows.some((r) => r.status === "failed"))
|
|
773
|
+
process.exitCode = 2;
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
case "doctor": {
|
|
777
|
+
const names = p.positional.length ? p.positional : await store.list();
|
|
778
|
+
const reports = await Promise.all(names.map(async (n) => diagnose(await requireServer(n), minSamples)));
|
|
779
|
+
const storage = (await store.diagnostics?.()) ?? [];
|
|
780
|
+
if (p.flags.json)
|
|
781
|
+
process.stdout.write(JSON.stringify({
|
|
782
|
+
store: storeLocation,
|
|
783
|
+
servers: reports,
|
|
784
|
+
warnings: storeWarnings,
|
|
785
|
+
storage,
|
|
786
|
+
}, null, 2) + "\n");
|
|
787
|
+
else if (!reports.length)
|
|
788
|
+
process.stdout.write(`No learning in ${storeLocation}. Generate an MCP config with config, then use its tools normally.\n`);
|
|
789
|
+
else
|
|
790
|
+
for (const report of reports)
|
|
791
|
+
process.stdout.write(formatDoctor(report));
|
|
792
|
+
if (!p.flags.json && storage.length) {
|
|
793
|
+
for (const item of storage)
|
|
794
|
+
process.stdout.write(`Storage: ${item.kind}, owner ${item.owner}${item.pid ? ` (PID ${item.pid})` : ""}: ${item.file}\n`);
|
|
795
|
+
process.stdout.write("Inspect abandoned artifacts before removing them; active writers are never automatically unlocked.\n");
|
|
796
|
+
}
|
|
797
|
+
const abandoned = storage.some((s) => s.owner !== "running");
|
|
798
|
+
if (p.flags.check &&
|
|
799
|
+
(abandoned ||
|
|
800
|
+
storeWarnings.length > 0 ||
|
|
801
|
+
reports.some((r) => r.export === "stale" || r.totals.warning > 0)))
|
|
802
|
+
process.exitCode = 2;
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
805
|
+
case "show": {
|
|
806
|
+
const names = p.positional.length ? p.positional : await store.list();
|
|
807
|
+
if (!names.length)
|
|
808
|
+
throw new Error(`Nothing learned yet in ${storeLocation}`);
|
|
809
|
+
for (const name of names) {
|
|
810
|
+
const server = await requireServer(name);
|
|
811
|
+
process.stdout.write(`${server.name}${server.version ? ` v${server.version}` : ""}\n`);
|
|
812
|
+
for (const tool of Object.values(server.tools)) {
|
|
813
|
+
const kinds = Object.entries(tool.kinds)
|
|
814
|
+
.filter(([, n]) => n > 0)
|
|
815
|
+
.map(([k, n]) => `${k}×${n}`)
|
|
816
|
+
.join(" ");
|
|
817
|
+
process.stdout.write(` ${tool.name} [${tool.calls} call(s)${kinds ? `: ${kinds}` : ""}]\n`);
|
|
818
|
+
const summary = describeOutput(tool);
|
|
819
|
+
if (summary)
|
|
820
|
+
process.stdout.write(` ${summary}\n`);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
return;
|
|
824
|
+
}
|
|
825
|
+
case "splice": {
|
|
826
|
+
await runSplice(p, requireServer);
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
case "snapshot": {
|
|
830
|
+
const server = await requireServer(p.positional[0]);
|
|
831
|
+
const tools = Array.isArray(p.flags.tool) ? p.flags.tool : undefined;
|
|
832
|
+
const snapshot = createContractSnapshot(server, tools === undefined ? {} : { tools });
|
|
833
|
+
const out = str(p.flags.out), contents = JSON.stringify(snapshot, null, 2) + "\n";
|
|
834
|
+
if (Buffer.byteLength(contents) > 5 * 1024 * 1024)
|
|
835
|
+
throw new Error("Serialized contract snapshot exceeds the 5 MiB limit; select fewer tools with --tool.");
|
|
836
|
+
if (out)
|
|
837
|
+
writeFileSync(out, contents, { mode: 0o600, flag: "wx" });
|
|
838
|
+
else
|
|
839
|
+
process.stdout.write(contents);
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
842
|
+
case "check": {
|
|
843
|
+
const baselinePath = str(p.flags.baseline);
|
|
844
|
+
if (!baselinePath)
|
|
845
|
+
throw new Error("check requires --baseline <file>.");
|
|
846
|
+
const failOn = str(p.flags["fail-on"]) ?? "any";
|
|
847
|
+
if (failOn !== "any" && failOn !== "breaking")
|
|
848
|
+
throw new Error("--fail-on must be any or breaking.");
|
|
849
|
+
const baseline = parseContractSnapshot(readFileSync(baselinePath, "utf8"));
|
|
850
|
+
const server = await requireServer(p.positional[0]);
|
|
851
|
+
const names = baseline.selection === "subset"
|
|
852
|
+
? baseline.tools
|
|
853
|
+
.map((t) => t.name)
|
|
854
|
+
.filter((n) => Object.hasOwn(server.tools, n))
|
|
855
|
+
: undefined;
|
|
856
|
+
const report = compareContractSnapshots(baseline, createContractSnapshot(server, names === undefined ? {} : { tools: names }));
|
|
857
|
+
if (p.flags.json)
|
|
858
|
+
process.stdout.write(JSON.stringify(report, null, 2) + "\n");
|
|
859
|
+
else {
|
|
860
|
+
process.stdout.write(`${JSON.stringify(report.server)}: contract ${report.status}\n`);
|
|
861
|
+
for (const change of report.changes)
|
|
862
|
+
process.stdout.write(` [${change.severity}] ${JSON.stringify(change.path)}: ${change.message}\n`);
|
|
863
|
+
if (report.truncated)
|
|
864
|
+
process.stdout.write(" Additional changes omitted; review is required.\n");
|
|
865
|
+
process.stdout.write(report.note + "\n");
|
|
866
|
+
}
|
|
867
|
+
if (contractCheckFailed(report, failOn))
|
|
868
|
+
process.exitCode = 2;
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
case "emit-ts": {
|
|
872
|
+
const server = await requireServer(p.positional[0]);
|
|
873
|
+
const out = str(p.flags.out);
|
|
874
|
+
if (p.flags.runtime &&
|
|
875
|
+
out &&
|
|
876
|
+
(!out.endsWith(".ts") || out.endsWith(".d.ts")))
|
|
877
|
+
throw new Error("--runtime output must be a .ts source file, not .d.ts.");
|
|
878
|
+
const code = p.flags.runtime
|
|
879
|
+
? emitBindings(server)
|
|
880
|
+
: emitModule(server);
|
|
881
|
+
if (out)
|
|
882
|
+
writeFileSync(out, code, { mode: 0o600 });
|
|
883
|
+
else
|
|
884
|
+
process.stdout.write(code);
|
|
885
|
+
const fingerprint = exportFingerprint(server);
|
|
886
|
+
await store.transact(server.name, (latest) => {
|
|
887
|
+
latest.exportedAt = new Date().toISOString();
|
|
888
|
+
// Stamp the exact contract that was exported, even if another process learned more meanwhile.
|
|
889
|
+
latest.exportedFingerprint = fingerprint;
|
|
890
|
+
});
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
case "schema": {
|
|
894
|
+
const toolName = p.positional[1];
|
|
895
|
+
const server = await requireServer(p.positional[0]);
|
|
896
|
+
if (!toolName || !Object.hasOwn(server.tools, toolName))
|
|
897
|
+
throw new Error("schema needs a recorded <server> <tool>.");
|
|
898
|
+
const tool = server.tools[toolName];
|
|
899
|
+
process.stdout.write(JSON.stringify(toJsonSchema(tool.shape, {
|
|
900
|
+
mode: p.flags.lenient ? "lenient" : "docs",
|
|
901
|
+
}), null, 2) + "\n");
|
|
902
|
+
return;
|
|
903
|
+
}
|
|
904
|
+
case "forget": {
|
|
905
|
+
const server = await requireServer(p.positional[0]);
|
|
906
|
+
await store.remove(server.name);
|
|
907
|
+
process.stdout.write(`Removed local learning for ${JSON.stringify(server.name)}.\n`);
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
default:
|
|
911
|
+
throw new Error(`Unknown command ${JSON.stringify(p.command)}. Run toolsplice --help.`);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
finally {
|
|
915
|
+
if (!keepOpen)
|
|
916
|
+
await store.close?.();
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
main().catch((error) => {
|
|
920
|
+
// No stacks or upstream response bodies: stderr is often captured in agent logs.
|
|
921
|
+
process.stderr.write(`toolsplice: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
922
|
+
process.exitCode = 1;
|
|
923
|
+
});
|