toolsplice 0.0.1 → 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 (137) hide show
  1. package/README.md +62 -330
  2. package/dist/abortable.d.ts +6 -0
  3. package/dist/abortable.js +50 -0
  4. package/dist/adaptive-read.d.ts +50 -0
  5. package/dist/adaptive-read.js +780 -0
  6. package/dist/answer-wait.d.ts +7 -0
  7. package/dist/answer-wait.js +45 -0
  8. package/dist/cache-reads.d.ts +18 -0
  9. package/dist/cache-reads.js +89 -0
  10. package/dist/calibration-ledger.d.ts +37 -0
  11. package/dist/calibration-ledger.js +148 -0
  12. package/dist/calibration-marker.d.ts +4 -0
  13. package/dist/calibration-marker.js +77 -0
  14. package/dist/catalog-setup.d.ts +33 -0
  15. package/dist/catalog-setup.js +89 -0
  16. package/dist/catalog.d.ts +10 -0
  17. package/dist/catalog.js +42 -0
  18. package/dist/checkpoint-files.d.ts +15 -0
  19. package/dist/checkpoint-files.js +99 -0
  20. package/dist/cli.js +545 -14
  21. package/dist/coalesce-reads.d.ts +6 -0
  22. package/dist/coalesce-reads.js +33 -0
  23. package/dist/contract-caller.d.ts +2 -1
  24. package/dist/contract-caller.js +35 -16
  25. package/dist/contract-schema.d.ts +3 -1
  26. package/dist/contract-schema.js +34 -4
  27. package/dist/contracts.d.ts +1 -0
  28. package/dist/contracts.js +5 -1
  29. package/dist/core.d.ts +31 -1
  30. package/dist/core.js +27 -0
  31. package/dist/db-final-answer.d.ts +9 -0
  32. package/dist/db-final-answer.js +62 -0
  33. package/dist/define.d.ts +78 -0
  34. package/dist/define.js +14 -0
  35. package/dist/final-answer-stores.d.ts +71 -0
  36. package/dist/final-answer-stores.js +72 -0
  37. package/dist/final-answer.d.ts +32 -0
  38. package/dist/final-answer.js +104 -0
  39. package/dist/impact.d.ts +48 -0
  40. package/dist/impact.js +71 -0
  41. package/dist/index.d.ts +32 -1
  42. package/dist/index.js +28 -0
  43. package/dist/local-tool.d.ts +18 -0
  44. package/dist/local-tool.js +32 -0
  45. package/dist/mcp-apps.d.ts +53 -0
  46. package/dist/mcp-apps.js +32 -0
  47. package/dist/mcp-event-delivery.d.ts +98 -0
  48. package/dist/mcp-event-delivery.js +211 -0
  49. package/dist/mcp-extensions.d.ts +46 -0
  50. package/dist/mcp-extensions.js +200 -0
  51. package/dist/mcp-peer.d.ts +45 -0
  52. package/dist/mcp-peer.js +207 -0
  53. package/dist/mcp-server-card.d.ts +21 -0
  54. package/dist/mcp-server-card.js +54 -0
  55. package/dist/page-checkpoint.d.ts +71 -0
  56. package/dist/page-checkpoint.js +286 -0
  57. package/dist/page-read-gate.d.ts +15 -0
  58. package/dist/page-read-gate.js +48 -0
  59. package/dist/pattern.d.ts +1 -0
  60. package/dist/pattern.js +27 -5
  61. package/dist/probe.js +6 -19
  62. package/dist/read-pages.d.ts +25 -0
  63. package/dist/read-pages.js +85 -0
  64. package/dist/read-policy.d.ts +6 -0
  65. package/dist/read-policy.js +16 -0
  66. package/dist/read-steps.d.ts +12 -0
  67. package/dist/read-steps.js +36 -0
  68. package/dist/result-session.d.ts +109 -0
  69. package/dist/result-session.js +620 -0
  70. package/dist/route-checkpoint.d.ts +3 -0
  71. package/dist/route-checkpoint.js +80 -0
  72. package/dist/route-driver-cli.d.ts +3 -0
  73. package/dist/route-driver-cli.js +43 -0
  74. package/dist/route-evaluation.d.ts +141 -0
  75. package/dist/route-evaluation.js +329 -0
  76. package/dist/row-groups.d.ts +17 -0
  77. package/dist/row-groups.js +79 -0
  78. package/dist/row-query.d.ts +62 -0
  79. package/dist/row-query.js +172 -0
  80. package/dist/rules.d.ts +30 -0
  81. package/dist/rules.js +72 -0
  82. package/dist/run-diagnostics.d.ts +75 -0
  83. package/dist/run-diagnostics.js +212 -0
  84. package/dist/search-fetch.d.ts +50 -0
  85. package/dist/search-fetch.js +264 -0
  86. package/dist/skill-files.d.ts +9 -0
  87. package/dist/skill-files.js +49 -0
  88. package/dist/splice-diagnostics.d.ts +4 -0
  89. package/dist/splice-diagnostics.js +24 -16
  90. package/dist/splice-measure.d.ts +33 -0
  91. package/dist/splice-measure.js +55 -0
  92. package/dist/splice-project.d.ts +12 -6
  93. package/dist/splice-project.js +72 -20
  94. package/dist/splice-recording.d.ts +29 -2
  95. package/dist/splice-recording.js +22 -5
  96. package/dist/splice.d.ts +98 -1
  97. package/dist/splice.js +225 -27
  98. package/dist/sqlite-checkpoint-store.d.ts +5 -0
  99. package/dist/sqlite-checkpoint-store.js +91 -0
  100. package/dist/sqlite-checkpoint-worker.d.ts +1 -0
  101. package/dist/sqlite-checkpoint-worker.js +115 -0
  102. package/dist/test-difference.d.ts +13 -0
  103. package/dist/test-difference.js +42 -0
  104. package/dist/testing.d.ts +122 -0
  105. package/dist/testing.js +261 -0
  106. package/dist/text-pages.d.ts +24 -0
  107. package/dist/text-pages.js +36 -0
  108. package/dist/tool-discovery.d.ts +59 -0
  109. package/dist/tool-discovery.js +136 -0
  110. package/dist/unevaluated.d.ts +7 -0
  111. package/dist/unevaluated.js +156 -0
  112. package/dist/v2.js +25 -8
  113. package/dist/version.d.ts +1 -1
  114. package/dist/version.js +1 -1
  115. package/dist/workflow-json.js +1 -1
  116. package/docs/AGENT-FRAMEWORKS.md +431 -0
  117. package/docs/BENCHMARKS.md +43 -0
  118. package/docs/INTEGRATION-QUICKSTART.md +859 -0
  119. package/docs/LEARNING-AND-STORAGE.md +393 -0
  120. package/docs/MCP.md +204 -0
  121. package/docs/PROJECTS-AND-UPGRADES.md +67 -9
  122. package/docs/PYTHON-REFERENCE.md +348 -0
  123. package/docs/PYTHON.md +120 -0
  124. package/docs/RECORDING-AND-CORRECTIONS.md +30 -1
  125. package/docs/TESTING.md +259 -0
  126. package/examples/mcp-app/build.mjs +11 -0
  127. package/examples/mcp-app/view.mjs +22 -0
  128. package/examples/quickstart.mjs +43 -0
  129. package/examples/route-driver.mjs +67 -0
  130. package/integrations/ai.d.mts +36 -0
  131. package/integrations/ai.mjs +178 -0
  132. package/integrations/call-options.mjs +9 -0
  133. package/integrations/langchain.d.mts +31 -0
  134. package/integrations/langchain.mjs +114 -0
  135. package/integrations/managed.mjs +154 -0
  136. package/integrations/types.d.mts +13 -0
  137. package/package.json +47 -3
