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,173 @@
1
+ # Projects, candidate-contract checks and the standalone core
2
+
3
+ Initially added in the v0.9 preview, these features are included in the public 0.0.1 release. Toolsplice provides offline setup and upgrade checks, plus an independently installable core package. No Cloudflare service/account is required. These changes do not add durable workflow resumption, automatic retries or provider authentication/discovery.
4
+
5
+ ## Start a project
6
+
7
+ ```sh
8
+ toolsplice init ./my-handoff
9
+ toolsplice test ./my-handoff
10
+ toolsplice project ./my-handoff --allow-review --json
11
+ ```
12
+
13
+ For a source checkout, build first and replace `toolsplice` with `node /absolute/path/to/mcp-shape/dist/cli.js`. A developer already running the CLI can check the generated project without installing a second package or configuring a provider account.
14
+
15
+ The new private directory contains:
16
+
17
+ | File | Purpose |
18
+ |---|---|
19
+ | `toolsplice.project.json` | Fixed-file project format, fixture encoding and origin |
20
+ | `plan.json` | Explicit source → destination bindings |
21
+ | `source.json`, `target.json` | Portable contract snapshots |
22
+ | `input.json` | Saved source arguments |
23
+ | `fixture.json` | Saved decoded or raw MCP source result |
24
+ | `context.json` | Per-call values, when declared/present |
25
+ | `tests.json` | Added in 0.0.2: regression cases referencing the current plan and contracts |
26
+ | `adapter.ts` | Generated typed adapter, using the full package |
27
+ | `README.md` | Check, regeneration and application instructions |
28
+
29
+ The default is a **synthetic** document → artifact handoff. It checks locally; it fetches no URL, writes no destination document and creates no clients or learning store. Applications provide actual tool callers and explicitly replace the contracts/mapping. Field names are not matched heuristically. The initializer does not run npm or install dependencies.
30
+
31
+ `project` checks source input, context, saved source output, selected-value requirements and every mapped destination argument. It also compares `adapter.ts` with the current plan/contracts/generator. A stale generated adapter blocks the check. It never overwrites that file. Regenerate into a new path with the command in the project's README, review the result and replace the generated adapter deliberately. Formatting/customizing a generated file can also trigger this conservative freshness check.
32
+
33
+ The check reports counts, paths and issues, omitting mapped values. `--allow-review` changes the exit policy for review status; blocked projects still fail, and runtime guards remain active. It does not authorize or perform live effects.
34
+
35
+ Project contents are prepared and checked before creating the directory. Existing directories are refused without modification. The directory uses mode 0700 and new files mode 0600. An I/O failure while writing can leave a partial new directory for inspection; filesystem creation is not claimed to be a transaction. The project format reads fixed artifact filenames and does not allow arbitrary path references in its manifest.
36
+
37
+ `test` (0.0.2+) checks expected outcomes, call counts and optionally exact arguments/results. It reads current plan/contracts but does not check generated adapter freshness; use `project` for that. See [rules, tests and mocks](TESTING.md).
38
+
39
+ ## Start from a successful recording
40
+
41
+ ```sh
42
+ toolsplice init ./existing-handoff --from-recording recording.json --json
43
+ ```
44
+
45
+ The recording must be a complete payload capture that reproduces a successful outcome under offline replay. Metadata-only, incomplete, failed, unrestored or mismatching recordings are rejected before creating the directory. The initializer copies the exact mapping/contracts and raw source response; it does not contact the original servers. It retains `recording.json` so that full response replay and upgrade checks remain available.
46
+
47
+ For a redacted recording:
48
+
49
+ ```sh
50
+ toolsplice init ./private-handoff --from-recording recording.json \
51
+ --restorations private-values.json --json
52
+ ```
53
+
54
+ Every redacted path requires an explicit restoration. **Restored input/context/source fixtures are copied into the new private project and may contain confidential values.** The retained `recording.json` is the original redacted artifact; private restoration policies/values are not inserted into that retained recording. Its replay still needs the private restoration file. Do not share a generated project merely because its original recording was redacted.
55
+
56
+ API equivalents are `createSpliceProjectFiles`, `initializeSpliceProject`, `checkSpliceProjectFiles` and `checkSpliceProject` from the full package. The file builder does not perform filesystem writes. The standalone core focuses on execution/contracts and does not export project/CLI helpers.
57
+
58
+ ## Check candidate contracts against saved calls
59
+
60
+ ```ts
61
+ import { replaySpliceRecording } from 'toolsplice'; // Or toolsplice-core.
62
+ const report = await replaySpliceRecording(recording, {
63
+ sourceContract: candidateSource,
64
+ targetContract: candidateTarget,
65
+ allowReview: true, // Explicitly allow uncertain preflight checks when reviewed.
66
+ });
67
+ console.log(report.upgrade?.status, report.networkCalls);
68
+ ```
69
+
70
+ ```sh
71
+ toolsplice replay recording.json --target-contract candidate-target.json --json
72
+ toolsplice replay recording.json --source-contract candidate-source.json \
73
+ --target-contract candidate-target.json --allow-review --json
74
+ ```
75
+
76
+ Candidate snapshots must identify the same logical servers as the recording. Only the selected tools are compared; unrelated catalog additions do not create handoff drift. A missing selected tool is reported as a failing fixture check with a breaking diff. A different server identity or malformed snapshot is a configuration error.
77
+
78
+ Replay retains the original plan and exact saved call sequence. Candidate input requirements validate saved source arguments and mapped destination arguments; candidate outputs validate the saved source/destination responses. All saved arguments must still match. No actual servers/callers can be supplied. The returned `upgrade` includes source/target schema comparisons and both recorded/candidate fingerprints. The recording and candidate objects are detached and remain unchanged.
79
+
80
+ | `upgrade.status` | Meaning |
81
+ |---|---|
82
+ | `passed` | A previously successful captured case still matches under candidate contracts |
83
+ | `failed` | That successful captured case no longer matches, including new validation or preflight-policy failures |
84
+ | `inconclusive` | The original run failed, was cancelled or included a transport failure, so it cannot establish successful upgrade compatibility |
85
+
86
+ `matched` still describes agreement with the recorded outcome. A saved expected failure can have `matched: true` while an upgrade check remains inconclusive. CLI exit 0 requires a passed candidate check; failed or inconclusive candidate checks exit 2. Ordinary replay without candidates preserves the v0.8 behavior: a matching expected failure exits 0. Invalid/unrestored artifacts or configuration errors exit 1.
87
+
88
+ The recorded review policy is retained by default. `--allow-review` is an explicit override for reviewing new uncertainty; it never bypasses blocked plans or runtime validation. Reports omit result values and raw exception causes. CLI human-readable output includes the candidate status.
89
+
90
+ These results apply only to saved cases. Passing fixtures do not prove universal schema compatibility, semantic ID correctness, factual accuracy, live server behavior or committed side effects. Applications retrieve/update catalogs and create candidate snapshots explicitly; this command neither calls a provider nor discovers schema changes automatically.
91
+
92
+ ## Choose a dependency footprint
93
+
94
+ `toolsplice` retains the full existing API/CLI and optional PostgreSQL support. No existing public import or persisted store name is renamed.
95
+
96
+ `toolsplice-core` is a separate package with only **Ajv and re2js** as direct production dependencies. It exports contracts, validators, handoff preparation, adapter generation, recording/replay, field-origin diagnostics and reviewed corrections. The application supplies raw-result `ToolCaller` functions. It has no SDK convenience client, CLI, learning proxy or PostgreSQL export.
97
+
98
+ ```ts
99
+ import { prepareSplice, emitSpliceModule, type ToolCaller } from 'toolsplice-core';
100
+ const adapter = prepareSplice(plan, sourceContract, targetContract);
101
+ const result = await adapter.run(sourceCaller, targetCaller, input);
102
+ const code = emitSpliceModule(plan, sourceContract, targetContract);
103
+ // Generated code imports toolsplice-core by default.
104
+ ```
105
+
106
+ The full package's emitter continues to default to `toolsplice`. Both emitters allow an explicit `runtimeImport`. Core requires Node 22+ and includes Node filesystem/crypto support internally; browser or Worker compatibility is not claimed.
107
+
108
+ Install the CLI with `npm install toolsplice@0.0.2` or use `npm install toolsplice-core@0.0.2` when your application supplies its own callers.
109
+
110
+ The core build uses TypeScript's dependency file graph and rejects SDK/Zod/PostgreSQL dependencies. Clean-consumer verification independently installs the tarball, proves the SDK cannot resolve, compiles/runs a generated adapter and exercises capture/replay, candidate checks and corrections. Full-package consumers separately test the original SDK/CLI paths. File-size measurements count regular-file bytes and skip symlinks; filesystem allocation can differ. Verification evidence and exact sizes are recorded in `test-results/v09-final-validation.json` in this checkout.
111
+
112
+
113
+ ## Capture a complete catalog
114
+
115
+ `toolsplice catalog --url https://learn.microsoft.com/api/mcp --out learn.json` initializes the server connection, follows each `tools/list` cursor and writes a new private catalog file after the last page. Omit `--out` to receive compact JSON on stdout. For stdio, use `toolsplice catalog --out tools.json -- server-command arg`. For authenticated HTTP, pass the name of an application-owned environment variable with `--bearer-env NAME`. The capture has a 30-second overall deadline by default, configurable with `--timeout` in milliseconds.
116
+
117
+ Use the resulting files with `init --source-catalog ... --target-catalog ...` or check an existing suite with `impact ./handoff --target-catalog tools.json`. A raw catalog takes its server identity from the selected side of the handoff. Use a contract snapshot to check an embedded server identity. Saving the catalog invokes only MCP initialization and discovery. Duplicate tool names, repeated cursors, invalid schemas or a disconnected session fail capture. Existing destination files are preserved. The collector accepts up to 1,000 pages and 5 MiB of bounded JSON. A raw intermediate page with a `nextCursor` yields a subset snapshot when passed to the contract builder.
118
+
119
+ Existing applications can reuse an initialized client.
120
+
121
+ ```js
122
+ const catalog = await collectToolCatalog(cursor =>
123
+ client.listTools(cursor === undefined ? undefined : {cursor}));
124
+ ```
125
+
126
+ ```python
127
+ catalog = await collect_tool_catalog(
128
+ lambda cursor: session.list_tools(**({"cursor": cursor} if cursor is not None else {}))
129
+ )
130
+ ```
131
+
132
+ The application owns the callback's connection, credentials, timeout and cleanup.
133
+
134
+ ### Map every row in a catalog sample
135
+
136
+ Use `--each /results` when the source returns an object with an array at `/results`. Source pointers in `--bind` are relative to each row. Use `--each ''` for a root array. Omit the bindings to preview the union of row fields, row count, number of rows inspected and target-call limit.
137
+
138
+ ```sh
139
+ toolsplice init lookup-pages --source-catalog learn.json --source learn:microsoft_docs_search \
140
+ --target-catalog firecrawl.json --target firecrawl:firecrawl_scrape \
141
+ --fixture search-response.json --fixture-format mcp --each /results --max-items 10 \
142
+ --bind /url=/contentUrl --result-path /markdown
143
+ toolsplice test lookup-pages --json
144
+ ```
145
+
146
+ Review the pinned argument list in `tests.json`. Preview and generated mapping tests perform zero network calls. A live run can make one destination call per row. All rows must pass their guards before the first destination call. The default batch limit is 100 and the maximum is 1,000.
147
+
148
+
149
+ ### Select a result by its stable key
150
+
151
+ Search order can change between requests. A reviewed plan can select a single row by its ID or exact name. Prepare this plan once and supply the requested key as context on each call.
152
+
153
+ ```json
154
+ {
155
+ "source": {
156
+ "server": "parks",
157
+ "tool": "find_campgrounds",
158
+ "path": "/campgrounds",
159
+ "matchOne": { "path": "/name", "fromContext": "/site" }
160
+ },
161
+ "contextSchema": {
162
+ "type": "object",
163
+ "properties": { "site": { "type": "string" } },
164
+ "required": ["site"]
165
+ },
166
+ "maxItems": 100,
167
+ "bindings": [{ "to": "/lat", "from": "/latitude" }]
168
+ }
169
+ ```
170
+
171
+ The fragment shows the source and one binding. The normal plan also needs its format, version and target. Each binding reads from the matching array element. An `equals` literal can replace `fromContext`. Both forms compare JSON scalar values exactly. A missing candidate field does not match JSON null. The runtime checks the selected array's consumer schema first, then examines up to `maxItems` candidates (default 100, maximum 1,000). An oversized array, no match or a second match stops the handoff before it calls the destination. The report counts at most one destination call. A missing or nonscalar context key stops execution before it calls the source. Use `forEach` for plans that send every row.
172
+
173
+ The JavaScript and Python SDKs read the same plan. Call `mapOutput(result, { context: { site } })` in JavaScript or `map_output(result, context={"site": site})` in Python to check mappings offline.
@@ -0,0 +1,348 @@
1
+ # Python API guide
2
+
3
+ This guide covers checked handoffs, offline tests, recording and the Python CLI. [Install Toolsplice and connect your framework](PYTHON.md)
4
+
5
+ ## Mix MCP tools with your own functions
6
+
7
+ A local function can receive a remote result or build the arguments for the next MCP call. Here a document server returns `{"text": "..."}`, and a local Python function counts the words. The agent gets `{"results": [3]}` for a document containing “one two three”.
8
+
9
+ ```python
10
+ from toolsplice import define_local_tool, prepare_splice
11
+
12
+ count_words = define_local_tool(
13
+ {
14
+ "name": "count_words",
15
+ "inputSchema": {
16
+ "type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"],
17
+ },
18
+ "outputSchema": {"type": "integer", "minimum": 0},
19
+ "annotations": {"readOnlyHint": True},
20
+ },
21
+ lambda args: len(args["text"].split()),
22
+ )
23
+
24
+
25
+ def word_count_tool(read_caller, documents_contract):
26
+ plan = {
27
+ "format": "toolsplice-splice", "formatVersion": 1,
28
+ "source": {"server": "documents", "tool": "read"},
29
+ "target": {"server": "local", "tool": "count_words"},
30
+ "bindings": [{"from": "/text", "to": "/text"}],
31
+ }
32
+ handoff = prepare_splice(plan, documents_contract, count_words.contract)
33
+ return handoff.as_tool(name="document_word_count", source=read_caller, target=count_words.caller)
34
+ ```
35
+
36
+ Pass your connected read caller and its `create_contract_from_catalog` snapshot. Call `await tool.call({"id": "doc-42"})` or register the definition and handler in your agent framework. A local handler accepts one dictionary of arguments and returns JSON or an awaitable. Use an async handler for I/O. A synchronous handler runs on the caller's event loop. For local code that builds a remote query, pass its contract and caller on the source side.
37
+
38
+ For independent reads in a `forEach` plan, set `read_concurrency=3` on `as_tool` or call `await handoff.run_reads(source, target, args, concurrency=3)`. Values from 1 through 16 are supported. The default in `run_reads` is four. Results follow input order. The destination must declare `readOnlyHint: true` or the application must explicitly set `assume_read_only=True` on an unlabeled read. On a failed parallel wave, `completed_targets` counts the successful in-order prefix and `scheduled_targets` counts submitted rows. Use `run` for serial operations.
39
+
40
+ Use `recorder.run_reads(...)` with payload capture to save the read policy and outcomes in submission order. `replay_splice_recording` and `suite_from_recording` reproduce completed and failed reads offline in either SDK.
41
+
42
+ For paged text, `await collect_text_pages(read_page, max_pages=8, max_bytes=1048576)` calls the application reader with `None` on the first request. Return `{"text": chunk, "nextCursor": cursor}` for each remaining page, and omit the cursor on completion. UTF-8 byte and page limits, cursor cycles and reader failures terminate the read.
43
+
44
+ ### Use an existing agent
45
+
46
+ Import `as_agno_tool` from `toolsplice.integrations.agno` or `as_langchain_tool` from `toolsplice.integrations.langchain`. Each accepts the workflow returned by `prepared.as_tool(...)`. Install the matching optional extra if you need the framework dependency.
47
+
48
+ ```python
49
+ from agno.agent import Agent
50
+ from toolsplice.integrations.agno import as_agno_tool
51
+
52
+ agent = Agent(model=model, tools=[as_agno_tool(workflow)])
53
+ response = await agent.arun(question)
54
+ ```
55
+
56
+ For LangChain, use `create_agent(model=model, tools=[as_langchain_tool(workflow)])` and `await agent.ainvoke(...)`. Pass trusted run options such as `context` at registration. Other async framework handlers can call `await workflow.execute(arguments, **run_options)` to receive the selected results directly.
57
+
58
+
59
+ A remote result may contain scientific integers outside JavaScript’s safe range. Python accepts them when binary64 and its canonical JSON decimal spelling both preserve the exact integer. Supply large opaque identifiers as strings across runtimes.
60
+
61
+ ## Start from two real tools
62
+
63
+ Save the two MCP `tools/list` responses as JSON. To see which tools they contain, run:
64
+
65
+ ```sh
66
+ python -m toolsplice init ./handoff --source-catalog firecrawl.json --target-catalog filesystem.json
67
+ ```
68
+
69
+ 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:
70
+
71
+ ```sh
72
+ python -m toolsplice init ./handoff \
73
+ --source-catalog firecrawl.json --source firecrawl:firecrawl_scrape \
74
+ --target-catalog filesystem.json --target filesystem:write_file \
75
+ --fixture scrape-result.json --fixture-format mcp \
76
+ --bind '/content=/markdown' --set '/path="saved.md"'
77
+ python -m toolsplice test ./handoff
78
+ ```
79
+
80
+ 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.
81
+
82
+ 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.
83
+
84
+ ## Turn a failed run into a test
85
+
86
+ ```sh
87
+ python -m toolsplice test --from-recording failed.json --save-case regression.json
88
+ python -m toolsplice test regression.json
89
+ ```
90
+
91
+ 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.
92
+
93
+ 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.
94
+
95
+ For Python code, pass the same catalog data to `await initialize_splice_project(directory, catalogs=config)`. The config keys are `source`, `target`, `sourceCatalog`, `targetCatalog`, `fixture`, optional `fixtureFormat` and `input`, and `bindings` using standard plan objects. Use `inspect_catalog_mapping(config)` for a preview.
96
+
97
+ ## Rules, regression suites and mocks
98
+
99
+ A plan's `rules` contains named conditions: `{"id": "same-tenant", "left": {"source": "/tenant"}, "op": "equals", "right": {"context": "/tenant"}}`. Operands select `source` (whole decoded output), `row` (selected row), `mapped` (destination arguments), `context`, or literal `value`. Operators: `equals`, `in`, `lte`, `gte`. Comparisons are strict; missing fields reject. All rows and rules pass before any destination call. An empty batch makes no destination calls and runs no per-row rules.
100
+
101
+ ```python
102
+ from toolsplice import run_splice_suite, suite_from_recording, mock_recorded_calls
103
+
104
+ # Complete payload recording, plus explicit restorations if redacted.
105
+ suite = suite_from_recording(recording, name="saved document")
106
+ report = await run_splice_suite(suite)
107
+ assert report["failed"] == 0
108
+
109
+ # Feed captured responses into your own application's workflow.
110
+ mocks = mock_recorded_calls(recording)
111
+ await your_workflow(mocks.source, mocks.target)
112
+ mocks.assert_done()
113
+ ```
114
+
115
+ Suites use shared `toolsplice-suite` v1 JSON, including `plan`, `sourceContract`, `targetContract`, `allowReview` and `cases`. Each case includes `name`, `input`, optional `context`, raw `sourceResult`, optional `targetResults`, and `expect` with `status`/`targetCalls`. Failures also require `stage`; optional `code`/`path` check the issue precisely. Optional `arguments`/`results` assert exact values. All cases are parsed before execution; no live callers are accepted. The library takes inline artifacts; the CLI also resolves plan/contract filenames inside the suite directory.
116
+
117
+ `run_splice_suite(suite, target_contract=candidate)` checks a new contract. `format_test_junit(report)` integrates with any CI runner. Reports contain names, counts, fingerprints and issue paths, without returned payloads. Use ordinary pytest assertions; no plugin or agent framework is needed.
118
+
119
+ `create_mock_caller` accepts up to 1,000 ordered steps with `name`, optional exact `arguments`, and either raw `result` or `throws: True`. `delayMs` (0–1,000) supports cancellation tests; asyncio cancellation propagates. Call `assert_done()` to catch unused steps or mismatches your application swallowed. `get_calls()` returns detached attempts and `stats()` returns counts. Retained calls are capped at 5 MiB. Mocks test your orchestration, not live provider behavior, timing or side effects.
120
+
121
+ Rules: 1–32 unique IDs; pointers up to 32 segments; membership arrays up to 1,000 items; operand pair up to 5 MiB; cumulative operand encoding up to 16 MiB per mapping. Suites: 1–100 cases, at most 1,000 expected target calls and 5 MiB of JSON. Rule paths identify row and rule index; `explain_error` adds `ruleId` without operand values. Plans/rules/suites are portable between JS and Python; generated adapters remain language-specific.
122
+
123
+ ## Handoffs
124
+
125
+ ```python
126
+ from toolsplice import ToolContract, prepare_splice
127
+
128
+ source = ToolContract(
129
+ "docs",
130
+ "fetch",
131
+ {"type": "object"},
132
+ {
133
+ "type": "object",
134
+ "properties": {"markdown": {"type": "string"}},
135
+ "required": ["markdown"],
136
+ },
137
+ )
138
+ target = ToolContract(
139
+ "files",
140
+ "save",
141
+ {
142
+ "type": "object",
143
+ "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
144
+ "required": ["path", "content"],
145
+ },
146
+ {"type": "boolean"},
147
+ )
148
+ plan = {
149
+ "format": "toolsplice-splice",
150
+ "formatVersion": 1,
151
+ "source": {"server": "docs", "tool": "fetch", "path": "/markdown"},
152
+ "target": {"server": "files", "tool": "save"},
153
+ "contextSchema": {
154
+ "type": "object",
155
+ "properties": {"path": {"type": "string"}},
156
+ "required": ["path"],
157
+ },
158
+ "bindings": [
159
+ {"to": "/content", "from": ""},
160
+ {"to": "/path", "fromContext": "/path"},
161
+ ],
162
+ }
163
+ handoff = prepare_splice(plan, source, target)
164
+ print(handoff.report) # ready / review / blocked; assumptions and fingerprints
165
+
166
+ # Application supplies async source_caller(request) and target_caller(request).
167
+ # request: {"name": "...", "arguments": {...}}
168
+ # Return {"structuredContent": json_value}, or an MCP content/result envelope.
169
+
170
+
171
+ async def save_document(url: str) -> dict:
172
+ """Fetch and save a document; register this ordinary function in any framework."""
173
+ results = await handoff.run(
174
+ source_caller,
175
+ target_caller,
176
+ {"url": url},
177
+ context={"path": "application-owned-destination.md"},
178
+ allow_review=True,
179
+ timeout=30,
180
+ )
181
+ return {"saved": len(results)}
182
+ ```
183
+
184
+ `prepare_splice` also accepts shared `callshape-contract` snapshots. `create_contract_from_catalog(server, catalog, tools=[...])` builds them from saved catalogs; applications own pagination/identity. `ToolContract.from_catalog` selects one tool.
185
+
186
+ Static preflight conservatively checks required/optional/missing paths, nullability, unions, local references, mapped argument types, literals and bounds. `allow_review` permits review only; blocked setup and runtime guards remain enforced. Consumer `source.valueSchema` is an additional requirement, never an implicit replacement for the server declaration.
187
+
188
+ `map_output(decoded_fixture, context=...)` checks without tools. `run` validates source input/context before the source call, known source output, `source.expect`, selection/optional JSON parsing, consumer schema, fanout cap, every destination argument and `target.uniqueBy` before any destination dispatch. Destination calls are sequential; returned outputs and aggregate result bytes are checked afterward. Plans retain shared v1 camelCase fields; Python APIs use snake_case.
189
+
190
+ ## Execution and MCP
191
+
192
+ ```python
193
+ from toolsplice.mcp import mcp_caller
194
+
195
+ source_caller = mcp_caller(source_session)
196
+ target_caller = mcp_caller(target_session)
197
+ ```
198
+
199
+ The application initializes and closes sessions. `mcp_caller` uses the installed MCP SDK major version to pass deadlines in the correct units. Core imports do not import MCP. Helpers include `create_tool_caller`, `invoke_tool`, `tool_functions`, `BindingCallOptions`, and `create_contract_caller`. Guards preserve successful raw results and leave normal MCP error/unfinished-result handling to the caller. Unknown tools reject before dispatch.
200
+
201
+ `run(timeout=...)` bounds the awaited workflow; `call_timeout` defaults to 120 seconds per call. Request-scoped `on_progress` reaches the SDK adapter. Normalize multiple internal progress streams in the application when exposing one outer tool. Synchronous work/schema checks cannot be preempted by asyncio.
202
+
203
+ `SpliceError` exposes stage, completed_targets and path-only issues; `explain_error` adds endpoints, row/binding origins and source selection. `SpliceCancelled` is an asyncio cancellation with stage/count. Counts mean acknowledged/collected results, not committed writes. Effects can occur before cancellation, timeout, output or size rejection. No retry, rollback, exactly-once execution or durable resume is promised.
204
+
205
+ ## Shared recording, replay and corrections
206
+
207
+ ```python
208
+ from toolsplice import create_splice_recorder, replay_splice_recording
209
+
210
+ recorder = create_splice_recorder(
211
+ plan, source, target, capture="payloads", redact_keys=["customerEmail"]
212
+ )
213
+ await recorder.run(
214
+ source_caller,
215
+ target_caller,
216
+ {"url": url},
217
+ context={"path": path},
218
+ allow_review=True,
219
+ )
220
+ recording = recorder.snapshot()
221
+ report = await replay_splice_recording(recording)
222
+ upgrade = await replay_splice_recording(recording, target_contract=candidate_target)
223
+ ```
224
+
225
+ The factory creates **`toolsplice-recording` v1**, shared with JS. Replay verifies artifact/plan/contract fingerprints, exact saved call order/arguments and expected outcome. Candidate checks report passed/failed/inconclusive plus diffs/fingerprints. Failed/cancelled/transport-failed baselines cannot establish upgrade success. Replay accepts no live callers; it checks captured data, not live behavior or effects. Cancellation/timeout timing is not reproduced.
226
+
227
+ Metadata-only capture is the default; payloads are explicit and bounded. Common credential keys and configured keys/secret substrings are redacted with exact paths. Every redacted path needs a private restoration; extra paths are rejected. Redaction is not anonymization and fingerprints are not authentication. Capture failures never retry/change forwarding; snapshot/storage remain separately fallible. Applications explicitly choose where to persist recordings. Preview `Recorder`/`replay` remain for v0.1 native artifacts; use the factory above for shared artifacts. `replay` dispatches shared artifacts too.
228
+
229
+ `parse_contract_correction`/`apply_contract_correction` validate shared whole-schema replacements pinned to the original fingerprint, reason and positive/negative fixtures per changed tool/side. Originals remain intact, corrected metadata is fingerprinted and outputs labelled corrected. No correction automatically activates after guard failure.
230
+
231
+ ## Typed code and projects
232
+
233
+ `emit_splice_module` generates an executable Python adapter with `create_splice`; `emit_bindings`/`emit_module` generate callable tool methods; `schema_to_python` emits declarations. TypedDict inputs/outputs and required context support static checking. Untrusted names and JSON literals are quoted safely. Python typing differs from TypeScript; runtime guards remain authoritative.
234
+
235
+ `initialize_splice_project` creates a new private fixed-file directory from synthetic data or a successful shared recording. `check_splice_project` validates inputs/fixtures/mappings and adapter freshness without calls. Existing directories/files are refused. Python projects use `adapter.py`; JS projects use `adapter.ts`; generated-language files/freshness checks are not interchangeable. Restored project fixtures can contain confidential values while the retained recording remains redacted.
236
+
237
+ ## Learning and storage
238
+
239
+ ```python
240
+ from toolsplice import ShapeStore, record_tool_list, record_call, extract
241
+
242
+ store = ShapeStore("/application-owned-volume/toolsplice")
243
+
244
+
245
+ def update(record):
246
+ record_tool_list(record, catalog["tools"])
247
+ record_call(record, "fetch", extract(raw_result))
248
+
249
+
250
+ store.transact("installation-account-name", update)
251
+ ```
252
+
253
+ File operations are synchronous; `LearningStore` permits sync/async backends and `toolsplice.store.await_maybe` supports both. New directories/files use 0700/0600. Atomic replacement, shared writer locks and stale-save checks protect updates. Synchronous mutators are never retried after entry. Existing locks are not automatically reclaimed. Refresh/remove respect another process's forget; diagnostics inspect lock/temp ownership without returned values. Close watchers when finished.
254
+
255
+ ```python
256
+ from toolsplice.postgres import PostgresShapeStore
257
+
258
+ store = PostgresShapeStore(database_url, namespace="project-tenant", migrate=False)
259
+ await store.transact("installation-account-name", update)
260
+ await store.close()
261
+ ```
262
+
263
+ The optional async PostgreSQL backend shares JS `public.mcp_shape_*` tables, migration v1 and advisory-lock identities, including absent-row/delete locks. `migrate=True` bootstraps; use False with a restricted runtime role after migration. Namespaces partition records, not authorization. No cache/file fallback or callback retry follows a DB failure. The store owns its pool unless explicitly supplied by the application.
264
+
265
+ Learning includes bounded statistics, safe/all/none examples (default **none**), sensitive-key suppression, embedded JSON, maps/recursive trees, merges, drift revisions, structural declaration diagnostics, doctor reports and export freshness. Field names/counts/nonsensitive numeric bounds can persist under none; it is not anonymization. `create_contract_snapshot` exports learned portable contracts.
266
+
267
+ ## Proxy and HTTP
268
+
269
+ `create_proxy(initialized_session, store=store, server_name=...)` gives list_tools/call_tool methods. Description/none modes preserve results; learning failures stay fail-open. Notifications are coalesced; ordinary repeated observations do not churn descriptions. Experimental `enrich="schema"` can advertise lenient schemas and attach compatible structured content when explicitly requested.
270
+
271
+ For transparent wire forwarding, pass `(upstream_read, upstream_write)` and call `proxy.run(downstream_read, downstream_write)`. Non-tool MCP requests, resources and prompts pass through too. The CLI supports stdio/Streamable HTTP upstreams. Cancellation is forwarded; deadline failure reports uncertainty and suppresses late duplicate results. `proxy.close()` does not close application-owned stores/sessions.
272
+
273
+ `toolsplice.http.LearningTransport` wraps HTTPX with explicit client/endpoint/principal identity. It observes JSON/SSE without a second fetch; bounded finite JSON catalogs can be enriched. Late/oversized bodies pass through, SSE bytes remain unchanged, and `on_changed` is a local cache-refresh signal. SDKs retain authentication and protocol negotiation. This supplies the JS v2 fetch-adapter role without requiring a Python SDK 2.x.
274
+
275
+ ## CLI
276
+
277
+ ```sh
278
+ python -m toolsplice init ./new-handoff
279
+ python -m toolsplice test ./new-handoff
280
+ python -m toolsplice project ./new-handoff --allow-review --json
281
+ python -m toolsplice replay recording.json --target-contract next.json --json
282
+ python -m toolsplice proxy --store ./private-learning --name installation -- python server.py
283
+ ```
284
+
285
+ Installed binaries: toolsplice, callshape, mcp-shape. Commands: splice, test, replay, correct, init/project, proxy, config wrapping, explicit/read-only-hint probe, doctor, show/list, schema, snapshot/check, forget, storage diagnostics and **emit-py**. Artifact outputs refuse existing files. Exit 2 denotes blocked/unaccepted review, regression or candidate incompatibility; invalid configuration/artifacts exit 1. MCP stdout stays protocol-only in proxy mode.
286
+
287
+ `--store` selects a directory (default `.mcp-shape` relative to cwd). `--database-env NAME`, `--namespace`, `--no-migrate`, `--database-timeout` select/control PostgreSQL. Artifact commands supplied explicit contracts/catalogs do not initialize a store or contact providers. `--source-contract`, `--target-contract`, catalog equivalents, `--fixture`, `--context`, `--summary`, `--allow-review` and `--out` support offline handoff checks/generation.
288
+
289
+ ## Bounds and validation
290
+
291
+ Runtime guards support Draft 7 and 2020-12 (default), local references/recursive types, restricted ASCII RE2 patterns, unions/conditionals/tuples/dependencies and supported unevaluated assertions. External/dynamic refs, nested resources/dialects, patternProperties, ambiguous Draft 7 ref siblings and unknown assertions reject setup. Root $id is an annotation; formats/content annotations are not assertions. uniqueItems requires maxItems<=1000, matching JS. No schema is downloaded.
292
+
293
+ Shared JSON is finite, UTF-8 encodable, string-keyed and uses safe integers. Budgets reject cycles/oversized/deep data. Python integers are not silently rounded into JS numbers. No semantic matching, factual correctness, token savings, production availability, independent adoption or universal schema equivalence follows from passing tests.
294
+
295
+ ```sh
296
+ python -m pip install -e './packages/python[mcp,http,postgres,test]'
297
+ python -m pytest packages/python/tests
298
+ python packages/python/examples/composite.py
299
+ python -m build packages/python
300
+ ```
301
+
302
+ DB tests require TOOLSPLICE_PG_BIN and create only a disposable private loopback cluster. Cross-language conformance needs this built checkout and Node **for testing only**. Core tests/demo need no provider account or model call.
303
+
304
+ To compare a candidate with an independently checked baseline, run
305
+ `toolsplice impact ./handoff --candidate-result fresh-scrape.json`. Add `--case "case name"` for a suite with multiple cases. Candidate contract snapshots can be supplied with `--source-contract` and `--target-contract`. In Python, use `await assess_splice_impact(suite, source_results={"case name": raw_mcp_result})`. Read `status` for the verdict and `candidate.cases` for the changed field and binding. Both runs are offline.
306
+
307
+
308
+ Install the `mcp` extra to capture catalogs from live servers. Run `toolsplice catalog --url https://learn.microsoft.com/api/mcp --out learn.json` or use `--out tools.json -- server-command arg` for a stdio server. Then run `toolsplice impact ./handoff --source-catalog learn.json` to check the saved handoff against those definitions. SDK users can call `await collect_tool_catalog(list_page)` with an async callback that takes the next cursor, starting with `None`.
309
+
310
+ For a concise return value, set `"resultPath": "/metadata/sourceURL"` on the plan's `target`, or pass `--result-path '/metadata/sourceURL'` when initializing from catalogs. The caller receives one selected value per destination result. The whole response is validated before selection. A successful recording-derived test pins the returned array with `expect.resultFingerprint`.
311
+
312
+ For a named dict of fields, set `"resultFields": {"title": "/metadata/ogTitle", "revision": "/metadata/git_commit_id"}` on `target`. Each selected field must exist. Python generates a `TypedDict` for the result. The JS SDK reads the same plan.
313
+
314
+
315
+
316
+ ## Expose a handoff as one MCP tool
317
+
318
+ ```python
319
+ tool = handoff.as_tool(
320
+ name="find_document",
321
+ description="Find a document and return the article.",
322
+ source=source_caller,
323
+ target=target_caller,
324
+ )
325
+
326
+ @server.list_tools()
327
+ async def list_tools():
328
+ return [types.Tool.model_validate(tool.definition)]
329
+
330
+ @server.call_tool()
331
+ async def call_tool(name, arguments):
332
+ if name != tool.definition["name"]:
333
+ raise ValueError("Unknown tool")
334
+ reply = await tool.call(arguments, allow_review=True)
335
+ return types.CallToolResult.model_validate(reply)
336
+ ```
337
+
338
+ Here `server` is your Python MCP server and `types` is imported with `from mcp import types`. The SDK-independent `as_tool` method also works with other hosts that accept a tool schema and coroutine. Supply caller-specific `context` as a handler keyword argument. Failures report the stage, issue paths, previously collected results count and whether the destination may already have run. Cancellation propagates to the host.
339
+
340
+ ## Serve an MCP App
341
+
342
+ Create a view with `create_mcp_app_resource(uri="ui://docs/results", name="Results", html=html)` and pass `ui=view.tool_ui` to `as_tool`. Return `tool.definition` from your tool listing. Serve `view.read(uri)` from your resource handler. The HTML and `text/html;profile=mcp-app` MIME type travel together. The ordinary text and structured responses work in clients without a renderer.
343
+
344
+ ### Current MCP clients and extensions
345
+
346
+ Install `toolsplice[mcp2]` to use the optional official 2.x client with `toolsplice discover` and `toolsplice catalog --modern`. Use `create_v2_tool_caller(client)` with an already connected client. Applications that supply their own JSON-RPC exchange can use `create_mcp_peer` for interactive calls and resumable tasks, `open_mcp_skills` to verify a file from a static manifest, and `open_mcp_events` to validate polled event batches. Generate a public v1 endpoint description with `create_mcp_server_card`. Install `toolsplice[mcp2,skills]` for the official transport and the default YAML 1.2 reader. Each operation is independent of the agent framework.
347
+
348
+ For batched catalog setup, use `toolsplice init … --each /results --max-items 10 --bind /url=/contentUrl`. The preview lists paths relative to a row. The generated offline case pins all mapped argument objects.