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
@@ -0,0 +1,259 @@
1
+ # Rules, regression tests and mock callers
2
+
3
+ Available since **0.0.2**. These APIs are available in full JS, standalone JS core and native Python. They require no agent framework, provider connection or Cloudflare service.
4
+
5
+ ## First test
6
+
7
+ With the package installed in your application:
8
+
9
+ ```sh
10
+ npx toolsplice init ./handoff
11
+ npx toolsplice test ./handoff
12
+ npx toolsplice test ./handoff --json
13
+ npx toolsplice test ./handoff --junit results.xml
14
+ ```
15
+
16
+ From this source checkout, build first and replace `npx toolsplice` with `node dist/cli.js`. Python uses `python -m toolsplice` for the same commands. The two starter tests expect a valid mapping to succeed and invalid source data to stop before the destination call. Passing both is the intended result.
17
+
18
+ `test` accepts a suite filename or a project directory (reads `tests.json`). The CLI resolves `plan`, `sourceContract` and `targetContract` filenames relative to the suite; references must stay inside that directory, including resolved symlinks. Inline JSON artifacts are also accepted. The library API accepts inline artifacts only. Current file contents are loaded on every run.
19
+
20
+ Exit 0: every case matched. Exit 2: one or more expectations failed. Exit 1: invalid artifacts/configuration, including a contract without the selected tool. Reports include case names, call counts, fingerprints and issue codes/paths; they omit arguments and result payloads. JUnit output creates a new 0600 file and refuses overwrites. `project` separately checks generated adapter freshness.
21
+
22
+ ## Start from two real tools
23
+
24
+ Save the two MCP `tools/list` responses as JSON. To see which tools they contain, run:
25
+
26
+ ```sh
27
+ toolsplice init ./handoff --source-catalog firecrawl.json --target-catalog filesystem.json
28
+ ```
29
+
30
+ Choose an identity and tool for each endpoint. Add a sample to see its JSON pointers and the destination's top-level required fields. Both previews leave the project directory uncreated. Add explicit bindings to create it:
31
+
32
+ ```sh
33
+ toolsplice init ./handoff \
34
+ --source-catalog firecrawl.json --source firecrawl:firecrawl_scrape \
35
+ --target-catalog filesystem.json --target filesystem:write_file \
36
+ --fixture scrape-result.json --fixture-format mcp \
37
+ --bind '/content=/markdown' --set '/path="saved.md"'
38
+ toolsplice test ./handoff
39
+ ```
40
+
41
+ Use `--fixture-format mcp` for a raw tool response. The default expects the decoded JSON value. Repeat `--bind '/destination=/source'` for fields or `--set '/destination=<JSON literal>'` for constants. Supply `--input input.json` to also validate saved source request arguments during the project check.
42
+
43
+ Review the expected arguments in `tests.json` against what the downstream tool should receive. The initializer derives this first expectation from your chosen bindings. Subsequent runs compare against it, using the current `plan.json`, contracts and `fixture.json`. This mapping-only test makes zero source and destination calls. A target response belongs in a separate execution test. Generated projects and tests can contain private sample data.
44
+
45
+ ## Turn a failed run into a test
46
+
47
+ ```sh
48
+ toolsplice test --from-recording failed.json --save-case regression.json
49
+ toolsplice test regression.json
50
+ ```
51
+
52
+ The first command verifies the original replay and runs the generated suite before writing a new private file. A reproduced failure reports its stage, the first recorded issue code and path when available, and the destination call count. The suite pins those expectations and exact recorded destination arguments. Correcting the underlying bug can intentionally turn this expected-failure test red; update the expectation when you adopt the fix. Omit `--save-case` to check reproduction without exporting.
53
+
54
+ Use a complete payload recording. Redacted captures require `--restorations private-values.json`, and the exported suite contains the restored values. A mismatch exits 2. If the source or last destination call threw, the suite reproduces that exception and checks how many calls were attempted and how many results were collected. Cancellation timing and incomplete captures cannot be exported. Choose a new path for the output file.
55
+
56
+ For the JS SDK, call `inspectCatalogMapping(config)` or `await initializeSpliceProject(dir, {catalogs: config})`. The Python equivalents are `inspect_catalog_mapping(config)` and `await initialize_splice_project(dir, catalogs=config)`. Both accept the same JSON configuration:
57
+
58
+ ```js
59
+ const config = {
60
+ source: {server: 'firecrawl', tool: 'firecrawl_scrape'},
61
+ target: {server: 'filesystem', tool: 'write_file'},
62
+ sourceCatalog, targetCatalog, fixture, fixtureFormat: 'mcp',
63
+ bindings: [{to: '/content', from: '/markdown'}, {to: '/path', value: 'saved.md'}],
64
+ };
65
+ ```
66
+
67
+ A `mappingOnly: true` case supplies an empty `input`, a successful raw `sourceResult`, and an expectation with `status: "succeeded"`, `targetCalls: 0`, and exact `arguments`. The CLI also accepts a local decoded `sourceFixture` filename in place of `sourceResult` for these cases. Both CLIs can run each other's mapping and execution suites. The map-only pass covers saved source output and all generated arguments. A call to the generated adapter still applies its normal runtime review and input guards.
68
+
69
+ ## Application rules
70
+
71
+ Schemas establish shape and types. Rules compare values across the handoff. Add this to the plan or inline `defineSplice` / `define_splice` definition:
72
+
73
+ ```json
74
+ {
75
+ "contextSchema": {
76
+ "type": "object",
77
+ "properties": {
78
+ "tenant": { "type": "string" },
79
+ "approvedIds": { "type": "array", "items": { "type": "string" } },
80
+ "maxAmount": { "type": "number" }
81
+ },
82
+ "required": ["tenant", "approvedIds", "maxAmount"]
83
+ },
84
+ "rules": [
85
+ { "id": "same-tenant", "left": { "source": "/tenant" }, "op": "equals", "right": { "context": "/tenant" } },
86
+ { "id": "approved-id", "left": { "mapped": "/id" }, "op": "in", "right": { "context": "/approvedIds" } },
87
+ { "id": "within-limit", "left": { "row": "/amount" }, "op": "lte", "right": { "context": "/maxAmount" } }
88
+ ]
89
+ }
90
+ ```
91
+
92
+ Each operand has exactly one key:
93
+
94
+ | Operand | Value selected |
95
+ |---|---|
96
+ | `source` | Whole decoded source output, before selection or parsing |
97
+ | `row` | Selected/parsed value; an individual item with `forEach` |
98
+ | `mapped` | Completed destination argument object |
99
+ | `context` | Per-invocation application context; requires `contextSchema` |
100
+ | `value` | Literal JSON value |
101
+
102
+ References use JSON pointers. `""` selects the entire value. `equals` compares JSON deeply, ignoring object key order. `in` checks deep membership in the right-hand array. `lte` and `gte` compare numbers. There is no coercion: `false`, `0` and `"0"` differ. A missing field rejects; it is distinct from null.
103
+
104
+ Rules run after source/selected-value and mapped-argument validation, for every row, before **any destination call**. A bad later row therefore prevents all destination dispatch. An empty batch makes no destination calls and runs no per-row rules; use `source.expect` for whole-response flags or `source.valueSchema` with `minItems` when an empty batch should reject.
105
+
106
+ Rule plans have preflight status `review` unless another issue blocks them. Inspect `handoff.report` and pass `allowReview: true` / `allow_review=True` explicitly. This does not disable runtime checks. Rules are application-specified conditions, not authentication or proof of content accuracy. Supply trusted context from the application.
107
+
108
+ Failures use `rule-failed`, `rule-field-missing`, `rule-type-mismatch` or `rule-budget-exceeded`, with a path such as `/rows/1/rules/0`. `explainSpliceError` / `explain_error` adds `ruleId` without operand values. Generated adapters, direct execution, dry runs and replay use the same rules.
109
+
110
+ Limits: 1–32 rules with unique IDs matching `[A-Za-z][A-Za-z0-9_-]{0,63}`; references up to 32 segments; membership arrays up to 1,000 items; encoded operand pair up to 5 MiB; cumulative operand encoding up to 16 MiB per mapping. There are no expression strings, arbitrary callbacks or automatic corrective actions.
111
+
112
+ ## Define an editable suite
113
+
114
+ Starting with the `handoff` from the [JavaScript quickstart](../README.md):
115
+
116
+ ```js
117
+ import { runSpliceSuite } from 'toolsplice';
118
+
119
+ const suite = {
120
+ format: 'toolsplice-suite', formatVersion: 1,
121
+ plan: handoff.plan,
122
+ sourceContract: handoff.sourceContract,
123
+ targetContract: handoff.targetContract,
124
+ allowReview: true,
125
+ cases: [
126
+ {
127
+ name: 'saves the correct document', input: {}, context: { tenant: 'acme' },
128
+ sourceResult: { structuredContent: { tenant: 'acme', text: 'Hello' } },
129
+ targetResults: [{ structuredContent: true }],
130
+ expect: {
131
+ status: 'succeeded', targetCalls: 1,
132
+ arguments: [{ content: 'Hello' }], results: [true],
133
+ },
134
+ },
135
+ {
136
+ name: 'wrong tenant makes zero writes', input: {}, context: { tenant: 'acme' },
137
+ sourceResult: { structuredContent: { tenant: 'other', text: 'Hello' } },
138
+ expect: {
139
+ status: 'failed', stage: 'mapping', targetCalls: 0,
140
+ code: 'rule-failed', path: '/rows/0/rules/0',
141
+ },
142
+ },
143
+ ],
144
+ };
145
+ const report = await runSpliceSuite(suite);
146
+ if (report.failed) throw new Error('Handoff regression');
147
+ console.log(report.passed); // 2
148
+ ```
149
+
150
+ Use your ordinary test runner's assertion on `report.failed`. Python calls `await run_splice_suite(suite)` with the same JSON fields and checks `report["failed"] == 0`.
151
+
152
+ Every case needs a unique name, source input and expected status/target call count. Supply a raw source response unless the source call itself throws. Expected failure also needs a stage. Optional `code` and `path` narrow the failure assertion. Optional `arguments` compares all destination argument objects, in order; `results` checks collected outputs on success. Prefer precise failure assertions so an unrelated error cannot satisfy the test.
153
+
154
+ `targetResults` supplies one raw MCP response per destination call that returns. For a thrown source call, set `transportFailure` to `source` and omit `sourceResult`. For a throw on the last destination call, set it to `target` and include only the earlier returned responses. For example, after one success followed by a disconnect, use `expect.targetCalls: 2`, `expect.completedTargets: 1`, and one entry in `targetResults`. The failing attempt may already have had side effects. `expect.sourceCalls` optionally pins the number of source attempts to 0 or 1. `sourceResult` and `targetResults` are MCP envelopes, not decoded values. Unexpected tool calls fail even if an exception would otherwise satisfy a failure expectation. All cases are parsed before running. Suites are bounded to 100 cases, 1,000 total expected destination calls and 5 MiB of JSON.
155
+
156
+ To check a changed contract:
157
+
158
+ ```js
159
+ const report = await runSpliceSuite(suite, { targetContract: candidate });
160
+ ```
161
+
162
+ ```sh
163
+ npx toolsplice test ./handoff --target-contract candidate.json --json
164
+ ```
165
+
166
+ A matching expected failure is a passing regression. This differs from replay's `upgrade.status`, which only establishes upgrade success from a previously successful capture. Neither verifies every possible provider response.
167
+
168
+ ## Start from a capture
169
+
170
+ ```js
171
+ import { suiteFromRecording, runSpliceSuite } from 'toolsplice';
172
+
173
+ const suite = suiteFromRecording(recording, { name: 'saved document' });
174
+ const report = await runSpliceSuite(suite);
175
+ ```
176
+
177
+ Python: `suite_from_recording(recording, name="saved document")`. This verifies the capture's structure/fingerprints and builds a case with exact saved destination arguments and outcome. Running the suite checks whether it still reproduces. Add negative cases for the assumptions important to your application.
178
+
179
+ Conversion needs complete payloads and explicit private `restorations` for redacted paths. A terminal transport exception becomes a generic mock exception. The fixture checks that execution reaches the failing call and preserves earlier call arguments and counts. Incomplete payloads and cancellation timing prevent conversion. Use [recording and replay](RECORDING-AND-CORRECTIONS.md) for capture details. Be deliberate about storing/sharing suites: they contain fixture payloads.
180
+
181
+ ## Test your application's own workflow
182
+
183
+ Replay reruns the saved Toolsplice handoff. To test your current application code, inject mock callers instead:
184
+
185
+ ```js
186
+ import { mockRecordedCalls } from 'toolsplice';
187
+
188
+ const mocks = mockRecordedCalls(recording);
189
+ await yourWorkflow({ source: mocks.source, target: mocks.target });
190
+ mocks.assertDone();
191
+ ```
192
+
193
+ Python: `mocks = mock_recorded_calls(recording)`, inject `mocks.source` / `mocks.target`, then `mocks.assert_done()`. These callers enforce the original cross-endpoint call order and exact arguments. They do not run your workflow for you. An added call, changed arguments or a missing call fails the test. Deliberately captured transport errors become generic mock exceptions; their original causes/timing are not reproduced.
194
+
195
+ For hand-authored tests:
196
+
197
+ ```js
198
+ import { createMockCaller } from 'toolsplice';
199
+
200
+ const read = createMockCaller([
201
+ { name: 'read', arguments: { id: 'a' }, result: { structuredContent: { text: 'Hello' } } },
202
+ { name: 'read', arguments: { id: 'b' }, throws: true },
203
+ ]);
204
+ // Inject read into the application under test; it consumes steps in order.
205
+ // After the workflow and its expected exception handling:
206
+ read.assertDone();
207
+ ```
208
+
209
+ Omit `arguments` to accept any JSON object; otherwise comparison is exact. `result` and `throws: true` are mutually exclusive. `delayMs` (0–1,000) enables cancellation tests, with AbortSignal in JS and normal asyncio cancellation in Python. Calls reserve their step at entry. Independent mocks do not enforce cross-caller order; use `mockRecordedCalls` when that matters.
210
+
211
+ `getCalls()` / `get_calls()` returns detached attempts; `stats()` reports attempts, consumed, remaining and mismatch. `assertDone()` / `assert_done()` rejects unused steps and remains failed after a mismatch even if your application swallowed its exception. Inputs/results and retained calls are bounded; at most 1,000 scripted steps and 5 MiB of retained call JSON. Mocks cannot establish real provider effects, realistic concurrent scheduling or timing equivalence.
212
+
213
+ ## Check an upgrade against a known baseline
214
+
215
+ Run the saved suite against its original contracts and responses first. Then supply a new raw MCP response, a candidate contract, or both. A one-case suite needs no case selector.
216
+
217
+ ```sh
218
+ toolsplice impact ./handoff --candidate-result fresh-scrape.json
219
+ toolsplice impact ./handoff --source-contract next-source.json --target-contract next-target.json --json
220
+ toolsplice impact ./handoff --case "saves the correct document" --candidate-result fresh-scrape.json
221
+ ```
222
+
223
+ Both runs use local fixtures. Fetch the new response separately using the same source arguments if the goal is to compare provider versions. A changed page can legitimately change the expected destination text.
224
+
225
+ | Status | Interpretation |
226
+ |---|---|
227
+ | `fixtures-pass` | The original and candidate runs satisfy the saved expectations, including at least one expected success. |
228
+ | `regression` | The baseline passes, then a candidate assertion fails or a selected tool is absent from a catalog snapshot marked complete. |
229
+ | `baseline-failed` | The original expectations already fail. The candidate has not been evaluated. |
230
+ | `inconclusive` | Only expected failures were available, a supplied response never reached the handoff, or the selected tool is outside a partial snapshot. |
231
+
232
+ The CLI exits 0 for `fixtures-pass`, 2 for the other verdicts and 1 for invalid input. The report gives case counts, the exact names of the substituted samples, the two test reports and their fingerprints. A mapping-only case checks the source response against the destination arguments. Execution cases also exercise the saved source inputs and mock destination responses. Unused candidate responses appear under `unexercisedSourceResults`.
233
+
234
+ The SDK accepts multiple source responses keyed by case name. Use `await assessSpliceImpact(suite, {sourceResults: {"my case": rawMcpResult}})` in JavaScript or `await assess_splice_impact(suite, source_results={"my case": raw_mcp_result})` in Python. Each response uses the raw MCP envelope. The runner detaches the suite and replacement data.
235
+
236
+ Both `test` and `impact` report the first exact argument or result mismatch in `actual.difference`. The JSON pointer starts at the array of mapped arguments or results, so `/0/content` means the first row's content. An argument mismatch also names the contributing bindings, including their source or context pointers. Reports include field names, difference kinds and mismatched array lengths. Fixture values stay out of the report.
237
+
238
+ ## Return a selected destination field
239
+
240
+ Set `target.resultPath` in the plan when the caller only needs one field from each destination response. For example, a handoff that scrapes a page and returns its canonical URL can use the following destination.
241
+
242
+ ```json
243
+ {"server":"firecrawl","tool":"firecrawl_scrape","resultPath":"/metadata/sourceURL"}
244
+ ```
245
+
246
+ Both SDKs validate the full destination response, then select the field using an RFC 6901 JSON pointer. The returned array contains one selected value per completed destination call. A present JSON null is a valid value. A missing field fails at stage `target` with `target-result-field-missing` and its row path. That destination invocation has already occurred. Later rows are skipped. `maxResultBytes` measures the serialized returned array. Source and destination payload guards still apply to the full responses.
247
+
248
+ For catalog setup, add `--result-path '/metadata/sourceURL'` to the `init` command. A saved mapping-only case exercises destination arguments. Use a captured execution case to pin the final response as well. Generated adapters expose the selected return type where the contract describes it.
249
+
250
+ For several fields, use a map of output names to JSON pointers. This Firecrawl example returns a citation from the scrape metadata.
251
+
252
+ ```json
253
+ {"server":"firecrawl","tool":"firecrawl_scrape","resultFields":{"title":"/metadata/ogTitle","url":"/metadata/sourceURL","revision":"/metadata/git_commit_id"}}
254
+ ```
255
+
256
+ The JS and Python CLIs accept the same map with `--result-fields '{"title":"/metadata/ogTitle","url":"/metadata/sourceURL","revision":"/metadata/git_commit_id"}'`. Use either `resultFields` or `resultPath`. Each alias is required in the returned object. A selected JSON null is preserved. A missing field fails the handoff with its original pointer. The result byte limit includes the names and values in the returned object.
257
+
258
+
259
+ A regression case created from a successful recording now includes `expect.resultFingerprint` when the recording contains one. It compares the returned JSON array with the saved SHA-256 fingerprint. This lets CI catch changes to returned values without duplicating the complete result in the expectation. For editable values and a field-level mismatch, use `expect.results`. Choose one of these two assertions per case. Payload-mode recordings still capture the raw tool responses.
@@ -0,0 +1,11 @@
1
+ // Run from an application that has @modelcontextprotocol/ext-apps and esbuild installed.
2
+ import {build} from "esbuild";
3
+ import {writeFile} from "node:fs/promises";
4
+ import {fileURLToPath} from "node:url";
5
+ const output = process.argv[2];
6
+ if (!output) throw new Error("Pass a new output HTML filename.");
7
+ const entry = fileURLToPath(new URL("./view.mjs", import.meta.url));
8
+ const result = await build({entryPoints:[entry],bundle:true,format:"esm",platform:"browser",write:false,minify:true});
9
+ const script = result.outputFiles[0].text.replace(/<\/script/gi, "<\\/script");
10
+ const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Handoff results</title></head><body><output aria-live="polite">Waiting for results…</output><script type="module">${script}</script></body></html>`;
11
+ await writeFile(output, html, {flag:"wx", mode:0o600});
@@ -0,0 +1,22 @@
1
+ // Bundle with @modelcontextprotocol/ext-apps and serve as the HTML of a ui:// resource.
2
+ import { App } from "@modelcontextprotocol/ext-apps";
3
+
4
+ const app = new App({ name: "Toolsplice results", version: "1.0.0" }, {});
5
+ const output = document.querySelector("output");
6
+ app.ontoolresult = (reply) => {
7
+ const results = reply.structuredContent?.results;
8
+ if (reply.isError || !Array.isArray(results)) {
9
+ output.textContent = "The handoff could not return results.";
10
+ return;
11
+ }
12
+ const list = document.createElement("ol");
13
+ for (const item of results) {
14
+ const row = document.createElement("li");
15
+ row.textContent = typeof item === "string" ? item : JSON.stringify(item);
16
+ list.append(row);
17
+ }
18
+ if (results.length) output.replaceChildren(list);
19
+ else output.textContent = "No results.";
20
+ };
21
+ app.onteardown = async () => ({});
22
+ await app.connect();
@@ -0,0 +1,43 @@
1
+ import { defineSplice, createMockCaller } from 'toolsplice';
2
+
3
+ const handoff = defineSplice({
4
+ source: {
5
+ server: 'documents', tool: 'read',
6
+ inputSchema: { type: 'object' },
7
+ outputSchema: {
8
+ type: 'object',
9
+ properties: { tenant: { type: 'string' }, text: { type: 'string' } },
10
+ required: ['tenant', 'text'],
11
+ },
12
+ },
13
+ target: {
14
+ server: 'files', tool: 'save',
15
+ inputSchema: {
16
+ type: 'object', properties: { content: { type: 'string' } },
17
+ required: ['content'],
18
+ },
19
+ outputSchema: { type: 'boolean' },
20
+ },
21
+ bindings: [{ to: '/content', from: '/text' }],
22
+ contextSchema: {
23
+ type: 'object', properties: { tenant: { type: 'string' } }, required: ['tenant'],
24
+ },
25
+ rules: [{
26
+ id: 'same-tenant', left: { source: '/tenant' },
27
+ op: 'equals', right: { context: '/tenant' },
28
+ }],
29
+ });
30
+
31
+ const read = createMockCaller([{
32
+ name: 'read', result: { structuredContent: { tenant: 'acme', text: 'Hello' } },
33
+ }]);
34
+ const save = createMockCaller([{
35
+ name: 'save', arguments: { content: 'Hello' }, result: { structuredContent: true },
36
+ }]);
37
+
38
+ const result = await handoff.run(read, save, {}, {
39
+ context: { tenant: 'acme' }, allowReview: true,
40
+ });
41
+ read.assertDone();
42
+ save.assertDone();
43
+ console.log(result); // [true]
@@ -0,0 +1,67 @@
1
+ import { searchThenFetch } from "toolsplice";
2
+
3
+ // Replace these two reads with your application's read-only tools.
4
+ const pages = { a: "alpha alpha", b: "beta", c: "alpha", d: "beta beta" };
5
+ const origin = "https://pages.test";
6
+ const search = {
7
+ definition: {
8
+ name: "search",
9
+ inputSchema: {
10
+ type: "object",
11
+ properties: { id: { type: "string" } },
12
+ required: ["id"],
13
+ additionalProperties: false,
14
+ },
15
+ },
16
+ async execute({ id }) {
17
+ return { results: [{ contentUrl: origin + "/" + id }] };
18
+ },
19
+ };
20
+ const fetchPage = {
21
+ definition: {
22
+ name: "fetch",
23
+ inputSchema: {
24
+ type: "object",
25
+ properties: { url: { type: "string" } },
26
+ required: ["url"],
27
+ },
28
+ },
29
+ async execute({ url }) {
30
+ return pages[new URL(url).pathname.slice(1)];
31
+ },
32
+ };
33
+ const combined = searchThenFetch(search, fetchPage, {
34
+ origins: [origin],
35
+ pageView: "markdown",
36
+ });
37
+
38
+ export default {
39
+ context: "local-pages/v1",
40
+ routes: ["native", "configured"],
41
+ cases: Object.keys(pages).map((id, i) => ({
42
+ id,
43
+ workload: "page-count",
44
+ split: i < 2 ? "fit" : "holdout",
45
+ input: { id, literal: i % 2 ? "beta" : "alpha" },
46
+ expected: [2, 1, 1, 2][i],
47
+ })),
48
+ // For an agent, call your actual agent here and return its measured usage.
49
+ async run(route, { input }) {
50
+ let count;
51
+ if (route === "configured") {
52
+ const result = await combined.execute({
53
+ id: input.id,
54
+ countLiteral: input.literal,
55
+ });
56
+ count = result.count;
57
+ } else {
58
+ const { results } = await search.execute({ id: input.id });
59
+ const text = await fetchPage.execute({ url: results[0].contentUrl });
60
+ count = text.split(input.literal).length - 1;
61
+ }
62
+ return { answer: count, modelCalls: 0, costUsd: 0 };
63
+ },
64
+ grade(item, answer) {
65
+ return answer === item.expected;
66
+ },
67
+ };
@@ -0,0 +1,36 @@
1
+ import type { Tool } from "ai";
2
+ import type { RunDiagnostics, SpliceRunOptions } from "../dist/core.js";
3
+ import type { ExecutableTool } from "./types.mjs";
4
+
5
+ export declare function aiTools<Result>(
6
+ workflow: ExecutableTool<Result>,
7
+ options?: SpliceRunOptions,
8
+ ): Record<string, Tool<Record<string, unknown>, Result>>;
9
+
10
+ import type { ToolSet } from "ai";
11
+ import type { ResultTool } from "../dist/core.js";
12
+
13
+ /** Consume streaming results before the callback finishes. */
14
+ export declare function withAiTools<T extends ToolSet, R>(
15
+ existing: T,
16
+ question: string,
17
+ use: (tools: T & ToolSet, activeTools: () => string[]) => R,
18
+ options?: { enabled?: boolean; diagnostics?: RunDiagnostics },
19
+ ): Promise<Awaited<R>>;
20
+ export declare function withAiTools<R>(
21
+ existing: readonly ResultTool[],
22
+ question: string,
23
+ use: (tools: ToolSet, activeTools: () => string[]) => R,
24
+ options?: { enabled?: boolean; diagnostics?: RunDiagnostics },
25
+ ): Promise<Awaited<R>>;
26
+
27
+ /** Yield a stream from the callback and keep its tools live until consumption ends. */
28
+ export declare function streamAiTools<T>(
29
+ existing: ToolSet | readonly ResultTool[],
30
+ question: string,
31
+ use: (
32
+ tools: ToolSet,
33
+ activeTools: () => string[],
34
+ ) => AsyncIterable<T> | PromiseLike<AsyncIterable<T>>,
35
+ options?: { enabled?: boolean; diagnostics?: RunDiagnostics },
36
+ ): AsyncGenerator<T>;
@@ -0,0 +1,178 @@
1
+ import { createHash } from "node:crypto";
2
+ import { jsonSchema, tool } from "ai";
3
+ import {
4
+ managedTools,
5
+ activeTools,
6
+ checkNames,
7
+ visibleContent,
8
+ withRun,
9
+ streamRun,
10
+ } from "./managed.mjs";
11
+ import { callOptions } from "./call-options.mjs";
12
+
13
+ /** Register one checked workflow under its existing name in a Vercel AI SDK tool set. */
14
+ export function aiTools(workflow, options = {}) {
15
+ const { name, description, inputSchema } = workflow.definition;
16
+ return {
17
+ [name]: tool({
18
+ description,
19
+ inputSchema: jsonSchema(inputSchema),
20
+ execute: (input, { abortSignal }) =>
21
+ workflow.execute(input, callOptions(options, abortSignal)),
22
+ }),
23
+ };
24
+ }
25
+
26
+ /** Run a Vercel agent with its existing tool set and a private result scope. */
27
+ export async function withAiTools(
28
+ existing,
29
+ question,
30
+ use,
31
+ { enabled = true, diagnostics } = {},
32
+ ) {
33
+ if (diagnostics) return diagnostics.run(enabled ? "adaptive" : "native", () => withAiTools(existing, question, use, {enabled}));
34
+ if (!enabled) {
35
+ const native = nativeTools(existing);
36
+ return use(native, () => activeTools(native, true));
37
+ }
38
+ return withRun(question, buildTools(existing, question), use);
39
+ }
40
+
41
+ /** Stream a run and release retained results on completion, failure or early return. */
42
+ export async function* streamAiTools(
43
+ existing,
44
+ question,
45
+ use,
46
+ { enabled = true, diagnostics } = {},
47
+ ) {
48
+ if (diagnostics) {
49
+ yield* diagnostics.stream(enabled ? "adaptive" : "native", () => streamAiTools(existing, question, use, {enabled}));
50
+ return;
51
+ }
52
+ if (!enabled) {
53
+ const native = nativeTools(existing);
54
+ yield* await use(native, () => activeTools(native, true));
55
+ return;
56
+ }
57
+ yield* streamRun(question, buildTools(existing, question), use);
58
+ }
59
+
60
+ function nativeTools(existing) {
61
+ if (!Array.isArray(existing)) return existing;
62
+ checkNames(existing.map((t) => t.definition.name));
63
+ return Object.fromEntries(
64
+ existing.flatMap((t) => Object.entries(aiTools(t))),
65
+ );
66
+ }
67
+
68
+ function buildTools(existing, question) {
69
+ return (session, begin, cleanup) => {
70
+ const sources = Array.isArray(existing) ? existing : [];
71
+ const entries = [];
72
+ if (!Array.isArray(existing)) {
73
+ for (const [name, native] of Object.entries(existing)) {
74
+ entries.push([name, wrapNative(name, native, begin, cleanup)]);
75
+ }
76
+ }
77
+ for (const source of managedTools(session, sources, question)) {
78
+ entries.push(...Object.entries(aiTools(source)));
79
+ }
80
+ checkNames(entries.map(([name]) => name));
81
+ return Object.fromEntries(entries);
82
+ };
83
+ }
84
+
85
+ function defaultOutput(raw) {
86
+ if (typeof raw === "string") return { type: "text", value: raw };
87
+ const json = JSON.stringify(raw);
88
+ return { type: "json", value: json === undefined ? null : JSON.parse(json) };
89
+ }
90
+
91
+ function wrapNative(name, native, begin, cleanup) {
92
+ if (
93
+ native.type === "provider" ||
94
+ native.type === "provider-defined" ||
95
+ !native.execute
96
+ )
97
+ return native;
98
+ // Vercel can serialize the same tool result again when rebuilding message history.
99
+ // Keep the submitted URL and reuse a view only when the model-visible content agrees.
100
+ const calls = new Map();
101
+ let submittedInputs = new WeakMap();
102
+ cleanup.push(() => {
103
+ calls.clear();
104
+ submittedInputs = new WeakMap();
105
+ });
106
+ return {
107
+ ...native,
108
+ execute(input, options) {
109
+ const present = begin(name, input ?? {});
110
+ const id = options?.toolCallId;
111
+ if (id) {
112
+ if (calls.size === 32) calls.delete(calls.keys().next().value);
113
+ calls.set(id, { present });
114
+ if (input && typeof input === "object")
115
+ submittedInputs.set(input, { id, present });
116
+ }
117
+ return native.execute(input, options);
118
+ },
119
+ async toModelOutput(options) {
120
+ const call = calls.get(options.toolCallId);
121
+ const original = submittedInputs.get(options.input);
122
+ // A reconstructed input may already contain a redirect. Only attach a submitted
123
+ // URL to an identified call when we still have its dispatch snapshot.
124
+ const fallback = begin(
125
+ name,
126
+ options.toolCallId ? {} : (options.input ?? {}),
127
+ );
128
+ const present =
129
+ call?.present ??
130
+ (original && original.id === options.toolCallId
131
+ ? original.present
132
+ : fallback);
133
+ const output = native.toModelOutput
134
+ ? await native.toModelOutput(options)
135
+ : defaultOutput(options.output);
136
+ if (
137
+ options.output?.isError === true ||
138
+ (output.type === "json" && output.value?.isError === true) ||
139
+ !["text", "json", "content"].includes(output.type)
140
+ )
141
+ return output;
142
+ if (
143
+ output.type === "content" &&
144
+ output.value.some((p) => p.type !== "text")
145
+ )
146
+ return output;
147
+ const serialized = call && JSON.stringify(output.value);
148
+ const hash =
149
+ serialized?.length > 1024
150
+ ? createHash("sha256").update(serialized).digest("hex")
151
+ : undefined;
152
+ let value;
153
+ if (hash && call.hash === hash && call.type === output.type) {
154
+ value = structuredClone(call.view);
155
+ } else {
156
+ value =
157
+ output.type === "content"
158
+ ? visibleContent(output.value, present)
159
+ : present(output.value);
160
+ if (hash && JSON.stringify(value).length <= 8192) {
161
+ Object.assign(call, {
162
+ hash,
163
+ type: output.type,
164
+ view: structuredClone(value),
165
+ });
166
+ }
167
+ }
168
+ return {
169
+ ...output,
170
+ type:
171
+ output.type === "text" && typeof value !== "string"
172
+ ? "json"
173
+ : output.type,
174
+ value,
175
+ };
176
+ },
177
+ };
178
+ }
@@ -0,0 +1,9 @@
1
+ // Model arguments and application-owned run options use separate paths.
2
+ export function callOptions(options, frameworkSignal) {
3
+ if (!frameworkSignal) return options;
4
+ const signal =
5
+ options.signal && options.signal !== frameworkSignal
6
+ ? AbortSignal.any([options.signal, frameworkSignal])
7
+ : frameworkSignal;
8
+ return { ...options, signal };
9
+ }
@@ -0,0 +1,31 @@
1
+ import type { StructuredToolInterface } from "@langchain/core/tools";
2
+ import type { RunDiagnostics, SpliceRunOptions } from "../dist/core.js";
3
+ import type { ExecutableTool } from "./types.mjs";
4
+
5
+ export declare function asLangChainTool<Result>(
6
+ workflow: ExecutableTool<Result>,
7
+ options?: SpliceRunOptions & { returnDirect?: boolean },
8
+ ): StructuredToolInterface;
9
+
10
+ import type { ResultTool } from "../dist/core.js";
11
+
12
+ /** Consume streaming results before the callback finishes. */
13
+ export declare function withLangChainTools<R>(
14
+ existing: readonly (ResultTool | StructuredToolInterface)[],
15
+ question: string,
16
+ use: (
17
+ tools: StructuredToolInterface[],
18
+ activeTools: () => StructuredToolInterface[],
19
+ ) => R,
20
+ options?: { enabled?: boolean; diagnostics?: RunDiagnostics },
21
+ ): Promise<Awaited<R>>;
22
+
23
+ export declare function streamLangChainTools<T>(
24
+ existing: readonly (ResultTool | StructuredToolInterface)[],
25
+ question: string,
26
+ use: (
27
+ tools: StructuredToolInterface[],
28
+ activeTools: () => StructuredToolInterface[],
29
+ ) => AsyncIterable<T> | PromiseLike<AsyncIterable<T>>,
30
+ options?: { enabled?: boolean; diagnostics?: RunDiagnostics },
31
+ ): AsyncGenerator<T>;