package/README.md CHANGED
@@ -1,373 +1,105 @@
1
1
  # Toolsplice
2
2
 
3
- **Test your MCP handoffs against saved responses and changed contracts.** Dry-run an explicit output-to-input mapping, replay captured calls offline, and generate a typed adapter that validates every destination argument before sending the first destination call.
3
+ Toolsplice connects the output of one MCP tool to the input of another. Your application defines the field mapping and validates it before a destination runs. An agent can then call the whole workflow as one tool. The same workflow can connect a remote tool to an ordinary function.
4
4
 
5
- ```text
6
- issues.list_issues[] people.get_person
7
- assignee.personId ───→ id
8
- ```
9
-
10
- A source field can be missing, nullable, inside a JSON string, or the wrong type for the next tool. A batch can contain one bad row halfway through. Toolsplice makes the mapping explicit and checks these assumptions using declared schemas or shapes learned from actual responses.
5
+ Use a checked handoff when the steps are known. For open-ended questions, wrap the agent's existing tools so it can receive a small result directly or inspect selected fields from a larger response. For jobs that span workers, save completed answers or page progress under a stable job ID.
11
6
 
12
- **Initial release, v0.0.1. Node.js 22+, ESM.** The package was previously called Callshape. `callshape` and `mcp-shape` remain CLI aliases, and existing learning stores remain readable.
7
+ ## Install
13
8
 
14
- An author-run [maintenance comparison](docs/MAINTENANCE-TRIAL.md) checks three existing project workflows against handwritten integrations using saved public responses and labelled mutations. Equally guarded code makes the same decisions; Toolsplice's proposed value is reusable artifacts, offline replay and diagnostics. Structural checks do not establish content accuracy. No independent adoption or developer-time savings have been measured. See the [developer trial](docs/DEVELOPER-TRIAL.md) for the next acceptance test.
15
-
16
- ## Start with one command
9
+ Requires Node.js 22 or later and ES modules.
17
10
 
