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.
Files changed (172) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +104 -2
  3. package/dist/abortable.d.ts +6 -0
  4. package/dist/abortable.js +50 -0
  5. package/dist/adaptive-read.d.ts +50 -0
  6. package/dist/adaptive-read.js +780 -0
  7. package/dist/answer-wait.d.ts +7 -0
  8. package/dist/answer-wait.js +45 -0
  9. package/dist/cache-reads.d.ts +18 -0
  10. package/dist/cache-reads.js +89 -0
  11. package/dist/calibration-ledger.d.ts +37 -0
  12. package/dist/calibration-ledger.js +148 -0
  13. package/dist/calibration-marker.d.ts +4 -0
  14. package/dist/calibration-marker.js +77 -0
  15. package/dist/catalog-setup.d.ts +33 -0
  16. package/dist/catalog-setup.js +89 -0
  17. package/dist/catalog.d.ts +10 -0
  18. package/dist/catalog.js +42 -0
  19. package/dist/checkpoint-files.d.ts +15 -0
  20. package/dist/checkpoint-files.js +99 -0
  21. package/dist/cli.d.ts +2 -0
  22. package/dist/cli.js +1454 -0
  23. package/dist/coalesce-reads.d.ts +6 -0
  24. package/dist/coalesce-reads.js +33 -0
  25. package/dist/codegen.d.ts +44 -0
  26. package/dist/codegen.js +479 -0
  27. package/dist/contract-caller.d.ts +23 -0
  28. package/dist/contract-caller.js +326 -0
  29. package/dist/contract-corrections.d.ts +35 -0
  30. package/dist/contract-corrections.js +159 -0
  31. package/dist/contract-schema.d.ts +7 -0
  32. package/dist/contract-schema.js +156 -0
  33. package/dist/contracts.d.ts +72 -0
  34. package/dist/contracts.js +370 -0
  35. package/dist/core.d.ts +44 -0
  36. package/dist/core.js +43 -0
  37. package/dist/db-final-answer.d.ts +9 -0
  38. package/dist/db-final-answer.js +62 -0
  39. package/dist/define.d.ts +78 -0
  40. package/dist/define.js +14 -0
  41. package/dist/doctor.d.ts +22 -0
  42. package/dist/doctor.js +91 -0
  43. package/dist/drift.d.ts +23 -0
  44. package/dist/drift.js +111 -0
  45. package/dist/execution.d.ts +38 -0
  46. package/dist/execution.js +66 -0
  47. package/dist/extract.d.ts +34 -0
  48. package/dist/extract.js +73 -0
  49. package/dist/final-answer-stores.d.ts +71 -0
  50. package/dist/final-answer-stores.js +72 -0
  51. package/dist/final-answer.d.ts +32 -0
  52. package/dist/final-answer.js +104 -0
  53. package/dist/impact.d.ts +48 -0
  54. package/dist/impact.js +71 -0
  55. package/dist/index.d.ts +51 -0
  56. package/dist/index.js +47 -0
  57. package/dist/local-tool.d.ts +18 -0
  58. package/dist/local-tool.js +32 -0
  59. package/dist/mcp-apps.d.ts +53 -0
  60. package/dist/mcp-apps.js +32 -0
  61. package/dist/mcp-event-delivery.d.ts +98 -0
  62. package/dist/mcp-event-delivery.js +211 -0
  63. package/dist/mcp-extensions.d.ts +46 -0
  64. package/dist/mcp-extensions.js +200 -0
  65. package/dist/mcp-peer.d.ts +45 -0
  66. package/dist/mcp-peer.js +207 -0
  67. package/dist/mcp-server-card.d.ts +21 -0
  68. package/dist/mcp-server-card.js +54 -0
  69. package/dist/ordered-transport.d.ts +12 -0
  70. package/dist/ordered-transport.js +106 -0
  71. package/dist/page-checkpoint.d.ts +71 -0
  72. package/dist/page-checkpoint.js +286 -0
  73. package/dist/page-read-gate.d.ts +15 -0
  74. package/dist/page-read-gate.js +48 -0
  75. package/dist/pattern.d.ts +3 -0
  76. package/dist/pattern.js +54 -0
  77. package/dist/postgres.d.ts +41 -0
  78. package/dist/postgres.js +264 -0
  79. package/dist/probe.d.ts +29 -0
  80. package/dist/probe.js +121 -0
  81. package/dist/proxy.d.ts +40 -0
  82. package/dist/proxy.js +436 -0
  83. package/dist/read-pages.d.ts +25 -0
  84. package/dist/read-pages.js +85 -0
  85. package/dist/read-policy.d.ts +6 -0
  86. package/dist/read-policy.js +16 -0
  87. package/dist/read-steps.d.ts +12 -0
  88. package/dist/read-steps.js +36 -0
  89. package/dist/result-session.d.ts +109 -0
  90. package/dist/result-session.js +620 -0
  91. package/dist/route-checkpoint.d.ts +3 -0
  92. package/dist/route-checkpoint.js +80 -0
  93. package/dist/route-driver-cli.d.ts +3 -0
  94. package/dist/route-driver-cli.js +43 -0
  95. package/dist/route-evaluation.d.ts +141 -0
  96. package/dist/route-evaluation.js +329 -0
  97. package/dist/row-groups.d.ts +17 -0
  98. package/dist/row-groups.js +79 -0
  99. package/dist/row-query.d.ts +62 -0
  100. package/dist/row-query.js +172 -0
  101. package/dist/rules.d.ts +30 -0
  102. package/dist/rules.js +72 -0
  103. package/dist/run-diagnostics.d.ts +75 -0
  104. package/dist/run-diagnostics.js +212 -0
  105. package/dist/runtime.d.ts +6 -0
  106. package/dist/runtime.js +26 -0
  107. package/dist/schema.d.ts +17 -0
  108. package/dist/schema.js +299 -0
  109. package/dist/search-fetch.d.ts +50 -0
  110. package/dist/search-fetch.js +264 -0
  111. package/dist/shape.d.ts +91 -0
  112. package/dist/shape.js +499 -0
  113. package/dist/skill-files.d.ts +9 -0
  114. package/dist/skill-files.js +49 -0
  115. package/dist/splice-diagnostics.d.ts +44 -0
  116. package/dist/splice-diagnostics.js +88 -0
  117. package/dist/splice-measure.d.ts +33 -0
  118. package/dist/splice-measure.js +55 -0
  119. package/dist/splice-project.d.ts +125 -0
  120. package/dist/splice-project.js +348 -0
  121. package/dist/splice-recording.d.ts +132 -0
  122. package/dist/splice-recording.js +481 -0
  123. package/dist/splice.d.ts +181 -0
  124. package/dist/splice.js +1263 -0
  125. package/dist/sqlite-checkpoint-store.d.ts +5 -0
  126. package/dist/sqlite-checkpoint-store.js +91 -0
  127. package/dist/sqlite-checkpoint-worker.d.ts +1 -0
  128. package/dist/sqlite-checkpoint-worker.js +115 -0
  129. package/dist/storage.d.ts +17 -0
  130. package/dist/storage.js +1 -0
  131. package/dist/store.d.ts +151 -0
  132. package/dist/store.js +735 -0
  133. package/dist/test-difference.d.ts +13 -0
  134. package/dist/test-difference.js +42 -0
  135. package/dist/testing.d.ts +122 -0
  136. package/dist/testing.js +261 -0
  137. package/dist/text-pages.d.ts +24 -0
  138. package/dist/text-pages.js +36 -0
  139. package/dist/tool-discovery.d.ts +59 -0
  140. package/dist/tool-discovery.js +136 -0
  141. package/dist/unevaluated.d.ts +7 -0
  142. package/dist/unevaluated.js +156 -0
  143. package/dist/v2.d.ts +49 -0
  144. package/dist/v2.js +413 -0
  145. package/dist/validate-output.d.ts +3 -0
  146. package/dist/validate-output.js +73 -0
  147. package/dist/version.d.ts +1 -0
  148. package/dist/version.js +1 -0
  149. package/dist/workflow-json.d.ts +8 -0
  150. package/dist/workflow-json.js +74 -0
  151. package/docs/AGENT-FRAMEWORKS.md +431 -0
  152. package/docs/BENCHMARKS.md +43 -0
  153. package/docs/INTEGRATION-QUICKSTART.md +859 -0
  154. package/docs/LEARNING-AND-STORAGE.md +393 -0
  155. package/docs/MCP.md +204 -0
  156. package/docs/PROJECTS-AND-UPGRADES.md +173 -0
  157. package/docs/PYTHON-REFERENCE.md +348 -0
  158. package/docs/PYTHON.md +120 -0
  159. package/docs/RECORDING-AND-CORRECTIONS.md +205 -0
  160. package/docs/TESTING.md +259 -0
  161. package/examples/mcp-app/build.mjs +11 -0
  162. package/examples/mcp-app/view.mjs +22 -0
  163. package/examples/quickstart.mjs +43 -0
  164. package/examples/route-driver.mjs +67 -0
  165. package/integrations/ai.d.mts +36 -0
  166. package/integrations/ai.mjs +178 -0
  167. package/integrations/call-options.mjs +9 -0
  168. package/integrations/langchain.d.mts +31 -0
  169. package/integrations/langchain.mjs +114 -0
  170. package/integrations/managed.mjs +154 -0
  171. package/integrations/types.d.mts +13 -0
  172. package/package.json +139 -4
