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.
- package/README.md +62 -330
- package/dist/abortable.d.ts +6 -0
- package/dist/abortable.js +50 -0
- package/dist/adaptive-read.d.ts +50 -0
- package/dist/adaptive-read.js +780 -0
- package/dist/answer-wait.d.ts +7 -0
- package/dist/answer-wait.js +45 -0
- package/dist/cache-reads.d.ts +18 -0
- package/dist/cache-reads.js +89 -0
- package/dist/calibration-ledger.d.ts +37 -0
- package/dist/calibration-ledger.js +148 -0
- package/dist/calibration-marker.d.ts +4 -0
- package/dist/calibration-marker.js +77 -0
- package/dist/catalog-setup.d.ts +33 -0
- package/dist/catalog-setup.js +89 -0
- package/dist/catalog.d.ts +10 -0
- package/dist/catalog.js +42 -0
- package/dist/checkpoint-files.d.ts +15 -0
- package/dist/checkpoint-files.js +99 -0
- package/dist/cli.js +545 -14
- package/dist/coalesce-reads.d.ts +6 -0
- package/dist/coalesce-reads.js +33 -0
- package/dist/contract-caller.d.ts +2 -1
- package/dist/contract-caller.js +35 -16
- package/dist/contract-schema.d.ts +3 -1
- package/dist/contract-schema.js +34 -4
- package/dist/contracts.d.ts +1 -0
- package/dist/contracts.js +5 -1
- package/dist/core.d.ts +31 -1
- package/dist/core.js +27 -0
- package/dist/db-final-answer.d.ts +9 -0
- package/dist/db-final-answer.js +62 -0
- package/dist/define.d.ts +78 -0
- package/dist/define.js +14 -0
- package/dist/final-answer-stores.d.ts +71 -0
- package/dist/final-answer-stores.js +72 -0
- package/dist/final-answer.d.ts +32 -0
- package/dist/final-answer.js +104 -0
- package/dist/impact.d.ts +48 -0
- package/dist/impact.js +71 -0
- package/dist/index.d.ts +32 -1
- package/dist/index.js +28 -0
- package/dist/local-tool.d.ts +18 -0
- package/dist/local-tool.js +32 -0
- package/dist/mcp-apps.d.ts +53 -0
- package/dist/mcp-apps.js +32 -0
- package/dist/mcp-event-delivery.d.ts +98 -0
- package/dist/mcp-event-delivery.js +211 -0
- package/dist/mcp-extensions.d.ts +46 -0
- package/dist/mcp-extensions.js +200 -0
- package/dist/mcp-peer.d.ts +45 -0
- package/dist/mcp-peer.js +207 -0
- package/dist/mcp-server-card.d.ts +21 -0
- package/dist/mcp-server-card.js +54 -0
- package/dist/page-checkpoint.d.ts +71 -0
- package/dist/page-checkpoint.js +286 -0
- package/dist/page-read-gate.d.ts +15 -0
- package/dist/page-read-gate.js +48 -0
- package/dist/pattern.d.ts +1 -0
- package/dist/pattern.js +27 -5
- package/dist/probe.js +6 -19
- package/dist/read-pages.d.ts +25 -0
- package/dist/read-pages.js +85 -0
- package/dist/read-policy.d.ts +6 -0
- package/dist/read-policy.js +16 -0
- package/dist/read-steps.d.ts +12 -0
- package/dist/read-steps.js +36 -0
- package/dist/result-session.d.ts +109 -0
- package/dist/result-session.js +620 -0
- package/dist/route-checkpoint.d.ts +3 -0
- package/dist/route-checkpoint.js +80 -0
- package/dist/route-driver-cli.d.ts +3 -0
- package/dist/route-driver-cli.js +43 -0
- package/dist/route-evaluation.d.ts +141 -0
- package/dist/route-evaluation.js +329 -0
- package/dist/row-groups.d.ts +17 -0
- package/dist/row-groups.js +79 -0
- package/dist/row-query.d.ts +62 -0
- package/dist/row-query.js +172 -0
- package/dist/rules.d.ts +30 -0
- package/dist/rules.js +72 -0
- package/dist/run-diagnostics.d.ts +75 -0
- package/dist/run-diagnostics.js +212 -0
- package/dist/search-fetch.d.ts +50 -0
- package/dist/search-fetch.js +264 -0
- package/dist/skill-files.d.ts +9 -0
- package/dist/skill-files.js +49 -0
- package/dist/splice-diagnostics.d.ts +4 -0
- package/dist/splice-diagnostics.js +24 -16
- package/dist/splice-measure.d.ts +33 -0
- package/dist/splice-measure.js +55 -0
- package/dist/splice-project.d.ts +12 -6
- package/dist/splice-project.js +72 -20
- package/dist/splice-recording.d.ts +29 -2
- package/dist/splice-recording.js +22 -5
- package/dist/splice.d.ts +98 -1
- package/dist/splice.js +225 -27
- package/dist/sqlite-checkpoint-store.d.ts +5 -0
- package/dist/sqlite-checkpoint-store.js +91 -0
- package/dist/sqlite-checkpoint-worker.d.ts +1 -0
- package/dist/sqlite-checkpoint-worker.js +115 -0
- package/dist/test-difference.d.ts +13 -0
- package/dist/test-difference.js +42 -0
- package/dist/testing.d.ts +122 -0
- package/dist/testing.js +261 -0
- package/dist/text-pages.d.ts +24 -0
- package/dist/text-pages.js +36 -0
- package/dist/tool-discovery.d.ts +59 -0
- package/dist/tool-discovery.js +136 -0
- package/dist/unevaluated.d.ts +7 -0
- package/dist/unevaluated.js +156 -0
- package/dist/v2.js +25 -8
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/workflow-json.js +1 -1
- package/docs/AGENT-FRAMEWORKS.md +431 -0
- package/docs/BENCHMARKS.md +43 -0
- package/docs/INTEGRATION-QUICKSTART.md +859 -0
- package/docs/LEARNING-AND-STORAGE.md +393 -0
- package/docs/MCP.md +204 -0
- package/docs/PROJECTS-AND-UPGRADES.md +67 -9
- package/docs/PYTHON-REFERENCE.md +348 -0
- package/docs/PYTHON.md +120 -0
- package/docs/RECORDING-AND-CORRECTIONS.md +30 -1
- package/docs/TESTING.md +259 -0
- package/examples/mcp-app/build.mjs +11 -0
- package/examples/mcp-app/view.mjs +22 -0
- package/examples/quickstart.mjs +43 -0
- package/examples/route-driver.mjs +67 -0
- package/integrations/ai.d.mts +36 -0
- package/integrations/ai.mjs +178 -0
- package/integrations/call-options.mjs +9 -0
- package/integrations/langchain.d.mts +31 -0
- package/integrations/langchain.mjs +114 -0
- package/integrations/managed.mjs +154 -0
- package/integrations/types.d.mts +13 -0
- package/package.json +47 -3
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
# Projects, candidate-contract checks and the standalone core
|
|
2
2
|
|
|
3
|
-
|
|
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
4
|
|
|
5
5
|
## Start a project
|
|
6
6
|
|
|
7
7
|
```sh
|
|
8
8
|
toolsplice init ./my-handoff
|
|
9
|
+
toolsplice test ./my-handoff
|
|
9
10
|
toolsplice project ./my-handoff --allow-review --json
|
|
10
11
|
```
|
|
11
12
|
|
|
12
|
-
For
|
|
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.
|
|
13
14
|
|
|
14
15
|
The new private directory contains:
|
|
15
16
|
|
|
@@ -21,6 +22,7 @@ The new private directory contains:
|
|
|
21
22
|
| `input.json` | Saved source arguments |
|
|
22
23
|
| `fixture.json` | Saved decoded or raw MCP source result |
|
|
23
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 |
|
|
24
26
|
| `adapter.ts` | Generated typed adapter, using the full package |
|
|
25
27
|
| `README.md` | Check, regeneration and application instructions |
|
|
26
28
|
|
|
@@ -32,6 +34,8 @@ The check reports counts, paths and issues, omitting mapped values. `--allow-rev
|
|
|
32
34
|
|
|
33
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.
|
|
34
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
|
+
|
|
35
39
|
## Start from a successful recording
|
|
36
40
|
|
|
37
41
|
```sh
|
|
@@ -101,15 +105,69 @@ const code = emitSpliceModule(plan, sourceContract, targetContract);
|
|
|
101
105
|
|
|
102
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.
|
|
103
107
|
|
|
104
|
-
|
|
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.
|
|
105
137
|
|
|
106
138
|
```sh
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
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
|
+
}
|
|
111
169
|
```
|
|
112
170
|
|
|
113
|
-
|
|
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.
|
|
114
172
|
|
|
115
|
-
The
|
|
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.
|
package/docs/PYTHON.md
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# Toolsplice for Python
|
|
2
|
+
|
|
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
|
+
|
|
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.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Requires Python 3.11 or later.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
python -m pip install toolsplice==0.0.2
|
|
13
|
+
python -m toolsplice init ./my-handoff
|
|
14
|
+
python -m toolsplice test ./my-handoff
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The starter verifies a successful handoff and an invalid source that must produce zero destination calls. Both run offline.
|
|
18
|
+
|
|
19
|
+
## Runnable example
|
|
20
|
+
|
|
21
|
+
Save this as `handoff.py` and run `python handoff.py`. A mock document read returns a text field. The destination takes a different argument name and confirms the text arrived. Replacing the two callers connects the same mapping to real tools.
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
import asyncio
|
|
25
|
+
from toolsplice import create_mock_caller, define_splice
|
|
26
|
+
|
|
27
|
+
def text_field(name):
|
|
28
|
+
return {"type": "object", "properties": {name: {"type": "string"}}, "required": [name]}
|
|
29
|
+
|
|
30
|
+
async def main():
|
|
31
|
+
handoff = define_splice({
|
|
32
|
+
"source": {"server": "docs", "tool": "read", "inputSchema": text_field("id"),
|
|
33
|
+
"outputSchema": text_field("text")},
|
|
34
|
+
"target": {"server": "notes", "tool": "save", "inputSchema": text_field("content"),
|
|
35
|
+
"outputSchema": {"type": "boolean"}},
|
|
36
|
+
"bindings": [{"from": "/text", "to": "/content"}],
|
|
37
|
+
})
|
|
38
|
+
read = create_mock_caller([{"name": "read", "arguments": {"id": "a1"},
|
|
39
|
+
"result": {"structuredContent": {"text": "one two three"}}}])
|
|
40
|
+
save = create_mock_caller([{"name": "save", "arguments": {"content": "one two three"},
|
|
41
|
+
"result": {"structuredContent": True}}])
|
|
42
|
+
print(await handoff.run(read, save, {"id": "a1"})) # [True]
|
|
43
|
+
read.assert_done()
|
|
44
|
+
save.assert_done()
|
|
45
|
+
|
|
46
|
+
asyncio.run(main())
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
For a connected Python MCP v1 session, install `toolsplice[mcp]` and adapt it with `create_tool_caller(session)`. The client remains responsible for authentication and connection lifetime.
|
|
50
|
+
|
|
51
|
+
## Add Toolsplice to an existing agent
|
|
52
|
+
|
|
53
|
+
Wrap the tools and question for one request. Keep your existing model and authorization logic. Each context manager closes its private result store when the block exits.
|
|
54
|
+
|
|
55
|
+
### Agno
|
|
56
|
+
|
|
57
|
+
Install `python -m pip install 'toolsplice[agno]==0.0.2'`. The tool list can include Python functions, Agno tools or an already connected MCP toolkit.
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from agno.agent import Agent
|
|
61
|
+
from toolsplice.integrations.agno import agno_tools
|
|
62
|
+
|
|
63
|
+
with agno_tools(existing_tools, question) as tools:
|
|
64
|
+
reply = await Agent(model=model, tools=tools).arun(question)
|
|
65
|
+
print(reply.content)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### LangChain
|
|
69
|
+
|
|
70
|
+
Install `python -m pip install 'toolsplice[langchain]==0.0.2' 'langchain>=1,<2'`. Pass your existing LangChain tool list, including tools from an MCP adapter.
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from langchain.agents import create_agent
|
|
74
|
+
from toolsplice.integrations.langchain import langchain_tools
|
|
75
|
+
|
|
76
|
+
with langchain_tools(existing_tools, question) as tools:
|
|
77
|
+
agent = create_agent(model=model, tools=tools)
|
|
78
|
+
state = await agent.ainvoke({"messages": [{"role": "user", "content": question}]})
|
|
79
|
+
print(state["messages"][-1].content)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Inspect a result during one agent run
|
|
83
|
+
|
|
84
|
+
Select a few fields without sending the entire table back to a model. Use one session for each authenticated run.
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
from toolsplice import ResultSession
|
|
88
|
+
|
|
89
|
+
session = ResultSession(inline_bytes=1024)
|
|
90
|
+
try:
|
|
91
|
+
saved = session.capture({"rows": [{"id": i, "queue": "open"} for i in range(200)]})
|
|
92
|
+
page = session.inspect({"ref": saved["ref"], "path": "/rows", "fields": ["id"], "limit": 3})
|
|
93
|
+
assert [row["value"]["id"] for row in page["rows"]] == [0, 1, 2]
|
|
94
|
+
finally:
|
|
95
|
+
session.close()
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Connect real tools
|
|
99
|
+
|
|
100
|
+
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)
|
|
101
|
+
|
|
102
|
+
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)
|
|
103
|
+
|
|
104
|
+
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)
|
|
105
|
+
|
|
106
|
+
## Benchmarks
|
|
107
|
+
|
|
108
|
+
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.
|
|
109
|
+
|
|
110
|
+
| Implementation | Vercel AI SDK p95 | Agno p95 | Mean model USD/lookup |
|
|
111
|
+
| --- | ---: | ---: | ---: |
|
|
112
|
+
| Native agent loop | 6.379 s | 7.892 s | 0.0000680 |
|
|
113
|
+
| Native early return | 4.491 s | 5.912 s | 0.0000264 |
|
|
114
|
+
| Toolsplice with checkpoint | 4.039 s | 4.988 s | 0.0000264 |
|
|
115
|
+
|
|
116
|
+
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)
|
|
117
|
+
|
|
118
|
+
[JavaScript SDK](https://www.npmjs.com/package/toolsplice) · [Framework integration guide](https://cdn.jsdelivr.net/npm/toolsplice@0.0.2/docs/AGENT-FRAMEWORKS.md) · [Offline tests and fixtures](https://cdn.jsdelivr.net/npm/toolsplice@0.0.2/docs/TESTING.md)
|
|
119
|
+
|
|
120
|
+
[Python API and CLI reference](https://cdn.jsdelivr.net/npm/toolsplice@0.0.2/docs/PYTHON-REFERENCE.md)
|
|
@@ -93,6 +93,35 @@ Only the artifact's listed redaction paths can be replaced; all are required. Re
|
|
|
93
93
|
|
|
94
94
|
Saved transport exceptions are simulated without retaining their raw messages or causes. Cancellation timing is not reproduced. A target may have committed before cancellation or a response-validation error, even if the acknowledged result count is zero. Replay proves agreement with a fixture; it does not execute, roll back, resume or verify provider side effects, billing or factual correctness. It is not a crash-recovery journal.
|
|
95
95
|
|
|
96
|
+
## Measure what the model would receive
|
|
97
|
+
|
|
98
|
+
Run this on a saved, successful payload recording.
|
|
99
|
+
|
|
100
|
+
```sh
|
|
101
|
+
toolsplice measure ./recording.json --json
|
|
102
|
+
python -m toolsplice measure ./recording.json --json
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
The command first reproduces the handoff offline. It counts compact UTF-8 JSON once for each decoded upstream result. It compares their sum with the actual composite response object `{"results":[...]}`, including any reviewed `target.resultPath` projection. The output contains counts only. A negative `saved.toolResultBytes` means the composite wrapper is larger. A successful empty batch can produce that result.
|
|
106
|
+
|
|
107
|
+
`direct.modelToolCalls` counts the saved upstream calls under the assumption that the model calls each tool itself. `composite.modelToolCalls` counts one outer invocation. Parallel calls can share a model turn. Provider calls, model turns, and token use therefore have distinct meanings. Handwritten code exposing the same composite interface yields the same model-visible payload.
|
|
108
|
+
|
|
109
|
+
The SDK accepts your tokenizer for exact counts of these result texts.
|
|
110
|
+
|
|
111
|
+
```js
|
|
112
|
+
const measured = await measureSpliceRecording(recording, {
|
|
113
|
+
countTokens: text => tokenizer.encode(text).length,
|
|
114
|
+
});
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
measured = await measure_splice_recording(
|
|
119
|
+
recording, count_tokens=lambda text: len(tokenizer.encode(text))
|
|
120
|
+
)
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Result-token counts cover the tool messages' JSON content. Tool definitions, message framing, repeated history, cache discounts and model output require a measurement from the model runtime. If the recording contains redactions, supply the same private restorations used for replay. Python also accepts its earlier native recording format.
|
|
124
|
+
|
|
96
125
|
## Explain a failed field
|
|
97
126
|
|
|
98
127
|
`explainSpliceError(plan, error)` produces path-only diagnostics. For a destination type error on row 1, it can identify:
|
|
@@ -173,4 +202,4 @@ The demo uses two native synthetic MCP servers and writes four new Markdown file
|
|
|
173
202
|
|
|
174
203
|
Node 24.4.1 and 22.23.3 each passed 385 normal tests with zero failures and 13 opt-in skips, plus clean installed-package consumers. The new recording/correction/CLI tests contribute 20 cases. Native PostgreSQL 18.4 integrations ran separately on both runtimes: 13 tests each, 1,000 cross-process calls/observations each, zero recording warnings and successful restart recovery. The previous v0.7 lifecycle-soak results remain evidence of those older loaded versions, not of the new recorder.
|
|
175
204
|
|
|
176
|
-
Both updated handoff demos passed with the servers closed before API/CLI replay. A generated adapter using a corrected output contract compiled, checked a negative type assertion and ran with two fixture calls. Existing saved real Firecrawl/filesystem responses were converted to a new recording and replayed through the API and CLI; this used zero new network calls, filesystem writes or provider credits. No direct model calls or paid model benchmarks were run. Detailed hashes and evidence paths are in `test-results/v08-final-validation.json` in the checkout.
|
|
205
|
+
Both updated handoff demos passed with the servers closed before API/CLI replay. A generated adapter using a corrected output contract compiled, checked a negative type assertion and ran with two fixture calls. Existing saved real Firecrawl/filesystem responses were converted to a new recording and replayed through the API and CLI; this used zero new network calls, filesystem writes or provider credits. No direct model calls or paid model benchmarks were run. Detailed hashes and evidence paths are in `test-results/v08-final-validation.json` in the checkout.
|