18
11
  ```sh
19
- npm install toolsplice@0.0.1
12
+ npm install toolsplice@0.0.2
20
13
  npx toolsplice init ./my-handoff
21
- toolsplice project ./my-handoff --allow-review --json
22
- ```
23
-
24
- When building from a local checkout, use `node dist/cli.js` in place of `toolsplice` after `npm run build`. The starter has synthetic contracts, an explicit plan, input/context, a source fixture and a generated adapter. Its check validates source arguments, context, source output, every mapped destination argument and whether the adapter is current. It calls no tools and installs no packages. Existing directories are refused.
25
-
26
- Use a successful payload recording to scaffold an existing handoff without guessing its mapping:
27
-
28
- ```sh
29
- toolsplice init ./my-handoff --from-recording recording.json
30
- ```
31
-
32
- Redacted recordings need an explicit private `--restorations` file. Restored project inputs/fixtures may contain confidential values and are written into a new private directory; the retained recording remains redacted. See the [projects and upgrades guide](docs/PROJECTS-AND-UPGRADES.md).
33
-
34
- ## Choose the package
35
-
36
- - **`toolsplice`**: existing full library and CLI, SDK convenience adapters, learning proxy and optional PostgreSQL support. Existing imports and binary aliases remain supported.
37
- - **`toolsplice-core`**: independently packaged Node library with handoff validation, typed adapter generation, recording/replay and corrections. Its production dependencies are Ajv and re2js; it requires no MCP SDK, Zod, transport/server stack or PostgreSQL driver. Applications provide raw-result `ToolCaller` functions.
38
-
39
- Install `toolsplice@0.0.1` or `toolsplice-core@0.0.1`. For local development, `npm run build` prepares both; `npm pack` and `npm pack ./packages/core` create their respective tarballs for local installation. Core generation defaults to importing `toolsplice-core`; full-package generation defaults to `toolsplice`. Splitting the packages reduces installation dependencies for core consumers; the full package continues to include its transport features.
40
-
41
- ## Python
42
-
43
- The [native Python SDK](packages/python/README.md) accepts async tool callers and optional MCP/HTTP adapters. No agent framework or Node runtime is required. Install with `python -m pip install toolsplice==0.0.1` (Python 3.11+), or `python -m pip install ./packages/python` from this checkout.
44
-
45
- Version `0.0.1` includes static preflight, portable contracts/recordings/corrections, typed Python adapters, project CLI, shape learning, file/PostgreSQL stores, transparent MCP proxy and HTTPX middleware alongside the existing runtime checks. Shared artifacts/fingerprints and database/file locks are checked against JavaScript; generated Python/TypeScript files remain language-specific. See the [parity matrix](docs/PYTHON-PARITY.md) for tests and boundaries; the historical v0.1 preview report remains separately versioned.
46
-
47
- ## Check an upgrade offline
48
-
49
- ```sh
50
- toolsplice replay recording.json --target-contract new-target.json --json
51
- toolsplice replay recording.json --source-contract new-source.json \
52
- --target-contract new-target.json --allow-review --json
53
- ```
54
-
55
- Candidate contracts are checked against the saved requests/responses, with schema diffs and field-origin explanations. `upgrade.status` is `passed`, `failed` or `inconclusive`. Previously failed/cancelled recordings cannot establish successful upgrade compatibility. Candidate checks exit 2 for failures or inconclusive results; ordinary replay still treats a matching expected failure as a passing regression. This verifies captured cases, not every possible provider response. Saved artifacts are never changed.
56
-
57
- ## Run the demo
58
-
59
- For the handoff and recording workflow, run:
60
-
61
- ```sh
62
- npm ci
63
- npm run demo:handoff
64
- ```
65
-
66
- It starts two synthetic MCP servers, writes four new Markdown files inside a private demo folder, and proves invalid context/source inputs, no-data responses and duplicate destination paths stop at the expected boundary. It compiles two generated adapters with five negative type checks and runs a compact offline CLI review. It records success/failure, shuts down both servers and replays those runs with zero further tool calls. There are ten native MCP tool calls and no model/API account is needed. Inspect the printed `demo-output/handoff-*/` directory, including `saved/`, `plan.json`, `context.json`, `adapter.ts`, `offline-review.json`, `recording-success.json`, `recording-failure.json` and `report.json`. `--out` selects a new directory, and `--json` prints the machine-readable report.
67
-
68
- The existing issue → person demo also covers learning from ordinary traffic. From this checkout:
69
-
70
- ```sh
71
- npm ci
72
- npm run demo
14
+ npx toolsplice test ./my-handoff
73
15
  ```
74
16
 
75
- The demo starts two synthetic MCP servers and:
17
+ The two starter cases run offline. One checks the mapped arguments. The other checks that an invalid source prevents a destination call.
76
18
 
77
- 1. Observes an issue-list result and a person lookup, including JSON returned after a prose prefix.
78
- 2. Checks an explicit mapping and dry-runs a saved result with **zero additional tool calls**.
79
- 3. Blocks numeric `issue.id → person.id` before either server is called.
80
- 4. Generates and compiles a TypeScript adapter, checking six incorrect type usages.
81
- 5. Runs the corrected adapter: **one source call and two destination calls**.
82
- 6. Changes the source output and verifies that neither destination lookup runs.
19
+ ## Connect a read to a local function
83
20
 
84
- Inspect the printed `demo-output/run-*/` folder: `splice.json`, `preflight.json`, `bad-plan-report.json`, `adapter.ts`, `workflow.ts`, and `report.json`. Runs use fresh folders. `npm run demo -- --out /absolute/path/to/new-folder` selects a new directory whose parent exists. The fixture data is synthetic; no model, API key or external account is needed. The generated folder links to this checkout for package resolution.
21
+ This runnable example maps a document's `text` to a counter's `content` argument. The mock source checks the public tool boundary offline. Save it as `count.mjs` and run `node count.mjs`.
85
22
 