@@ -0,0 +1,78 @@
1
+ import { type SpliceSpec } from "./splice.js";
2
+ /** Inline definitions for applications that already know their tools' schemas. */
3
+ export type SpliceDefinition = Omit<SpliceSpec, "format" | "formatVersion" | "source" | "target"> & {
4
+ source: SpliceSpec["source"] & {
5
+ inputSchema: Record<string, unknown>;
6
+ outputSchema?: Record<string, unknown>;
7
+ };
8
+ target: SpliceSpec["target"] & {
9
+ inputSchema: Record<string, unknown>;
10
+ outputSchema?: Record<string, unknown>;
11
+ };
12
+ };
13
+ export declare function defineSplice(definition: SpliceDefinition): {
14
+ report: import("./splice.js").SpliceReport;
15
+ mapOutput: (output: unknown, options?: import("./splice.js").SpliceMappingOptions) => Promise<Record<string, unknown>[]>;
16
+ run: (source: import("./execution.js").ToolCaller, target: import("./execution.js").ToolCaller, args: unknown, options?: import("./splice.js").SpliceRunOptions) => Promise<unknown[]>;
17
+ runReads: (source: import("./execution.js").ToolCaller, target: import("./execution.js").ToolCaller, args: unknown, options?: import("./splice.js").SpliceReadOptions) => Promise<unknown[]>;
18
+ asTool: ({ name, description, source, target, ui, readConcurrency: requested, assumeReadOnly }: import("./splice.js").SpliceToolOptions) => {
19
+ definition: {
20
+ name: string;
21
+ description?: string | undefined;
22
+ _meta?: {
23
+ ui: import("./mcp-apps.js").McpToolUi;
24
+ } | undefined;
25
+ inputSchema: {
26
+ type: "object";
27
+ };
28
+ outputSchema: {
29
+ type: "object";
30
+ properties: {
31
+ results: {
32
+ type: string;
33
+ items: {
34
+ type: string;
35
+ properties: {
36
+ [k: string]: {};
37
+ };
38
+ required: string[];
39
+ additionalProperties: boolean;
40
+ } | {
41
+ type?: undefined;
42
+ properties?: undefined;
43
+ required?: undefined;
44
+ additionalProperties?: undefined;
45
+ };
46
+ };
47
+ };
48
+ required: string[];
49
+ additionalProperties: boolean;
50
+ };
51
+ };
52
+ call: (args: Record<string, unknown>, options?: import("./splice.js").SpliceRunOptions) => Promise<{
53
+ resultType: "complete";
54
+ structuredContent: {
55
+ results: unknown[];
56
+ };
57
+ content: {
58
+ type: "text";
59
+ text: string;
60
+ }[];
61
+ isError?: undefined;
62
+ } | {
63
+ structuredContent?: undefined;
64
+ resultType: "complete";
65
+ isError: true;
66
+ content: {
67
+ type: "text";
68
+ text: string;
69
+ }[];
70
+ }>;
71
+ execute: (args: Record<string, unknown>, options?: import("./splice.js").SpliceRunOptions) => Promise<{
72
+ results: unknown[];
73
+ }>;
74
+ };
75
+ plan: SpliceSpec;
76
+ sourceContract: import("./contracts.js").ContractSnapshot;
77
+ targetContract: import("./contracts.js").ContractSnapshot;
78
+ };
package/dist/define.js ADDED
@@ -0,0 +1,14 @@
1
+ import { createContractFromCatalog } from "./contracts.js";
2
+ import { parseSpliceSpec, prepareSplice } from "./splice.js";
3
+ import { copyJson, jsonObject } from "./workflow-json.js";
4
+ export function defineSplice(definition) {
5
+ const config = copyJson(definition);
6
+ const { inputSchema: si, outputSchema: so, ...source } = config.source;
7
+ const { inputSchema: ti, outputSchema: to, ...target } = config.target;
8
+ if (!jsonObject(si) || !jsonObject(ti) || (so !== undefined && !jsonObject(so)) || (to !== undefined && !jsonObject(to)))
9
+ throw new Error("Inline tool schemas must be JSON Schema objects.");
10
+ const plan = parseSpliceSpec({ format: "toolsplice-splice", formatVersion: 1, ...config, source, target });
11
+ const sourceContract = createContractFromCatalog({ name: source.server }, { tools: [{ name: source.tool, inputSchema: si, ...(so === undefined ? {} : { outputSchema: so }) }] });
12
+ const targetContract = createContractFromCatalog({ name: target.server }, { tools: [{ name: target.tool, inputSchema: ti, ...(to === undefined ? {} : { outputSchema: to }) }] });
13
+ return { ...prepareSplice(plan, sourceContract, targetContract), plan, sourceContract, targetContract };
14
+ }
@@ -0,0 +1,22 @@
1
+ import { type ServerRecord, type ToolRecord } from "./store.js";
2
+ export type ToolHealth = "declared" | "enriched" | "learning" | "text" | "warning";
3
+ export interface ToolDiagnostic {
4
+ name: string;
5
+ status: ToolHealth;
6
+ observations: number;
7
+ errors: number;
8
+ revision: number;
9
+ limited: boolean;
10
+ detail: string;
11
+ }
12
+ export interface DoctorReport {
13
+ server: string;
14
+ version?: string;
15
+ tools: ToolDiagnostic[];
16
+ totals: Record<ToolHealth, number>;
17
+ export: "not-exported" | "current" | "stale";
18
+ nextSteps: string[];
19
+ }
20
+ export declare function diagnoseTool(tool: ToolRecord, minSamples?: number): ToolDiagnostic;
21
+ export declare function diagnose(server: ServerRecord, minSamples?: number): DoctorReport;
22
+ export declare function formatDoctor(report: DoctorReport): string;
package/dist/doctor.js ADDED
@@ -0,0 +1,91 @@
1
+ import { exportFingerprint } from "./drift.js";
2
+ import { hasEmbeddedJson } from "./shape.js";
3
+ import { toolOutput } from "./store.js";
4
+ function usefulDeclaration(tool) {
5
+ const schema = tool.outputSchema;
6
+ if (!schema)
7
+ return false;
8
+ if (schema.$ref || schema.anyOf || schema.oneOf || schema.allOf)
9
+ return true;
10
+ if (schema.type && schema.type !== "object")
11
+ return true;
12
+ if (schema.additionalProperties && typeof schema.additionalProperties === "object")
13
+ return true;
14
+ const props = schema.properties;
15
+ if (!props || !Object.keys(props).length)
16
+ return false;
17
+ return !(Object.keys(props).length === 1 && props.content?.type === "string");
18
+ }
19
+ function hasLimits(shape) {
20
+ if (shape.object?.truncated || shape.array?.truncated)
21
+ return true;
22
+ if (shape.array && hasLimits(shape.array.items))
23
+ return true;
24
+ if (shape.string?.json && hasLimits(shape.string.json))
25
+ return true;
26
+ return shape.object ? Object.values(shape.object.props).some(hasLimits) : false;
27
+ }
28
+ export function diagnoseTool(tool, minSamples = 1) {
29
+ const observations = tool.shape.count + tool.kinds.text;
30
+ const result = { name: tool.name, status: "learning", observations, errors: tool.kinds.error, revision: tool.drift?.revision ?? 0, limited: hasLimits(tool.shape), detail: "No successful observations yet; use this tool normally to learn its return type." };
31
+ const out = toolOutput(tool);
32
+ if (tool.schemaValidation?.latest === "mismatch") {
33
+ return { ...result, status: "warning", detail: `Observed output does not match the upstream structural schema at ${tool.schemaValidation.paths.join(", ")}. Results are still forwarded unchanged.` };
34
+ }
35
+ if (tool.schemaValidation?.latest === "unverified") {
36
+ return { ...result, status: "warning", detail: "The declared schema could not be structurally checked within diagnostic limits (for example, an unsupported reference). This is not evidence of an invalid tool result." };
37
+ }
38
+ if (out?.warning && !hasEmbeddedJson(tool.shape)) {
39
+ return { ...result, status: "warning", detail: out.warning };
40
+ }
41
+ if (usefulDeclaration(tool)) {
42
+ return { ...result, status: "declared", detail: observations ? "Upstream provides an output schema; observed outputs are recorded." : "Upstream declares an output schema; delivery has not been observed yet." };
43
+ }
44
+ if (observations < minSamples) {
45
+ if (observations)
46
+ result.detail = `${observations}/${minSamples} observations; use this tool more to enable enrichment.`;
47
+ return result;
48
+ }
49
+ const wrapper = tool.outputSchema?.properties;
50
+ if ((tool.shape.count === 0 && tool.kinds.text > 0) || (wrapper?.content?.type === "string" && !hasEmbeddedJson(tool.shape))) {
51
+ return { ...result, status: "text", detail: "Returns text with no inferred inner structure; values are passed through unchanged." };
52
+ }
53
+ return { ...result, status: "enriched", detail: hasEmbeddedJson(tool.shape) ? "Learned JSON hidden inside a string; parsing instructions can be added to the description." : "Learned return type is ready for description enrichment and TypeScript export." };
54
+ }
55
+ export function diagnose(server, minSamples = 1) {
56
+ const tools = Object.values(server.tools).sort((a, b) => a.name.localeCompare(b.name)).map((t) => diagnoseTool(t, minSamples));
57
+ const totals = { declared: 0, enriched: 0, learning: 0, text: 0, warning: 0 };
58
+ tools.forEach((t) => totals[t.status]++);
59
+ const exportStatus = !server.exportedFingerprint ? "not-exported" : server.exportedFingerprint === exportFingerprint(server) ? "current" : "stale";
60
+ const nextSteps = [];
61
+ if (totals.learning)
62
+ nextSteps.push("Use the unobserved tools in your agent; the proxy learns without making extra calls.");
63
+ if (totals.enriched)
64
+ nextSteps.push("Keep the proxy enabled; changed descriptions are announced with tools/list_changed. Clients that cache tools may need a reconnect.");
65
+ if (tools.some((t) => t.limited))
66
+ nextSteps.push("Some outputs exceeded sampling or retained-shape limits; affected branches remain unknown rather than claiming an exhaustive type.");
67
+ if (totals.text)
68
+ nextSteps.push("Text-only tools still work; toolsplice does not invent a parser for arbitrary prose.");
69
+ if (totals.warning)
70
+ nextSteps.push("Check tools marked warning: upstream schema declarations do not match observed output encodings.");
71
+ if (exportStatus === "stale")
72
+ nextSteps.push("Output shapes or definitions changed since emit-ts. Regenerate the exported types.");
73
+ return { server: server.name, version: server.version, tools, totals, export: exportStatus, nextSteps };
74
+ }
75
+ export function formatDoctor(report) {
76
+ const { totals: t } = report;
77
+ const lines = [
78
+ `${report.server}${report.version ? ` v${report.version}` : ""}: ${report.tools.length} tools`,
79
+ ` ${t.declared} already have useful output schemas`,
80
+ ` ${t.enriched} learned return types ready`,
81
+ ` ${t.learning} need observations`,
82
+ ` ${t.text} return text without inferred structure`,
83
+ ` ${t.warning} have schema/encoding warnings`,
84
+ ` TypeScript export: ${report.export}`,
85
+ "",
86
+ ...report.tools.map((x) => ` ${x.name} [${x.status}; ${x.observations} observation(s)${x.errors ? `; ${x.errors} error(s)` : ""}${x.revision ? `; revision ${x.revision}` : ""}${x.limited ? "; inference limited" : ""}]\n ${x.detail}`),
87
+ ];
88
+ if (report.nextSteps.length)
89
+ lines.push("", ...report.nextSteps.map((s) => ` → ${s}`));
90
+ return lines.join("\n") + "\n";
91
+ }
@@ -0,0 +1,23 @@
1
+ import type { Extracted } from "./extract.js";
2
+ import type { ServerRecord, ToolRecord } from "./store.js";
3
+ export interface DriftEvent {
4
+ at: string;
5
+ changes: string[];
6
+ reason: "observed-shape" | "tool-definition" | "server-version";
7
+ }
8
+ export interface DriftState {
9
+ revision: number;
10
+ events: DriftEvent[];
11
+ }
12
+ /** Strip examples, occurrence counts and other annotations. Stable across key order and traffic volume. */
13
+ export declare function contract(schema: unknown): unknown;
14
+ export declare function stableHash(value: unknown): string;
15
+ export declare function learnedContract(tool: ToolRecord): unknown;
16
+ export declare function exportFingerprint(server: ServerRecord): string;
17
+ /** Run after recordCall, using a snapshot taken before it. Only changes after the first result count. */
18
+ export declare function recordDrift(tool: ToolRecord, before: unknown, priorObservations: number, kind: Extracted["kind"]): DriftEvent | undefined;
19
+ export declare function resetLearning(tool: ToolRecord, reason: "tool-definition" | "server-version"): void;
20
+ export declare function definitionFingerprint(tool: {
21
+ inputSchema?: unknown;
22
+ outputSchema?: unknown;
23
+ }): string;
package/dist/drift.js ADDED
@@ -0,0 +1,111 @@
1
+ // Structural changes are observations, not proof of a breaking upstream change. No result values
2
+ // are retained here. This also gives exports a fingerprint that doesn't change on every call.
3
+ import { definitionContract } from "./contract-schema.js";
4
+ import { createHash } from "node:crypto";
5
+ import { emptyShape } from "./shape.js";
6
+ import { toJsonSchema } from "./schema.js";
7
+ const CONTRACT_KEYS = new Set([
8
+ "type", "properties", "required", "items", "prefixItems", "additionalProperties", "anyOf", "oneOf", "allOf",
9
+ "$ref", "$defs", "definitions", "format", "enum", "const", "contentMediaType", "contentSchema", "x-hint",
10
+ "minItems", "maxItems",
11
+ "x-observed-items", "x-sampled",
12
+ ]);
13
+ /** Strip examples, occurrence counts and other annotations. Stable across key order and traffic volume. */
14
+ export function contract(schema) {
15
+ if (schema === null || typeof schema !== "object")
16
+ return schema;
17
+ if (Array.isArray(schema))
18
+ return schema.map(contract);
19
+ const s = schema;
20
+ return Object.fromEntries(Object.keys(s).filter((k) => CONTRACT_KEYS.has(k)).sort().map((k) => {
21
+ const value = s[k];
22
+ if (k === "const" || k === "enum")
23
+ return [k, literal(value)];
24
+ if (["properties", "$defs", "definitions"].includes(k) && value && typeof value === "object") {
25
+ return [k, Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([n, v]) => [n, contract(v)]))];
26
+ }
27
+ if (k === "required" && Array.isArray(value))
28
+ return [k, [...value].sort()];
29
+ return [k, contract(value)];
30
+ }));
31
+ }
32
+ /** Literal JSON objects inside const/enum are data: do not filter their property names. */
33
+ function literal(value) {
34
+ if (Array.isArray(value))
35
+ return value.map(literal);
36
+ if (!value || typeof value !== "object")
37
+ return value;
38
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, literal(v)]));
39
+ }
40
+ export function stableHash(value) {
41
+ return createHash("sha256").update(JSON.stringify(value)).digest("hex");
42
+ }
43
+ export function learnedContract(tool) {
44
+ return {
45
+ schema: contract(toJsonSchema(tool.shape)),
46
+ encodings: ["structured", "json-text", "text", "empty"].filter((k) => tool.kinds[k] > 0),
47
+ };
48
+ }
49
+ export function exportFingerprint(server) {
50
+ return stableHash(Object.values(server.tools).sort((a, b) => a.name.localeCompare(b.name)).map((t) => ({
51
+ name: t.name, input: t.inputSchema === undefined ? undefined : definitionContract(t.inputSchema), declared: t.outputSchema === undefined ? undefined : definitionContract(t.outputSchema), learned: learnedContract(t),
52
+ })));
53
+ }
54
+ /** Run after recordCall, using a snapshot taken before it. Only changes after the first result count. */
55
+ export function recordDrift(tool, before, priorObservations, kind) {
56
+ if (kind === "error" || !priorObservations)
57
+ return undefined;
58
+ const after = learnedContract(tool);
59
+ if (stableHash(before) === stableHash(after))
60
+ return undefined;
61
+ return addEvent(tool, { at: new Date().toISOString(), changes: differences(before, after), reason: "observed-shape" });
62
+ }
63
+ function addEvent(tool, event) {
64
+ const drift = (tool.drift ??= { revision: 0, events: [] });
65
+ drift.revision++;
66
+ drift.events.push(event);
67
+ if (drift.events.length > 20)
68
+ drift.events.splice(0, drift.events.length - 20);
69
+ return event;
70
+ }
71
+ export function resetLearning(tool, reason) {
72
+ if (!tool.calls)
73
+ return;
74
+ tool.calls = 0;
75
+ tool.kinds = { structured: 0, "json-text": 0, text: 0, error: 0, empty: 0 };
76
+ tool.shape = emptyShape();
77
+ tool.textSamples = [];
78
+ tool.errorSamples = [];
79
+ tool.prefixes = [];
80
+ delete tool.schemaValidation;
81
+ addEvent(tool, { at: new Date().toISOString(), changes: ["Learned output reset; observe this version again."], reason });
82
+ }
83
+ export function definitionFingerprint(tool) {
84
+ return stableHash({ input: tool.inputSchema === undefined ? undefined : definitionContract(tool.inputSchema), output: tool.outputSchema === undefined ? undefined : definitionContract(tool.outputSchema) });
85
+ }
86
+ /** Short, value-free JSON-pointer paths; field names are data, not prose instructions. */
87
+ function differences(before, after) {
88
+ const changes = [];
89
+ const walk = (a, b, path, depth) => {
90
+ if (changes.length >= 12 || depth > 28 || JSON.stringify(a) === JSON.stringify(b))
91
+ return;
92
+ if (a && b && !Array.isArray(a) && !Array.isArray(b) && typeof a === "object" && typeof b === "object") {
93
+ const aa = a, bb = b;
94
+ for (const k of [...new Set([...Object.keys(aa), ...Object.keys(bb)])].sort()) {
95
+ const p = `${path}/${k.replace(/~/g, "~0").replace(/\//g, "~1")}`;
96
+ if (!Object.hasOwn(aa, k))
97
+ changes.push(`Added ${p}`);
98
+ else if (!Object.hasOwn(bb, k))
99
+ changes.push(`Changed ${p}`);
100
+ else
101
+ walk(aa[k], bb[k], p, depth + 1);
102
+ if (changes.length >= 12)
103
+ break;
104
+ }
105
+ }
106
+ else
107
+ changes.push(`Changed ${path || "/"}`);
108
+ };
109
+ walk(before, after, "", 0);
110
+ return changes.length ? changes : ["Observed output shape changed."];
111
+ }
@@ -0,0 +1,38 @@
1
+ import { type ToolResultLike } from "./extract.js";
2
+ export type ToolFunction = (args?: Record<string, unknown>) => Promise<unknown>;
3
+ export interface BindingCallOptions {
4
+ signal?: AbortSignal;
5
+ timeoutMs?: number;
6
+ onProgress?: (progress: {
7
+ progress: number;
8
+ total?: number;
9
+ message?: string;
10
+ }) => void;
11
+ }
12
+ /** Supply a raw MCP result; generated bindings perform the matching decode. */
13
+ export type ToolCaller = (request: {
14
+ name: string;
15
+ arguments: Record<string, unknown>;
16
+ }, options?: BindingCallOptions) => Promise<ToolResultLike>;
17
+ export declare function bindingOptions(options?: BindingCallOptions, defaults?: BindingCallOptions): {
18
+ timeout: number;
19
+ signal: AbortSignal | undefined;
20
+ onprogress: ((progress: {
21
+ progress: number;
22
+ total?: number;
23
+ message?: string;
24
+ }) => void) | undefined;
25
+ };
26
+ /** Used by generated factories. Output is observationally typed, not runtime validated.
27
+ * Transport/abort errors propagate unchanged; an MCP isError result throws ToolError. */
28
+ export declare function invokeTool<Output>(caller: ToolCaller, name: string, args: unknown, options?: BindingCallOptions): Promise<Output>;
29
+ /**
30
+ * decoded: structuredContent, else text parsed as JSON (a short prose prefix is stripped), else the text.
31
+ * raw: structuredContent, else the text as-is — what most code-mode runtimes hand the model today.
32
+ */
33
+ export type DecodeMode = "decoded" | "raw";
34
+ export declare class ToolError extends Error {
35
+ readonly tool: string;
36
+ constructor(tool: string, message: string);
37
+ }
38
+ export declare function decode(result: ToolResultLike, mode?: DecodeMode): unknown;
@@ -0,0 +1,66 @@
1
+ // SDK-free call options, decoding and execution used by both package variants.
2
+ import { extract } from "./extract.js";
3
+ export function bindingOptions(options, defaults) {
4
+ const timeout = options?.timeoutMs ?? defaults?.timeoutMs ?? 120_000;
5
+ if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 2_147_483_647)
6
+ throw new RangeError("timeoutMs must be an integer between 1 and 2147483647.");
7
+ const signal = options?.signal ?? defaults?.signal;
8
+ signal?.throwIfAborted();
9
+ return {
10
+ timeout,
11
+ signal,
12
+ onprogress: options?.onProgress ?? defaults?.onProgress,
13
+ };
14
+ }
15
+ /** Used by generated factories. Output is observationally typed, not runtime validated.
16
+ * Transport/abort errors propagate unchanged; an MCP isError result throws ToolError. */
17
+ export async function invokeTool(caller, name, args, options) {
18
+ bindingOptions(options);
19
+ if (!args || typeof args !== "object" || Array.isArray(args))
20
+ throw new TypeError("Tool arguments must be an object.");
21
+ const result = await caller({ name, arguments: args }, options);
22
+ options?.signal?.throwIfAborted();
23
+ if (result &&
24
+ typeof result === "object" &&
25
+ "resultType" in result &&
26
+ result.resultType !== undefined &&
27
+ result.resultType !== "complete") {
28
+ throw new ToolError(name, "Tool did not complete; handle its interactive or deferred result through the SDK.");
29
+ }
30
+ try {
31
+ return decode(result);
32
+ }
33
+ catch (error) {
34
+ throw new ToolError(name, error instanceof Error ? error.message : String(error));
35
+ }
36
+ }
37
+ export class ToolError extends Error {
38
+ tool;
39
+ constructor(tool, message) {
40
+ super(`${tool}: ${message}`);
41
+ this.tool = tool;
42
+ this.name = "ToolError";
43
+ }
44
+ }
45
+ export function decode(result, mode = "decoded") {
46
+ const extracted = extract(result);
47
+ if (extracted.kind === "error")
48
+ throw new Error(extracted.text || "tool returned an error");
49
+ if (mode === "raw") {
50
+ if (result.structuredContent !== undefined)
51
+ return result.structuredContent;
52
+ const texts = (result.content ?? [])
53
+ .filter((c) => c.type === "text")
54
+ .map((c) => c.text ?? "");
55
+ return texts.length === 1 ? texts[0] : texts;
56
+ }
57
+ switch (extracted.kind) {
58
+ case "structured":
59
+ case "json-text":
60
+ return extracted.value;
61
+ case "text":
62
+ return extracted.text;
63
+ case "empty":
64
+ return null;
65
+ }
66
+ }
@@ -0,0 +1,34 @@
1
+ export type OutputKind = "structured" | "json-text" | "text" | "error" | "empty";
2
+ export type Extracted = {
3
+ kind: "structured";
4
+ value: unknown;
5
+ } | {
6
+ kind: "json-text";
7
+ value: unknown;
8
+ multi: boolean;
9
+ prefix?: string;
10
+ } | {
11
+ kind: "text";
12
+ text: string;
13
+ } | {
14
+ kind: "error";
15
+ text: string;
16
+ } | {
17
+ kind: "empty";
18
+ };
19
+ interface ContentItem {
20
+ type: string;
21
+ text?: string;
22
+ }
23
+ export interface ToolResultLike {
24
+ content?: ContentItem[];
25
+ structuredContent?: unknown;
26
+ isError?: boolean;
27
+ }
28
+ /** Parses a string as JSON, tolerating code fences and a short leading sentence. */
29
+ export declare function parseJsonText(raw: string): {
30
+ value: unknown;
31
+ prefix?: string;
32
+ } | undefined;
33
+ export declare function extract(result: ToolResultLike): Extracted;
34
+ export {};
@@ -0,0 +1,73 @@
1
+ // Pulls a machine-readable value out of an MCP tool result.
2
+ // Most servers don't send structuredContent, so we also look for JSON inside text content.
3
+ const FENCE = /^```(?:json|JSON)?\s*\n([\s\S]*?)\n?```$/;
4
+ /** Parses a string as JSON, tolerating code fences and a short leading sentence. */
5
+ export function parseJsonText(raw) {
6
+ const text = raw.trim();
7
+ if (!text)
8
+ return undefined;
9
+ const fenced = FENCE.exec(text);
10
+ const body = fenced ? fenced[1].trim() : text;
11
+ const direct = tryParse(body);
12
+ if (direct.ok)
13
+ return { value: direct.value };
14
+ // "Found 3 issues:\n[...]" — accept a short prefix followed by a JSON object or array.
15
+ const start = firstJsonStart(body);
16
+ if (start > 0 && start <= 200) {
17
+ const rest = body.slice(start);
18
+ const parsed = tryParse(rest);
19
+ if (parsed.ok && typeof parsed.value === "object" && parsed.value !== null) {
20
+ return { value: parsed.value, prefix: body.slice(0, start).trim() };
21
+ }
22
+ }
23
+ return undefined;
24
+ }
25
+ export function extract(result) {
26
+ const textItems = (result.content ?? []).filter((c) => c.type === "text" && typeof c.text === "string");
27
+ const allText = textItems.map((c) => c.text).join("\n");
28
+ if (result.isError)
29
+ return { kind: "error", text: allText };
30
+ // Modern MCP permits any JSON value here, including null; absence is undefined.
31
+ if (result.structuredContent !== undefined) {
32
+ return { kind: "structured", value: result.structuredContent };
33
+ }
34
+ if (textItems.length === 0)
35
+ return { kind: "empty" };
36
+ if (textItems.length === 1) {
37
+ const parsed = parseJsonText(textItems[0].text);
38
+ if (parsed)
39
+ return { kind: "json-text", value: parsed.value, multi: false, prefix: parsed.prefix };
40
+ return { kind: "text", text: allText };
41
+ }
42
+ // Some servers send one text item per record. Treat it as an array only if every item is JSON.
43
+ const values = [];
44
+ for (const item of textItems) {
45
+ const parsed = parseJsonText(item.text);
46
+ if (!parsed || parsed.prefix)
47
+ return { kind: "text", text: allText };
48
+ values.push(parsed.value);
49
+ }
50
+ return { kind: "json-text", value: values, multi: true };
51
+ }
52
+ function tryParse(text) {
53
+ const first = text[0];
54
+ // Only structured JSON counts; a bare word like `true` or `12` in prose is too ambiguous.
55
+ if (first !== "{" && first !== "[" && first !== '"' && !/^-?\d/.test(text) && text !== "true" && text !== "false" && text !== "null") {
56
+ return { ok: false };
57
+ }
58
+ try {
59
+ return { ok: true, value: JSON.parse(text) };
60
+ }
61
+ catch {
62
+ return { ok: false };
63
+ }
64
+ }
65
+ function firstJsonStart(text) {
66
+ const brace = text.indexOf("{");
67
+ const bracket = text.indexOf("[");
68
+ if (brace < 0)
69
+ return bracket;
70
+ if (bracket < 0)
71
+ return brace;
72
+ return Math.min(brace, bracket);
73
+ }
@@ -0,0 +1,71 @@
1
+ /** Database adapters use an application-owned pool or database. Both SDKs store the
2
+ * same bounded JSON text to preserve JSON keys and numbers across SQL and BSON. */
3
+ export interface FinalAnswerRow {
4
+ identity: string;
5
+ payload: string | null;
6
+ }
7
+ export interface FinalAnswerStore {
8
+ read(job: string): Promise<FinalAnswerRow | null>;
9
+ claim(job: string, identity: string): Promise<boolean>;
10
+ complete(job: string, identity: string, payload: string): Promise<boolean>;
11
+ }
12
+ interface PgResult {
13
+ rowCount: number | null;
14
+ rows: Record<string, unknown>[];
15
+ }
16
+ interface PgQuery {
17
+ query(sql: string, values?: string[]): Promise<PgResult>;
18
+ }
19
+ interface PgPool extends PgQuery {
20
+ connect(): Promise<PgQuery & {
21
+ release(discard?: boolean): void;
22
+ }>;
23
+ }
24
+ export declare function postgresFinalAnswerStore(pool: PgPool): {
25
+ /** Run once in a migration; application workers need only SELECT, INSERT and UPDATE. */
26
+ initialize(): Promise<void>;
27
+ read(job: string): Promise<FinalAnswerRow>;
28
+ claim(job: string, identity: string): Promise<boolean>;
29
+ complete(job: string, identity: string, payload: string): Promise<boolean>;
30
+ };
31
+ interface MongoCollection {
32
+ findOne(filter: {
33
+ _id: string;
34
+ }, options: {
35
+ readPreference: "primary";
36
+ readConcern: {
37
+ level: "majority";
38
+ };
39
+ }): Promise<(FinalAnswerRow & {
40
+ _id: string;
41
+ }) | null>;
42
+ insertOne(row: FinalAnswerRow & {
43
+ _id: string;
44
+ }, options: MongoWrite): Promise<{
45
+ acknowledged: boolean;
46
+ }>;
47
+ updateOne(filter: {
48
+ _id: string;
49
+ identity: string;
50
+ payload: null;
51
+ }, update: {
52
+ $set: {
53
+ payload: string;
54
+ };
55
+ }, options: MongoWrite): Promise<{
56
+ acknowledged: boolean;
57
+ modifiedCount: number;
58
+ }>;
59
+ }
60
+ interface MongoWrite {
61
+ writeConcern: {
62
+ w: "majority";
63
+ j: true;
64
+ };
65
+ }
66
+ interface MongoDatabase {
67
+ databaseName: string;
68
+ collection(name: string): MongoCollection;
69
+ }
70
+ export declare function mongoFinalAnswerStore(database: MongoDatabase): FinalAnswerStore;
71
+ export {};