toolsplice-core 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 toolsplice contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,29 @@
1
- # Temporary Holding Version
1
+ # Toolsplice Core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The standalone Node.js library for explicit MCP output-to-input handoffs. It includes validation, catalog contracts, generated typed adapters, recordings/replay, field-origin explanations and reviewed contract corrections.
4
+
5
+ **No MCP SDK, transport/server stack, Zod, PostgreSQL driver or Cloudflare service is required.** Production dependencies are Ajv and re2js. Your application supplies its own tool callers; the full `toolsplice` package supplies the CLI, SDK convenience adapters, learning proxy and optional PostgreSQL support.
6
+
7
+ Install with `npm install toolsplice-core@0.0.1`. For local development, build this checkout with `npm run build`, then pack `packages/core` and install that local tarball in your application.
8
+
9
+ ```ts
10
+ import { createContractFromCatalog, prepareSplice, type ToolCaller } from 'toolsplice-core';
11
+
12
+ // Ordinary saved tools/list responses; identities are application-selected.
13
+ const source = createContractFromCatalog({ name: 'documents' }, sourceCatalog);
14
+ const target = createContractFromCatalog({ name: 'artifacts' }, targetCatalog);
15
+ const adapter = prepareSplice(plan, source, target);
16
+
17
+ // Return raw MCP result objects. Authentication, authorization and connections stay in your app.
18
+ const read: ToolCaller = (request, options) => yourClient.callSource(request, options);
19
+ const write: ToolCaller = (request, options) => yourClient.callTarget(request, options);
20
+ const result = await adapter.run(read, write, input, { allowReview: true });
21
+ ```
22
+
23
+ Use `emitSpliceModule(plan, source, target)` to generate a TypeScript adapter importing `toolsplice-core` by default. Supply `runtimeImport` explicitly to override it. Generated adapters and the library use the same runtime guards.
24
+
25
+ `createSpliceRecorder` defaults to metadata only; explicitly opt in to payload capture. `replaySpliceRecording` consumes saved responses with no network connections. Pass `sourceContract` and/or `targetContract` to test captured cases against candidate contracts. `upgrade.status` distinguishes passed, failed and inconclusive checks; a previously failed recording cannot establish successful upgrade compatibility. Fixtures are evidence for those cases, not universal provider guarantees.
26
+
27
+ `applyContractCorrection` requires a pinned baseline, a reason and both accepted/rejected fixtures for every replacement. Applications explicitly choose corrected contracts. `explainSpliceError` reports field paths without literal values or raw causes.
28
+
29
+ Redaction is configurable and is not guaranteed anonymization. Replay is not durable job recovery, rollback or proof of committed effects. The library makes no automatic semantic joins, coercions or retries. Node 22+, ESM.
@@ -0,0 +1,44 @@
1
+ import type { JsonSchema } from "./schema.js";
2
+ import { type ServerRecord, type ToolRecord } from "./store.js";
3
+ export interface TsOptions {
4
+ compact: boolean;
5
+ }
6
+ export declare const MAX_OUTPUT_DESCRIPTION_LENGTH = 2000;
7
+ export interface TsParts {
8
+ type: string;
9
+ /** Named definitions the main type refers to, as [name, body]. */
10
+ aliases: [string, string][];
11
+ }
12
+ export declare function schemaToTsParts(schema: JsonSchema, options?: TsOptions & {
13
+ aliasPrefix?: string;
14
+ usedNames?: Set<string>;
15
+ }): TsParts;
16
+ /** A self-contained rendering: named recursive types follow as `where Node = ...` (compact) or `type` lines. */
17
+ export declare function schemaToTs(schema: JsonSchema, options?: TsOptions): string;
18
+ /** True when `type` contains `|` or `&` outside any brackets, strings or comments. */
19
+ export declare function hasTopLevelOperator(type: string): boolean;
20
+ export declare function pascalCase(name: string): string;
21
+ /** One line describing what a tool returns, for appending to its description. */
22
+ export declare function describeOutput(tool: ToolRecord, options?: {
23
+ maxLength?: number;
24
+ }): string | undefined;
25
+ export interface ModuleOptions {
26
+ /** Name of the generated interface; defaults to the server name in PascalCase. */
27
+ interfaceName?: string;
28
+ /**
29
+ * learned: full output types. unknown: untyped (code mode without toolsplice).
30
+ * description: untyped, but each method's doc carries the one-line summary that
31
+ * `proxy --enrich description` appends to tool descriptions.
32
+ */
33
+ outputs?: "learned" | "unknown" | "description";
34
+ /** Replaces the comment explaining what a call returns. */
35
+ header?: string[];
36
+ }
37
+ export interface BindingModuleOptions extends Omit<ModuleOptions, "outputs"> {
38
+ /** Module specifier for Toolsplice's runtime. Default: toolsplice. */
39
+ runtimeImport?: string;
40
+ }
41
+ export declare const DEFAULT_HEADER: string[];
42
+ export declare function emitModule(server: ServerRecord, options?: ModuleOptions): string;
43
+ /** Emits a real .ts module containing types and a callable create<Interface> factory. */
44
+ export declare function emitBindings(server: ServerRecord, options?: BindingModuleOptions): string;
@@ -0,0 +1,479 @@
1
+ // Renders JSON Schema as TypeScript, either as a full .d.ts module with JSDoc
2
+ // or as a compact one-line signature cheap enough to append to a tool description.
3
+ import { toolOutput } from "./store.js";
4
+ const COMPACT_MAX_FIELDS = 25;
5
+ const MAX_COMMENT_LENGTH = 1000;
6
+ export const MAX_OUTPUT_DESCRIPTION_LENGTH = 2000;
7
+ const RESERVED_NAMES = new Set(["Array", "Record", "Promise", "String", "Number", "Boolean", "Object", "Function", "Symbol", "Date", "Map", "Set", "Unknown", "Any", "Never", "Null", "Undefined"]);
8
+ const RESERVED_BINDINGS = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with implements interface let package private protected public static yield await any unknown never number string boolean undefined object intrinsic keyof unique readonly infer is asserts abstract declare namespace module require global".split(" "));
9
+ function allocateName(base, used) {
10
+ let name = base;
11
+ for (let i = 2; used.has(name) || RESERVED_NAMES.has(name); i++)
12
+ name = `${base}${i}`;
13
+ used.add(name);
14
+ return name;
15
+ }
16
+ /** Text is data even when a server supplies comment delimiters or line separators. */
17
+ function commentText(text, limit = MAX_COMMENT_LENGTH) {
18
+ return text.slice(0, limit).replace(/\*\//g, "*\\/").replace(/\/\*/g, "/ *").replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]/g, " ");
19
+ }
20
+ export function schemaToTsParts(schema, options = { compact: false }) {
21
+ const ctx = { root: schema, compact: options.compact, depth: 0, seenRefs: new Set(), aliases: new Map(), aliasPrefix: options.aliasPrefix ? pascalCase(options.aliasPrefix) : "", refNames: new Map(), usedNames: options.usedNames ?? new Set(), budget: { remaining: options.compact ? 500 : 10000, characters: options.compact ? 20_000 : 1_000_000 }, renderDepth: 0, guardDepth: 0, activeRefs: new Map() };
22
+ const type = render(schema, ctx);
23
+ if (options.compact && type.length + [...ctx.aliases].reduce((n, [a, b]) => n + a.length + b.length + 5, 0) > 4000)
24
+ return { type: "unknown /* summary omitted: large schema */", aliases: [] };
25
+ return { type, aliases: [...ctx.aliases] };
26
+ }
27
+ /** A self-contained rendering: named recursive types follow as `where Node = ...` (compact) or `type` lines. */
28
+ export function schemaToTs(schema, options = { compact: false }) {
29
+ const { type, aliases } = schemaToTsParts(schema, options);
30
+ if (!aliases.length)
31
+ return type;
32
+ if (options.compact)
33
+ return `${type} where ${aliases.map(([n, b]) => `${n} = ${b}`).join("; ")}`;
34
+ return `${type}
35
+ ${aliases.map(([n, b]) => `type ${n} = ${b};`).join("\n")}`;
36
+ }
37
+ function render(schema, ctx) {
38
+ if (--ctx.budget.remaining < 0 || ctx.renderDepth >= 64)
39
+ return "unknown";
40
+ ctx = { ...ctx, renderDepth: ctx.renderDepth + 1 };
41
+ const result = renderBody(schema, ctx);
42
+ if (result.length > ctx.budget.characters)
43
+ return "unknown";
44
+ ctx.budget.characters -= result.length;
45
+ return result;
46
+ }
47
+ function renderBody(schema, ctx) {
48
+ if (schema === undefined || schema === true)
49
+ return "unknown";
50
+ if (schema === false)
51
+ return "never";
52
+ if (schema === null || typeof schema !== "object")
53
+ return "unknown";
54
+ if (typeof schema.$ref === "string")
55
+ return renderRef(schema.$ref, ctx);
56
+ if (Array.isArray(schema.enum) && schema.enum.length > ctx.budget.remaining)
57
+ return "unknown";
58
+ if (Array.isArray(schema.enum))
59
+ return schema.enum.map((v) => (boundedLiteral(v) ?? "unknown")).join(" | ") || "never";
60
+ if (Object.hasOwn(schema, "const"))
61
+ return boundedLiteral(schema.const) ?? "unknown";
62
+ const union = (schema.anyOf ?? schema.oneOf);
63
+ if (Array.isArray(union) && union.length > ctx.budget.remaining)
64
+ return "unknown";
65
+ if (Array.isArray(union))
66
+ return joinUnion(union.map((s) => render(s, ctx)));
67
+ if (Array.isArray(schema.allOf) && schema.allOf.length > ctx.budget.remaining)
68
+ return "unknown";
69
+ if (Array.isArray(schema.allOf))
70
+ return schema.allOf.map((s) => wrap(render(s, ctx))).join(" & ") || "unknown";
71
+ const type = schema.type;
72
+ if (Array.isArray(type))
73
+ return joinUnion(type.map((t) => render({ ...schema, type: t }, ctx)));
74
+ switch (type) {
75
+ case "string":
76
+ return withHint("string", stringHint(schema, ctx), ctx);
77
+ case "integer":
78
+ case "number":
79
+ return withHint("number", numberHint(schema), ctx);
80
+ case "boolean":
81
+ return "boolean";
82
+ case "null":
83
+ return "null";
84
+ case "array":
85
+ return renderArray(schema, ctx);
86
+ case "object":
87
+ return renderObject(schema, ctx);
88
+ default:
89
+ // Without an explicit type, properties/items only constrain instances of that type.
90
+ // Other JSON types remain valid; an object-only or array-only rendering would narrow it.
91
+ return withHint("unknown", typeof schema["x-hint"] === "string" ? schema["x-hint"] : undefined, ctx);
92
+ }
93
+ }
94
+ function renderRef(ref, ctx) {
95
+ if (ref !== "#" && !ref.startsWith("#/"))
96
+ return "unknown";
97
+ let target = ctx.root;
98
+ let segments;
99
+ try {
100
+ segments = ref === "#" ? [] : decodeURIComponent(ref.slice(2)).split("/").map((s) => s.replace(/~1/g, "/").replace(/~0/g, "~"));
101
+ }
102
+ catch {
103
+ return "unknown";
104
+ }
105
+ for (const key of segments) {
106
+ if (!target || typeof target !== "object" || !Object.hasOwn(target, key))
107
+ return "unknown";
108
+ target = target[key];
109
+ }
110
+ if (typeof target === "boolean")
111
+ return render(target, ctx);
112
+ if (!target || typeof target !== "object")
113
+ return "unknown";
114
+ // Reference-only cycles have no structural guard and cannot form valid TS aliases.
115
+ if (typeof target.$ref === "string") {
116
+ if (ctx.seenRefs.has(ref))
117
+ return "unknown";
118
+ ctx.seenRefs.add(ref);
119
+ try {
120
+ return render(target, ctx);
121
+ }
122
+ finally {
123
+ ctx.seenRefs.delete(ref);
124
+ }
125
+ }
126
+ const existing = ctx.refNames.get(ref);
127
+ if (existing)
128
+ return ctx.activeRefs.has(ref) && ctx.guardDepth <= ctx.activeRefs.get(ref) ? "unknown" : existing;
129
+ const name = allocateName(`${ctx.aliasPrefix}${pascalCase(segments.at(-1) ?? "Root")}`, ctx.usedNames);
130
+ ctx.refNames.set(ref, name);
131
+ ctx.aliases.set(name, "");
132
+ ctx.activeRefs.set(ref, ctx.guardDepth);
133
+ try {
134
+ ctx.aliases.set(name, render(target, { ...ctx, depth: 0 }));
135
+ }
136
+ finally {
137
+ ctx.activeRefs.delete(ref);
138
+ }
139
+ return name;
140
+ }
141
+ function renderArray(schema, ctx) {
142
+ ctx = { ...ctx, guardDepth: ctx.guardDepth + 1 };
143
+ if (Array.isArray(schema.prefixItems)) {
144
+ if (schema.prefixItems.length > ctx.budget.remaining)
145
+ return "unknown[]";
146
+ const min = typeof schema.minItems === "number" ? schema.minItems : 0;
147
+ const max = typeof schema.maxItems === "number" ? schema.maxItems : Infinity;
148
+ const members = schema.prefixItems.slice(0, max).map((item, i) => `${wrap(render(item, ctx))}${i >= min ? "?" : ""}`);
149
+ if (schema.items !== false && max > schema.prefixItems.length)
150
+ members.push(`...Array<${render(schema.items, ctx)}>`);
151
+ return `[${members.join(", ")}]`;
152
+ }
153
+ const items = schema.items;
154
+ const inner = render(items, ctx);
155
+ const array = hasTopLevelOperator(inner) ? `Array<${inner}>` : `${inner}[]`;
156
+ if (!ctx.suppressSampleHints && schema["x-sampled"] === true && schema["x-observed-items"] && typeof schema["x-observed-items"] === "object") {
157
+ const observed = annotationType(schema["x-observed-items"], { ...ctx, suppressSampleHints: true });
158
+ return `${array} /* ${commentText(`sampled item shape: ${observed}`)} */`;
159
+ }
160
+ return array;
161
+ }
162
+ function renderObject(schema, ctx) {
163
+ const props = (schema.properties ?? {});
164
+ const required = new Set((schema.required ?? []));
165
+ const keys = Object.keys(props);
166
+ if (keys.length > (ctx.compact ? 500 : 10000))
167
+ return "Record<string, unknown>";
168
+ if (keys.some((key) => key.length > 1000))
169
+ return "Record<string, unknown>";
170
+ const extra = schema.additionalProperties;
171
+ const mapHint = typeof schema["x-hint"] === "string" && ctx.compact ? ` /* ${commentText(schema["x-hint"])} */` : "";
172
+ if (keys.length === 0) {
173
+ if (extra === false)
174
+ return "Record<string, never>";
175
+ if (extra && typeof extra === "object") {
176
+ const value = render(extra, { ...ctx, guardDepth: ctx.guardDepth + 1 });
177
+ return ctx.activeRefs.size ? `{ [key: string]: ${value} }${mapHint}` : `Record<string, ${value}>${mapHint}`;
178
+ }
179
+ return "Record<string, unknown>";
180
+ }
181
+ const child = { ...ctx, depth: ctx.depth + 1, guardDepth: ctx.guardDepth + 1 };
182
+ const members = keys.map((key) => {
183
+ const prop = props[key];
184
+ const name = isIdentifier(key) ? key : JSON.stringify(key);
185
+ const optional = required.has(key) ? "" : "?";
186
+ const type = render(prop, child);
187
+ return { name, optional, type, doc: ctx.compact || !prop || typeof prop !== "object" ? "" : docComment(prop, ctx) };
188
+ });
189
+ if (extra && typeof extra === "object")
190
+ members.push({ name: "[key: string]", optional: "", type: joinUnion([render(extra, child), ...members.map((m) => m.type), ...(members.some((m) => m.optional) ? ["undefined"] : [])]), doc: "" });
191
+ if (ctx.compact) {
192
+ // Descriptions must stay short: summarize wide objects instead of listing every field.
193
+ if (members.length > COMPACT_MAX_FIELDS) {
194
+ const types = [...new Set(members.map((m) => m.type))];
195
+ if (types.length === 1 && !types[0].startsWith("{"))
196
+ return `Record<string, ${types[0]}> /* ${members.length} fields */`;
197
+ const shown = members.slice(0, COMPACT_MAX_FIELDS).map((m) => `${m.name}${m.optional}: ${m.type}`);
198
+ return `{ ${shown.join("; ")}; /* +${members.length - COMPACT_MAX_FIELDS} more fields */ }`;
199
+ }
200
+ return `{ ${members.map((m) => `${m.name}${m.optional}: ${m.type}`).join("; ")} }`;
201
+ }
202
+ const pad = " ".repeat(ctx.depth + 1);
203
+ const lines = members.map((m) => `${m.doc ? indentDoc(m.doc, pad) : ""}${pad}${m.name}${m.optional}: ${m.type};`);
204
+ return `{\n${lines.join("\n")}\n${" ".repeat(ctx.depth)}}`;
205
+ }
206
+ function stringHint(schema, ctx) {
207
+ const json = jsonContentType(schema, ctx);
208
+ if (json)
209
+ return `JSON string, parse to: ${json}`;
210
+ const observed = Array.isArray(schema["x-observed-values"]) ? schema["x-observed-values"].slice(0, 12) : undefined;
211
+ if (observed)
212
+ return observed.map((v) => boundedLiteral(v) ?? "[large value omitted]").join("|");
213
+ if (typeof schema.format === "string")
214
+ return schema.format;
215
+ return undefined;
216
+ }
217
+ /** For strings holding JSON: the parsed type, rendered compactly and safe to put inside a comment. */
218
+ function jsonContentType(schema, ctx) {
219
+ if (schema.contentMediaType !== "application/json" || !schema.contentSchema)
220
+ return undefined;
221
+ return annotationType(schema.contentSchema, ctx);
222
+ }
223
+ /** Render informational schemas in an isolated alias scope, sharing resource limits. */
224
+ function annotationType(schema, ctx) {
225
+ // Rendered against the same root so `$ref`s into the root's `$defs` resolve.
226
+ const inner = { ...ctx, compact: true, depth: 0, seenRefs: new Set(), aliases: new Map(), aliasPrefix: "", refNames: new Map(), usedNames: new Set(), activeRefs: new Map() };
227
+ const type = render(schema, inner);
228
+ const where = [...inner.aliases].map(([n, b]) => `${n} = ${b}`).join("; ");
229
+ return (where ? `${type} where ${where}` : type).replace(/\/\*\s*/g, "(").replace(/\s*\*\//g, ")");
230
+ }
231
+ /** Bound traversal before serializing untrusted enum/const/example JSON values. */
232
+ function boundedLiteral(value) {
233
+ let nodes = 512;
234
+ let characters = 4000;
235
+ const visit = (v, depth) => {
236
+ if (--nodes < 0 || depth > 32)
237
+ return undefined;
238
+ let result;
239
+ if (v === null || typeof v === "boolean" || (typeof v === "number" && Number.isFinite(v)))
240
+ result = JSON.stringify(v);
241
+ else if (typeof v === "string") {
242
+ if (v.length > characters)
243
+ return undefined;
244
+ result = JSON.stringify(v);
245
+ }
246
+ else if (Array.isArray(v)) {
247
+ if (v.length > nodes)
248
+ return undefined;
249
+ const parts = [];
250
+ for (const item of v) {
251
+ const part = visit(item, depth + 1);
252
+ if (part === undefined)
253
+ return undefined;
254
+ parts.push(part);
255
+ }
256
+ result = `[${parts.join(",")}]`;
257
+ }
258
+ else if (v && typeof v === "object") {
259
+ const parts = [];
260
+ for (const key in v) {
261
+ if (!Object.hasOwn(v, key))
262
+ continue;
263
+ if (key.length > characters)
264
+ return undefined;
265
+ const encodedKey = visit(key, depth + 1);
266
+ const part = visit(v[key], depth + 1);
267
+ if (encodedKey === undefined || part === undefined)
268
+ return undefined;
269
+ parts.push(`${encodedKey}:${part}`);
270
+ }
271
+ result = `{${parts.join(",")}}`;
272
+ }
273
+ if (result === undefined || result.length > characters)
274
+ return undefined;
275
+ characters -= result.length;
276
+ return result;
277
+ };
278
+ return visit(value, 0);
279
+ }
280
+ function numberHint(schema) {
281
+ if (schema["x-hint"] === "unix-seconds")
282
+ return "unix seconds";
283
+ if (schema["x-hint"] === "unix-millis")
284
+ return "unix millis";
285
+ return undefined;
286
+ }
287
+ /** Compact mode puts hints inline because there is no room for JSDoc. */
288
+ function withHint(type, hint, ctx) {
289
+ return ctx.compact && hint ? `${type} /* ${commentText(hint)} */` : type;
290
+ }
291
+ function docComment(schema, ctx, depth = 0) {
292
+ if (!schema || typeof schema !== "object" || depth >= 16 || --ctx.budget.remaining < 0)
293
+ return "";
294
+ const parts = [];
295
+ if (typeof schema.description === "string")
296
+ parts.push(schema.description.slice(0, MAX_COMMENT_LENGTH));
297
+ const observed = Array.isArray(schema["x-observed-values"]) ? schema["x-observed-values"].slice(0, 12) : undefined;
298
+ if (observed)
299
+ parts.push(`Observed values: ${observed.map((v) => boundedLiteral(v) ?? "[large value omitted]").join(", ")} (may not be exhaustive).`);
300
+ const json = jsonContentType(schema, ctx);
301
+ if (json)
302
+ parts.push(`Holds JSON; JSON.parse() it to get: ${json}`);
303
+ if (typeof schema.format === "string")
304
+ parts.push(`Format: ${schema.format}.`);
305
+ const hint = numberHint(schema);
306
+ if (hint)
307
+ parts.push(`Looks like a timestamp in ${hint}.`);
308
+ else if (typeof schema["x-hint"] === "string")
309
+ parts.push(`${capitalize(schema["x-hint"])}.`);
310
+ if (typeof schema["x-presence"] === "number")
311
+ parts.push(`Present in ${Math.round(schema["x-presence"] * 100)}% of observed objects.`);
312
+ if (schema["x-redacted"])
313
+ parts.push("Examples suppressed (key looks sensitive).");
314
+ const examples = Array.isArray(schema.examples) ? schema.examples : undefined;
315
+ if (examples?.length)
316
+ parts.push(`Example: ${examples.slice(0, 2).map((e) => boundedLiteral(e) ?? "[large value omitted]").join(", ")}`);
317
+ if (Array.isArray(schema.anyOf)) {
318
+ for (const v of schema.anyOf) {
319
+ const inner = docComment(v, ctx, depth + 1);
320
+ if (inner)
321
+ parts.push(inner);
322
+ }
323
+ }
324
+ return commentText(parts.join(" "));
325
+ }
326
+ function capitalize(text) {
327
+ return text.charAt(0).toUpperCase() + text.slice(1);
328
+ }
329
+ function indentDoc(doc, pad) {
330
+ return `${pad}/** ${commentText(doc)} */\n`;
331
+ }
332
+ function joinUnion(parts) {
333
+ return [...new Set(parts)].join(" | ") || "never";
334
+ }
335
+ function wrap(type) {
336
+ return hasTopLevelOperator(type) ? `(${type})` : type;
337
+ }
338
+ /** True when `type` contains `|` or `&` outside any brackets, strings or comments. */
339
+ export function hasTopLevelOperator(type) {
340
+ let depth = 0;
341
+ for (let i = 0; i < type.length; i++) {
342
+ const c = type[i];
343
+ if (c === "/" && type[i + 1] === "*") {
344
+ const end = type.indexOf("*/", i + 2);
345
+ i = end < 0 ? type.length : end + 1;
346
+ }
347
+ else if (c === '"') {
348
+ i++;
349
+ while (i < type.length && type[i] !== '"')
350
+ i += type[i] === "\\" ? 2 : 1;
351
+ }
352
+ else if (c === "{" || c === "(" || c === "<" || c === "[")
353
+ depth++;
354
+ else if (c === "}" || c === ")" || c === ">" || c === "]")
355
+ depth--;
356
+ else if (depth === 0 && (c === "|" || c === "&"))
357
+ return true;
358
+ }
359
+ return false;
360
+ }
361
+ function isIdentifier(key) {
362
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key);
363
+ }
364
+ export function pascalCase(name) {
365
+ const cleaned = name.replace(/[^A-Za-z0-9]+/g, " ").trim();
366
+ const result = cleaned.replace(/(?:^|\s)(\w)/g, (_, c) => c.toUpperCase()).replace(/\s+/g, "");
367
+ return /^\d/.test(result) ? `T${result}` : result || "Tool";
368
+ }
369
+ // ---------------------------------------------------------------------------------------------
370
+ // Module and description rendering
371
+ /** One line describing what a tool returns, for appending to its description. */
372
+ export function describeOutput(tool, options = {}) {
373
+ const out = toolOutput(tool);
374
+ if (!out)
375
+ return undefined;
376
+ const type = outputTs(out, true);
377
+ const source = out.source === "declared" ? "declared by server" : `learned from ${out.samples} response${out.samples === 1 ? "" : "s"}`;
378
+ const encoding = out.encoding === "json-text" ? "JSON in the text content" : out.encoding === "structured" ? "structuredContent" : "plain text";
379
+ const limit = Math.max(0, Math.min(MAX_OUTPUT_DESCRIPTION_LENGTH, Math.floor(options.maxLength ?? MAX_OUTPUT_DESCRIPTION_LENGTH) || 0));
380
+ const summary = `Returns ${encoding} (${source}): ${type}`.replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]/g, " ");
381
+ if (summary.length <= limit)
382
+ return summary;
383
+ const fallback = `Returns ${encoding} (${source}): unknown (schema summary omitted).`;
384
+ return fallback.length <= limit ? fallback : fallback.slice(0, limit);
385
+ }
386
+ function outputTs(out, compact) {
387
+ if (!out.schema)
388
+ return withText("string", out);
389
+ const { type, aliases } = schemaToTsParts(out.schema, { compact });
390
+ const result = withText(type, out);
391
+ if (!aliases.length)
392
+ return result;
393
+ return compact ? `${result} where ${aliases.map(([n, b]) => `${n} = ${b}`).join("; ")}` : `${result}\n${aliases.map(([n, b]) => `type ${n} = ${b};`).join("\n")}`;
394
+ }
395
+ function withText(type, out) {
396
+ const variants = [type, ...(out.alsoText ? ["string"] : []), ...(out.alsoEmpty ? ["null"] : [])];
397
+ return [...new Set(variants)].join(" | ");
398
+ }
399
+ /** `export type` lines for a schema plus the named recursive types it uses. */
400
+ function typeDeclarations(name, schema, fallback, prefix, out, usedNames) {
401
+ if (!schema)
402
+ return [`export type ${name} = ${out ? withText(fallback, out) : fallback};`];
403
+ const { type, aliases } = schemaToTsParts(schema, { compact: false, aliasPrefix: prefix, usedNames });
404
+ return [...aliases.map(([n, body]) => `export type ${n} = ${body};`), `export type ${name} = ${out ? withText(type, out) : type};`];
405
+ }
406
+ export const DEFAULT_HEADER = [
407
+ "// Output types are learned from real responses. A tool's result is its structuredContent,",
408
+ "// or its text content parsed as JSON, or the raw text when it isn't JSON.",
409
+ ];
410
+ export function emitModule(server, options = {}) {
411
+ return renderModule(server, options);
412
+ }
413
+ /** Emits a real .ts module containing types and a callable create<Interface> factory. */
414
+ export function emitBindings(server, options = {}) {
415
+ return renderModule(server, { ...options, outputs: "learned" }, options.runtimeImport ?? "toolsplice");
416
+ }
417
+ function renderModule(server, options, runtimeImport) {
418
+ const requestedIface = options.interfaceName ?? `${pascalCase(server.name)}Tools`;
419
+ const iface = isIdentifier(requestedIface) && !RESERVED_NAMES.has(requestedIface) && !RESERVED_BINDINGS.has(requestedIface) ? requestedIface : `${pascalCase(requestedIface)}Tools`;
420
+ const usedNames = new Set([iface]);
421
+ const runtime = runtimeImport === undefined ? undefined : allocateName("__toolsplice", usedNames);
422
+ const factory = runtime ? allocateName(`create${iface}`, usedNames) : undefined;
423
+ const tools = Object.values(server.tools).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
424
+ const names = tools.map((tool) => {
425
+ const base = pascalCase(tool.name);
426
+ return { input: allocateName(`${base}Input`, usedNames), output: allocateName(`${base}Output`, usedNames), base };
427
+ });
428
+ const learnedOutputs = (options.outputs ?? "learned") === "learned";
429
+ const out = [
430
+ `// Generated by toolsplice from "${commentText(server.name)}"${server.version ? ` v${commentText(server.version)}` : ""}.`,
431
+ ...(options.header ?? DEFAULT_HEADER),
432
+ "",
433
+ ...(runtime ? [`import * as ${runtime} from ${JSON.stringify(runtimeImport)};`, "// Observed return types are not runtime guarantees. Monitor drift before relying on them.", ""] : []),
434
+ ];
435
+ const methods = [];
436
+ const implementations = [];
437
+ for (const [index, tool] of tools.entries()) {
438
+ const { input, output: outputName, base } = names[index];
439
+ const output = learnedOutputs ? toolOutput(tool) : undefined;
440
+ out.push(...typeDeclarations(input, tool.inputSchema, "Record<string, unknown>", input, undefined, usedNames), "");
441
+ if (learnedOutputs)
442
+ out.push(`/** ${commentText(outputDoc(tool, output))} */`);
443
+ const outputFallback = output && !output.schema ? "string" : "unknown";
444
+ out.push(...typeDeclarations(outputName, output?.schema, outputFallback, base, output, usedNames), "");
445
+ const summary = options.outputs === "description" ? describeOutput(tool) : undefined;
446
+ const doc = [tool.description?.trim().slice(0, MAX_COMMENT_LENGTH), summary, annotationsDoc(tool)].filter(Boolean).join("\n");
447
+ const docBlock = doc ? ` /**\n${doc.split("\n").map((l) => ` * ${commentText(l)}`).join("\n")}\n */\n` : "";
448
+ const method = isIdentifier(tool.name) ? tool.name : JSON.stringify(tool.name);
449
+ methods.push(`${docBlock} ${method}(args: ${input}${runtime ? `, options?: ${runtime}.BindingCallOptions` : ""}): Promise<${outputName}>;`);
450
+ if (runtime)
451
+ implementations.push(` [${JSON.stringify(tool.name)}]: (args: ${input}, options?: ${runtime}.BindingCallOptions) => ${runtime}.invokeTool<${outputName}>(caller, ${JSON.stringify(tool.name)}, args, options),`);
452
+ }
453
+ out.push(`export interface ${iface} {`, methods.join("\n"), "}", "");
454
+ if (runtime)
455
+ out.push(`export function ${factory}(caller: ${runtime}.ToolCaller): ${iface} {`, " return {", ...implementations, " };", "}", "");
456
+ return out.join("\n");
457
+ }
458
+ function outputDoc(tool, out) {
459
+ if (!out)
460
+ return tool.calls ? `Not learned yet: ${tool.calls} call(s), none returned JSON.` : "Not learned yet: no calls recorded.";
461
+ const parts = [out.source === "declared" ? "Declared by the server." : `Learned from ${out.samples} response(s).`];
462
+ if (out.alsoText)
463
+ parts.push(out.textSample === undefined ? "Sometimes returns plain text instead." : "Sometimes returns plain text instead, e.g. " + (boundedLiteral(out.textSample) ?? "[large value omitted]") + ".");
464
+ if (out.prefix)
465
+ parts.push(`JSON follows a text prefix like ${(boundedLiteral(out.prefix) ?? "[large value omitted]")}.`);
466
+ if (out.warning)
467
+ parts.push(out.warning);
468
+ return parts.join(" ");
469
+ }
470
+ function annotationsDoc(tool) {
471
+ const a = tool.annotations;
472
+ if (!a)
473
+ return "";
474
+ if (a.readOnlyHint)
475
+ return "Read-only.";
476
+ if (a.destructiveHint)
477
+ return "Destructive: changes or deletes data.";
478
+ return "";
479
+ }
@@ -0,0 +1,22 @@
1
+ import { type ContractSnapshot } from "./contracts.js";
2
+ import { type ToolCaller } from "./execution.js";
3
+ export interface ContractIssue {
4
+ path: string;
5
+ keyword: string;
6
+ }
7
+ export declare class ContractValidationError extends Error {
8
+ readonly tool: string;
9
+ readonly stage: "input" | "output" | "contract";
10
+ readonly issues: ContractIssue[];
11
+ constructor(tool: string, stage: "input" | "output" | "contract", issues: ContractIssue[]);
12
+ }
13
+ export interface ContractCallerOptions {
14
+ /** Both default true. Disabling one stage is explicit; unknown tools always fail before dispatch. */
15
+ inputs?: boolean;
16
+ outputs?: boolean;
17
+ }
18
+ /** Compile once, then enforce a detached snapshot before inputs and after decoded outputs.
19
+ * Raw successful results are returned unchanged for generated bindings or SDK consumers.
20
+ * MCP error and unfinished results pass through for normal SDK/binding error handling.
21
+ * Reviewed schemas are trusted configuration, not an arbitrary-schema execution sandbox. */
22
+ export declare function createContractCaller(caller: ToolCaller, source: ContractSnapshot, options?: ContractCallerOptions): ToolCaller;