86
- ## Record, explain and replay
23
+ ```js
24
+ import { createMockCaller, defineLocalTool, defineSplice } from "toolsplice";
87
25
 
88
- Capture one run through the standalone library. No Cloudflare service or account is required:
89
-
90
- ```ts
91
- import { createSpliceRecorder, replaySpliceRecording } from 'toolsplice';
92
-
93
- const recorder = createSpliceRecorder(plan, sourceContract, targetContract, {
94
- capture: 'payloads', // Default is metadata only.
95
- redactKeys: ['customerEmail'],
96
- redactValues: [process.env.PROVIDER_SECRET].filter((v): v is string => !!v),
26
+ const string = { type: "string" };
27
+ const fields = (name) => ({
28
+ type: "object", properties: { [name]: string }, required: [name],
97
29
  });
98
- await recorder.run(sourceCaller, targetCaller, input, {
99
- allowReview: true,
100
- context: { path: 'saved.md' },
30
+ const count = defineLocalTool({
31
+ name: "count_words", inputSchema: fields("content"), outputSchema: { type: "integer" },
32
+ }, ({ content }) => content.trim().split(/\s+/u).filter(Boolean).length);
33
+
34
+ const handoff = defineSplice({
35
+ source: { server: "docs", tool: "read", inputSchema: fields("id"), outputSchema: fields("text") },
36
+ target: { server: "local", tool: "count_words", inputSchema: fields("content"), outputSchema: { type: "integer" } },
37
+ bindings: [{ from: "/text", to: "/content" }],
101
38
  });
102
- const recording = recorder.snapshot(); // Also available after a rejected run.
103
- // Application owns storage; save explicitly to a private file.
104
-
105
- // Later, using an unredacted recording or explicit private restorations:
106
- const report = await replaySpliceRecording(savedRecording);
107
- console.log(report.matched, report.networkCalls); // expected true, 0
108
- ```
109
-
110
- ```sh
111
- node dist/cli.js replay recording.json --json
112
- node dist/cli.js replay recording.json --restorations private-values.json --json
113
- node dist/cli.js correct baseline.json --correction reviewed-correction.json \
114
- --out corrected.json --json
115
- ```
116
-
117
- Replay uses saved raw MCP responses and the saved contracts with the current guard implementation. It accepts no live caller/connection. A matching expected failure exits 0; a different call sequence, arguments or outcome exits 2. Invalid, incomplete or unrestored artifacts exit 1. CLI reports omit returned result payloads. Redaction is configurable and does not guarantee anonymization. Every redacted artifact path requires an explicit restoration before replay.
118
-
119
- Use `explainSpliceError(plan, error)` for path-only failure details: binding index, destination path, source/context path, source selection/JSON parsing and row number where available. Literal values and raw exception causes are excluded. Fixture CLI reports include this explanation automatically.
120
-
121
- Reviewed corrections pin the baseline fingerprint, replace explicit tool input/output schemas and require positive and negative fixtures. All fixtures must pass offline before a separate corrected contract is returned or written. The original is retained; output corrections are labelled `corrected`, and correction metadata is fingerprinted. Applications explicitly choose the corrected contract for execution. There is no automatic schema weakening or claim that fixtures prove live-provider behavior.
122
-
123
- See [recording and corrections guide](docs/RECORDING-AND-CORRECTIONS.md) for complete formats, redaction/restoration, limits and examples.
124
-
125
- ## Define the handoff
126
-
127
- A plan names the endpoints and maps JSON pointers explicitly:
128
-
129
- ```json
130
- {
131
- "format": "toolsplice-splice",
132
- "formatVersion": 1,
133
- "source": { "server": "issues", "tool": "list_issues" },
134
- "target": { "server": "people", "tool": "get_person" },
135
- "forEach": true,
136
- "maxItems": 50,
137
- "bindings": [
138
- { "to": "/id", "from": "/assignee/personId" }
139
- ]
140
- }
141
- ```
142
-
143
- `forEach` is opt-in. It changes the binding's source to one array item and caps the entire batch before destination dispatch. The default cap is 100; supported caps are 1–1,000. Without `forEach`, one destination argument object is produced. Empty batches make no destination calls. Exceeding the cap rejects the whole batch; it never silently truncates it.
144
-
145
- Use `{ "to": "/state", "value": "open" }` for a literal. Destination paths can build nested objects, such as `/body/id`; they cannot overlap or create array elements. Map an entire array into its argument field instead. Paths use RFC 6901 escaping (`~1` for `/`, `~0` for `~`). Values are copied without coercion, and missing fields are errors.
146
-
147
- For a JSON string inside an output wrapper, select and decode it explicitly:
148
-
149
- ```json
150
- "source": {
151
- "server": "filesystem",
152
- "tool": "directory_tree",
153
- "path": "/content",
154
- "parseJson": true
155
- }
156
- ```
157
-
158
- For APIs with a business success flag, add an explicit source expectation:
159
-
160
- ```json
161
- "source": {
162
- "server": "firecrawl",
163
- "tool": "firecrawl_search",
164
- "expect": [{ "path": "/success", "equals": true }],
165
- "path": "/data/web/0"
166
- }
167
- ```
168
-
169
- Expectations check the whole decoded response before `path`, `parseJson` or fanout. Missing fields and unequal JSON values stop execution before any destination call. Equality ignores object key order. Plans support up to 16 conditions and require review approval; Toolsplice does not guess which API flags mean success. Protocol `isError` responses already stop execution.
170
-
171
- Toolsplice's ordinary MCP decoder already handles structured content and JSON text with a short prose prefix. `parseJson` handles an additional JSON document stored inside a string. It does not invent a parser for arbitrary prose.
172
-
173
- Validation evidence and measured limits: [v0.6 report](docs/PIVOT-VALIDATION.md), [real-workflow assessment](docs/USEFULNESS-ASSESSMENT.md).
174
-
175
- ## Add explicit data requirements
176
-
177
- A valid string can still say “No documentation found.” Add a consumer schema to the selected source value:
178
-
179
- ```json
180
- "source": {
181
- "server": "gitmcp", "tool": "fetch_typescript_sdk_docs",
182
- "valueSchema": {
183
- "type": "string", "minLength": 100,
184
- "not": { "const": "No documentation found." }
185
- }
186
- }
187
- ```
188
-
189
- `valueSchema` runs after `path` and `parseJson`, before `forEach` or any destination dispatch. Use an array schema with `minItems` to reject an empty result set, or an object schema to require particular fields. It adds a consumer requirement; it does not change the saved server contract or prove that content is true. These plans require review, and unsupported validator assertions block setup. A failed requirement is a mapping-stage error in both fixtures and live runs.
190
-
191
- For a batch whose destination identifiers must be distinct, declare explicit keys:
192
-
193
- ```json
194
- "target": {
195
- "server": "filesystem", "tool": "write_file",
196
- "uniqueBy": ["/path"]
197
- }
198
- ```
199
-
200
- Toolsplice rejects the whole batch before its first destination call if a key is absent or two rows have the same tuple of key values. Multiple paths form one composite tuple, such as `["/tenantId", "/id"]`. JSON types remain distinct and object key order does not matter. Keys use destination argument paths; specify 1–8 paths without duplicates or overlaps. Uniqueness is optional, requires review, and applies only inside one mapped batch. It does not deduplicate, normalize identifiers, provide cross-run idempotency, or detect collisions in fields you did not select. Per-call context is shared by every row; using one file path for a multi-row batch will collide when `/path` is the declared key.
201
-
202
- ## Bound returned data
203
-
204
- Plans can set `"maxResultBytes": 65536` to cap the UTF-8 JSON encoding of the final result array. The default is 5 MiB; supported limits are 2 bytes–64 MiB. Destination values are copied as bounded JSON before collection. A result that exceeds the remaining budget throws a target-stage `result-batch-byte-limit` error and prevents later destination calls; it does not truncate data or return partial success. The overflowing remote call may already have completed or committed. The count records earlier validated, collected results, not all remote side effects. This cap applies after a response is decoded; it is not a transport download limit or a model-token budget.
205
-
206
- ## Real-server verification
207
-
208
- `npm run test:handoffs` explicitly downloads pinned official filesystem/memory servers into a disposable directory and calls the public DeepWiki and Microsoft Learn MCP endpoints. It compiles and executes generated adapters for DeepWiki → file, Learn search → fetch, file → memory lookup and explicit memory fanout. It also proves actual source errors and exceeded fanout caps prevent destination calls. Evidence goes to `test-results/`; remote responses and schemas can change.
209
-
210
- `FIRECRAWL_API_KEY=... npm run test:firecrawl` runs a small authenticated search → scrape test using the real Firecrawl MCP server. It makes two live tool calls and consumes provider credits. It verifies a generated adapter, source success expectations, and invalid-input prevention; the credential is never written by the harness. The initial keyless connection listed tools but refused search from the test network. An authenticated run succeeded. No model API is used by these harnesses; provider-side implementation and billing remain the provider's responsibility.
211
-
212
- `npm run test:firecrawl:workflows` exercises map → three scrapes, search → three link scrapes and paper search → two paper inspections. `npm run test:firecrawl:files` compiles a reusable scrape → filesystem adapter with per-call paths, then exposes it as one ordinary MCP tool. Both are explicitly opt-in, consume Firecrawl credits and retain public response fixtures locally. The filesystem harness installs a pinned reference server into disposable storage. No model API is called.
213
-
214
- `npm run test:public:files` exercises public Context7, Hugging Face, Exa and GitMCP outputs against the official filesystem server, including an explicit no-data requirement. `npm run test:catalogs` lists public remote catalogs and checks validator setup without calling tools. Catalog coverage is not an execution or semantic-accuracy guarantee.
215
-
216
- A real Firecrawl JSON-extraction probe found a declared-input/provider disagreement: its catalog rejects fields inside `jsonOptions.schema` that the server accepted. Toolsplice honors the reviewed catalog; it does not silently weaken a schema to make a request succeed. Review an explicit application-owned contract correction when a provider declaration is inaccurate. Shape validation also cannot verify extracted facts.
217
-
218
- ## Check, dry-run and generate
219
-
220
- Use portable contract snapshots without a database or server connection:
221
-
222
- ```sh
223
- node dist/cli.js splice plan.json \
224
- --source-contract issues.json --target-contract people.json --json
225
-
226
- node dist/cli.js splice plan.json \
227
- --source-contract issues.json --target-contract people.json \
228
- --fixture saved-result.json --fixture-format mcp \
229
- --out adapter.ts --json
230
- ```
231
-
232
- Saved MCP `tools/list` responses also work directly. No learning proxy or database is required:
233
39
 
234
- ```sh
235
- node dist/cli.js splice plan.json \
236
- --source-catalog source-tools.json --target-catalog target-tools.json \
237
- --fixture result.json --fixture-format mcp --out adapter.ts --json
40
+ const read = createMockCaller([{
41
+ name: "read", arguments: { id: "a1" }, result: { structuredContent: { text: "one two three" } },
42
+ }]);
43
+ console.log(await handoff.run(read, count.caller, { id: "a1" })); // [3]
44
+ read.assertDone();
238
45
  ```
239
46
 
240
- Each endpoint accepts exactly one contract or catalog file; mixing a source contract with a target catalog is supported. Catalog identities come from the explicit plan. Catalogs describe declared schemas only; an omitted output remains unknown. Applications must collect the page containing the selected tool, or combine all `tools/list` pages. Missing selected tools and duplicate names are rejected.
241
-
242
- Alternatively, read existing learning from files or PostgreSQL:
243
-
244
- ```sh
245
- node dist/cli.js splice plan.json --store /private/learning --json
246
- node dist/cli.js splice plan.json --database-env TOOL_STORAGE_URL --namespace project --json
247
- ```
47
+ For an existing MCP v1 client, replace `read` with `createToolCaller(client)`. To expose the handoff to an agent, use `handoff.asTool({ name: "document_word_count", source: read, target: count.caller })`. Review `handoff.report` when either endpoint has incomplete contracts or the plan includes application rules.
248
48
 
249
- These commands **never execute tools**. File-based checking does not open a learning store. `--fixture-format decoded` is the default; `mcp` decodes a saved MCP result envelope first. Dry-run output can contain the fixture values you explicitly supplied. `--out` writes a new `.ts` source file and refuses to overwrite it; blocked plans do not produce adapters.
49
+ ## Add Toolsplice to an existing agent
250
50
 
251
- Reports identify the exact plan and both endpoint contracts with fingerprints. Save the plan, contracts, fixture and report together to make a review reproducible. Add `--summary` to JSON fixture reports to keep mapped values out of the report while retaining row count and total argument bytes. It does not change validation or what an adapter would send. `--allow-review` changes a reviewed plan’s CLI exit to 0; `status` stays `review`, blocked plans still exit 2, and generated adapters still require their own runtime `allowReview: true`. This supports an intentional CI gate without treating uncertainty as compatibility.
51
+ Each example uses your existing `model`, authorized tools and user `question`. The wrapper creates and closes a result session for the request.
252
52
 
253
- Statuses are deliberately conservative:
53
+ ### Vercel AI SDK
254
54
 
255
- | Status | Meaning | CLI exit | Adapter execution |
256
- |---|---|---:|---|
257
- | `ready` | Supported structural checks establish the mapping | 0 | Runtime guards still apply |
258
- | `review` | Missing observations, optional fields or constraints leave uncertainty | 2 | Requires explicit `allowReview: true` |
259
- | `blocked` | A known incompatibility or unsupported runtime schema prevents execution | 2 | Cannot execute |
55
+ Install `ai` (v6 or v7) alongside Toolsplice. Pass the tool map from your application or MCP client.
260
56
 
261
- A valid JSON fixture that fails source or mapping validation produces `status: blocked`, a structured `fixture` failure and exit 2; it does not create an adapter. `preflightStatus` preserves the static result. Raw MCP error fixtures are reported without echoing the provider error text. Malformed plans, unreadable files and configuration errors exit 1. Shape compatibility is not semantic identity: a `customerId` and an `orderId` can both be strings. **Toolsplice never guesses which fields mean the same thing.** Review the mapping yourself. Observed schemas remain provisional, and `ready` is not a provider guarantee.
57
+ ```js
58
+ import { generateText, stepCountIs } from "ai";
59
+ import { withAiTools } from "toolsplice/ai";
262
60
 
263
- If a server has no usable output schema, the optional learning proxy can observe ordinary traffic and save its return shape. It makes no extra calls to learn. See [learning and storage](docs/LEARNING-AND-STORAGE.md) for config generation, file paths/PVCs, PostgreSQL and snapshots. A developer with declared schemas can also construct a snapshot through `newServer`, `recordToolList` and `createContractSnapshot`.
264
-
265
- ## Use the generated adapter
266
-
267
- Compile `adapter.ts` with your application:
268
-
269
- ```ts
270
- import { createToolCaller } from 'toolsplice';
271
- import { createSplice } from './adapter.js';
272
-
273
- const lookupOwners = createSplice(
274
- createToolCaller(issueClient),
275
- createToolCaller(peopleClient),
61
+ const { text } = await withAiTools(existingTools, question, (tools, activeTools) =>
62
+ generateText({
63
+ model, tools, prompt: question, stopWhen: stepCountIs(6),
64
+ prepareStep: () => ({ activeTools: activeTools() }),
65
+ })
276
66
  );
277
- const owners = await lookupOwners({ state: 'open' }, {
278
- signal: abortController.signal,
279
- timeoutMs: 30_000,
280
- });
281
- ```
282
-
283
- Use `createV2ToolCaller` from `toolsplice/v2` for SDK 2.x clients. Applications establish connections, authentication and authorization. Generated source input and destination output types come from the selected contracts. The result array follows source-row order; destination calls run sequentially. This is a two-tool adapter, not a general workflow executor or an execution sandbox.
284
-
285
- The library surface is also usable directly:
286
-
287
- ```ts
288
- import { prepareSplice } from 'toolsplice';
289
-
290
- const splice = prepareSplice(plan, sourceContract, targetContract);
291
- console.log(splice.report);
292
- const argumentsForReview = await splice.mapOutput(savedDecodedOutput); // no tool calls
293
- const results = await splice.run(sourceCaller, targetCaller, sourceArgs);
294
67
  ```
295
68
 
296
- `parseSpliceSpec`, `preflightSplice` and `emitSpliceModule` are also exported. `prepareSplice` includes runtime-schema setup checks; `preflightSplice` performs only static analysis. `mapOutput` checks the whole fixture against the known source contract before validating mapped arguments. It can test a `review` plan against a fixture; live execution still requires `allowReview: true`. A `blocked` plan cannot map or run.
297
-
298
- Source inputs are checked before the source call, source outputs after it, and **every mapped destination argument before any destination call**. Known destination output schemas are checked too; unknown outputs remain `unknown`. Cancellation and progress options pass through; `timeoutMs` applies to each tool call, not the whole splice. Use a deadline-backed `AbortSignal` to bound the entire operation. There are no retries or automatic skips. A destination failure throws `SpliceError` with `stage`, path-only `issues`, `completedTargets`, and its original `cause`. Completed destination calls are not rolled back; a failed or canceled remote request may already have committed. Output checks cannot undo the source's effects.
299
-
300
- ## Supply values for each call
301
-
302
- A reusable scrape → file adapter needs both scraped content and an application-selected file path. Declare context separately from the source tool's arguments:
303
-
304
- ```json
305
- {
306
- "format": "toolsplice-splice",
307
- "formatVersion": 1,
308
- "source": { "server": "firecrawl", "tool": "firecrawl_scrape" },
309
- "target": { "server": "filesystem", "tool": "write_file" },
310
- "contextSchema": {
311
- "type": "object",
312
- "properties": { "path": { "type": "string", "minLength": 1 } },
313
- "required": ["path"],
314
- "additionalProperties": false
315
- },
316
- "bindings": [
317
- { "to": "/content", "from": "/markdown" },
318
- { "to": "/path", "fromContext": "/path" }
319
- ]
320
- }
321
- ```
69
+ ### LangChain
322
70
 
323
- ```ts
324
- const savePage = createSplice(firecrawlCaller, filesystemCaller);
325
- await savePage({ url, formats: ['markdown'], objective: 'Save this documentation.' }, {
326
- allowReview: true,
327
- context: { path: '/application-approved-output/page.md' },
328
- });
329
- ```
71
+ Install `langchain` and `@langchain/core@^1`. Pass the tool array you already supply to the agent.
330
72
 
331
- Generated adapters require typed `context` options when the plan declares `contextSchema`. The schema must have an object root and follows the same bounded runtime validation rules as endpoint contracts. Invalid context and missing mapped context paths stop before the source call. Context is copied before awaiting tools, isolated between runs, and excluded from caller options; explicitly mapped context fields are sent to the destination. Applications own filesystem permissions and allowed paths; a string schema does not authorize a path. Context bindings require review and all destination arguments remain validated before dispatch.
73
+ ```js
74
+ import { createAgent } from "langchain";
75
+ import { withLangChainTools } from "toolsplice/langchain";
332
76
 
333
- For offline fixtures, pass `--context context.json`, or `splice.mapOutput(savedOutput, { context: { path } })`. Context files are used only with `--fixture`; they are not embedded in generated adapters. A fixture rejected at the context stage creates no adapter.
334
-
335
- Build contracts in application code directly from catalogs:
336
-
337
- ```ts
338
- import { createContractFromCatalog } from 'toolsplice';
339
- const source = createContractFromCatalog(
340
- { name: 'firecrawl' }, await firecrawlClient.listTools(),
341
- { tools: ['firecrawl_scrape'] },
77
+ const state = await withLangChainTools(existingTools, question, tools =>
78
+ createAgent({ model, tools }).invoke({ messages: [{ role: "user", content: question }] })
342
79
  );
80
+ console.log(state.messages.at(-1).content);
343
81
  ```
344
82
 
345
- ## Expose one tool to an agent
346
-
347
- The [application-side example](examples/compose-mcp-tool.ts) wraps a generated adapter as an ordinary MCP tool and validates its advertised outer input schema before running the adapter. Applications supply the reviewed input schema, connected callers and any explicit approval for a `review` plan. It forwards cancellation, normalizes progress events from multiple internal calls, and returns only `{ results: [...] }` from the destination.
83
+ ## Connect real tools
348
84
 
349
- The real-server harness uses this example: one external `save_wiki_outline` tool call performs a DeepWiki read and a filesystem write. Intermediate documentation stays inside the application. This is an optional example, not an automatically installed server or new MCP protocol.
85
+ Use the two `tools/list` catalogs from MCP clients that your application has already authorized. Choose a source and destination, then map source JSON pointers to destination arguments. The CLI can scaffold the mapping and its first regression test. [Start from two catalogs](https://cdn.jsdelivr.net/npm/toolsplice@0.0.2/docs/TESTING.md#start-from-two-real-tools)
350
86
 
351
- ## Scope and current limits
87
+ A search followed by a fetch is a common example. Register both reads once, restrict the allowed origins, and expose the combined tool to the model. One model-visible invocation still performs the underlying search and fetch. [Search and fetch guide](https://cdn.jsdelivr.net/npm/toolsplice@0.0.2/docs/INTEGRATION-QUICKSTART.md#search-and-fetch-in-one-model-tool-call)
352
88
 
353
- Static analysis supports a conservative subset of object/array paths, types, enums, presence and bounds. Complex schema relationships require review rather than a claim of compatibility. Runtime guards support bounded structural subsets of explicit Draft 7 and JSON Schema 2020-12; format/content annotations are not enforced, a bounded ASCII regex subset runs through the non-backtracking RE2JS engine, external refs are rejected, and unsupported assertions fail setup. [The reference](docs/LEARNING-AND-STORAGE.md#guard-a-tool-chain-at-runtime) documents dialect, size and resource limits. Plan limits are 1 MiB, 64 non-overlapping bindings and 32 path segments. All mapped arguments together are capped at 5 MiB. Patterns are capped at 1,024 characters and 64 per input/output schema; unsupported regex constructs fail setup.
89
+ Normal calls use an in-memory result store. To resume work after a restart, choose a persistent directory or a supported checkpoint database. Give each job a stable ID and bind the tenant, inputs and workflow version to its checkpoint. Authorize access on every replay. [Recovery with files, PostgreSQL or MongoDB](https://cdn.jsdelivr.net/npm/toolsplice@0.0.2/docs/INTEGRATION-QUICKSTART.md#recover-a-completed-answer-after-a-restart)
354
90
 
355
- No automatic field matching, numeric/string conversion, semantic ID validation, joins, arbitrary transforms, rollback, distributed execution, sandbox, or Python client is included. Existing file/PostgreSQL learning and contract checks support the adapter workflow; they are not the product's differentiation.
91
+ ## Benchmarks
356
92
 
357
- ## Why this direction
93
+ In 20 live Microsoft Learn lookups per configuration, all three approaches returned the exact URL, heading and literal count every time. The conventional loop made two model calls per lookup. Both early-return approaches made one, with two MCP reads in every configuration.
358
94
 
359
- [Cloudflare Code Mode](https://developers.cloudflare.com/agents/tools/codemode/) and [Model Context Shell](https://github.com/StacklokLabs/model-context-shell) already compose tools. [SEP-1610](https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1610) proposed declarative MCP chaining with JSON-pointer mapping; it was closed as dormant on June 26, 2026 and was not adopted. Toolsplice uses ordinary MCP calls and does not implement that draft extension. [mcp-contracts](https://github.com/mcp-contracts/mcp-contracts), [Covenant](https://github.com/Mhemd139/Covenant) and [Agothe](https://agothe.ai/mcp-breaking-change-checker/) cover contract snapshots/drift or release checks. Toolsplice concentrates on an explicit **output-to-input handoff**, fixture dry-runs and generated adapters, including undeclared outputs learned from traffic. Related building blocks exist; there is no claim of complete uniqueness.
95
+ | Implementation | Vercel AI SDK p95 | Agno p95 | Mean model USD/lookup |
96
+ | --- | ---: | ---: | ---: |
97
+ | Native agent loop | 6.379 s | 7.892 s | 0.0000680 |
98
+ | Native early return | 4.491 s | 5.912 s | 0.0000264 |
99
+ | Toolsplice with checkpoint | 4.039 s | 4.988 s | 0.0000264 |
360
100
 
361
- It can prevent demonstrably invalid destination calls and remove repeated parsing/mapping code. Fewer model turns or lower total agent cost remain hypotheses until measured in a real workflow. Learning and checks make no model calls; validation and descriptions also add overhead. Paid model benchmarks remain paused.
101
+ A separate ten-page recovery test matched native on accuracy, model calls and cost. Toolsplice had a lower observed wall p95 with Vercel and a higher one with Agno. The sample was four jobs per configuration. [Full tables, controls and timing boundaries](https://cdn.jsdelivr.net/npm/toolsplice@0.0.2/docs/BENCHMARKS.md)
362
102
 
363
- ## Validation
364
-
365
- ```sh
366
- npm run typecheck
367
- npm test
368
- npm run demo
369
- npm run test:package
370
- npm run test:real
371
- ```
103
+ The Python distribution includes native Agno and LangChain integrations. The smaller Node package provides the handoff runtime for applications that supply their own transport. [Python SDK](https://pypi.org/project/toolsplice/) · [Standalone Node runtime](https://www.npmjs.com/package/toolsplice-core) · [Integration guide](https://cdn.jsdelivr.net/npm/toolsplice@0.0.2/docs/INTEGRATION-QUICKSTART.md)
372
104
 
373
- Tests use synthetic data, local MCP servers and disposable reference-server storage. Clean-package checks pack/install locally without publishing. Optional PostgreSQL and longer lifecycle tests are documented in the [reference](docs/LEARNING-AND-STORAGE.md#testing). Historical evidence remains in `docs/VALIDATION.md`, `POSTGRES-VALIDATION.md` and `BINDINGS-VALIDATION.md`; those earlier runs do not prove the new adapter behavior.
105
+ [Python API and CLI reference](https://cdn.jsdelivr.net/npm/toolsplice@0.0.2/docs/PYTHON-REFERENCE.md)
@@ -0,0 +1,6 @@
1
+ import { type BindingCallOptions } from "./execution.js";
2
+ /** Stop awaiting an application callback when its caller aborts. */
3
+ export declare function abortable<T>(action: () => T | PromiseLike<T>, signal?: AbortSignal): Promise<T>;
4
+ export declare function isReadDeadline(error: unknown): boolean;
5
+ /** Apply one optional deadline across application callbacks and propagate caller cancellation. */
6
+ export declare function withCallDeadline<T, O extends BindingCallOptions>(options: O | undefined, message: string, action: (options?: O) => T | PromiseLike<T>): Promise<T>;
@@ -0,0 +1,50 @@
1
+ import { bindingOptions } from "./execution.js";
2
+ /** Stop awaiting an application callback when its caller aborts. */
3
+ export async function abortable(action, signal) {
4
+ if (!signal)
5
+ return action();
6
+ signal.throwIfAborted();
7
+ let onAbort;
8
+ const aborted = new Promise((_, reject) => {
9
+ onAbort = () => reject(signal.reason);
10
+ signal.addEventListener("abort", onAbort, { once: true });
11
+ });
12
+ try {
13
+ return await Promise.race([
14
+ Promise.resolve().then(() => {
15
+ signal.throwIfAborted();
16
+ return action();
17
+ }),
18
+ aborted,
19
+ ]);
20
+ }
21
+ finally {
22
+ signal.removeEventListener("abort", onAbort);
23
+ }
24
+ }
25
+ const localDeadlines = new WeakSet();
26
+ export function isReadDeadline(error) {
27
+ return error instanceof DOMException && localDeadlines.has(error);
28
+ }
29
+ function readDeadline(message) {
30
+ const error = new DOMException(message, "TimeoutError");
31
+ localDeadlines.add(error);
32
+ return error;
33
+ }
34
+ /** Apply one optional deadline across application callbacks and propagate caller cancellation. */
35
+ export async function withCallDeadline(options, message, action) {
36
+ if (options?.timeoutMs === undefined)
37
+ return abortable(() => action(options), options?.signal);
38
+ const { timeout } = bindingOptions(options);
39
+ const deadline = new AbortController();
40
+ const signal = options.signal
41
+ ? AbortSignal.any([options.signal, deadline.signal])
42
+ : deadline.signal;
43
+ const timer = setTimeout(() => deadline.abort(readDeadline(message)), timeout);
44
+ try {
45
+ return await abortable(() => action({ ...options, signal }), signal);
46
+ }
47
+ finally {
48
+ clearTimeout(timer);
49
+ }
50
+ }
@@ -0,0 +1,50 @@
1
+ export declare function literalCount(text: string, literal: string): {
2
+ literal: string;
3
+ count: number;
4
+ complete: boolean;
5
+ caseSensitive: boolean;
6
+ };
7
+ /** A declared Markdown projection scans the complete document, including fenced text for literal counts. */
8
+ export declare function markdownPageFacts(raw: unknown, literal?: string, headingLevel?: number): {
9
+ heading: string | null;
10
+ literal?: string | undefined;
11
+ count?: number | undefined;
12
+ };
13
+ /** Bind only a submitted document URL. Never substitute a provider-reported redirect. */
14
+ export declare function requestedPageUrl(args: Record<string, unknown>): string | undefined;
15
+ export declare function isPageResult(raw: unknown): raw is string | Record<string, unknown>;
16
+ /** Build a bounded, explicitly partial view. All routing inputs stay in the host. */
17
+ export declare function prepareAdaptiveRead(question: string): (raw: unknown, fallbackSize?: number, requestedUrl?: string) => {
18
+ readonly native: false;
19
+ readonly selection: {
20
+ headings?: {
21
+ syntax: string;
22
+ coverage?: string | undefined;
23
+ level: number;
24
+ count: number;
25
+ complete: boolean;
26
+ first?: string | null | undefined;
27
+ last?: string | null | undefined;
28
+ } | undefined;
29
+ occurrences?: {
30
+ literal: string;
31
+ count: number;
32
+ complete: boolean;
33
+ caseSensitive: boolean;
34
+ } | undefined;
35
+ heading?: string | undefined;
36
+ metadata?: {
37
+ [k: string]: unknown;
38
+ } | undefined;
39
+ };
40
+ readonly headingEvidence?: string | undefined;
41
+ readonly value?: undefined;
42
+ } | {
43
+ readonly native: true;
44
+ readonly value: unknown;
45
+ readonly selection?: undefined;
46
+ } | {
47
+ readonly value?: undefined;
48
+ readonly native: false;
49
+ readonly selection: unknown;
50
+ };