toolsplice 0.0.1__tar.gz

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 (47) hide show
  1. toolsplice-0.0.1/LICENSE +21 -0
  2. toolsplice-0.0.1/MANIFEST.in +3 -0
  3. toolsplice-0.0.1/PKG-INFO +221 -0
  4. toolsplice-0.0.1/README.md +196 -0
  5. toolsplice-0.0.1/examples/composite.py +112 -0
  6. toolsplice-0.0.1/pyproject.toml +33 -0
  7. toolsplice-0.0.1/setup.cfg +4 -0
  8. toolsplice-0.0.1/src/toolsplice/__init__.py +111 -0
  9. toolsplice-0.0.1/src/toolsplice/__main__.py +3 -0
  10. toolsplice-0.0.1/src/toolsplice/_json.py +137 -0
  11. toolsplice-0.0.1/src/toolsplice/cli.py +455 -0
  12. toolsplice-0.0.1/src/toolsplice/codegen.py +209 -0
  13. toolsplice-0.0.1/src/toolsplice/contracts.py +475 -0
  14. toolsplice-0.0.1/src/toolsplice/core.py +712 -0
  15. toolsplice-0.0.1/src/toolsplice/corrections.py +128 -0
  16. toolsplice-0.0.1/src/toolsplice/diagnostics.py +280 -0
  17. toolsplice-0.0.1/src/toolsplice/execution.py +147 -0
  18. toolsplice-0.0.1/src/toolsplice/http.py +147 -0
  19. toolsplice-0.0.1/src/toolsplice/learning.py +734 -0
  20. toolsplice-0.0.1/src/toolsplice/mcp.py +11 -0
  21. toolsplice-0.0.1/src/toolsplice/portable.py +318 -0
  22. toolsplice-0.0.1/src/toolsplice/postgres.py +285 -0
  23. toolsplice-0.0.1/src/toolsplice/preflight.py +490 -0
  24. toolsplice-0.0.1/src/toolsplice/probe.py +131 -0
  25. toolsplice-0.0.1/src/toolsplice/projects.py +298 -0
  26. toolsplice-0.0.1/src/toolsplice/proxy.py +566 -0
  27. toolsplice-0.0.1/src/toolsplice/py.typed +0 -0
  28. toolsplice-0.0.1/src/toolsplice/recording.py +472 -0
  29. toolsplice-0.0.1/src/toolsplice/schema.py +290 -0
  30. toolsplice-0.0.1/src/toolsplice/storage.py +15 -0
  31. toolsplice-0.0.1/src/toolsplice/store.py +716 -0
  32. toolsplice-0.0.1/src/toolsplice.egg-info/PKG-INFO +221 -0
  33. toolsplice-0.0.1/src/toolsplice.egg-info/SOURCES.txt +45 -0
  34. toolsplice-0.0.1/src/toolsplice.egg-info/dependency_links.txt +1 -0
  35. toolsplice-0.0.1/src/toolsplice.egg-info/entry_points.txt +4 -0
  36. toolsplice-0.0.1/src/toolsplice.egg-info/requires.txt +19 -0
  37. toolsplice-0.0.1/src/toolsplice.egg-info/top_level.txt +1 -0
  38. toolsplice-0.0.1/tests/conftest.py +58 -0
  39. toolsplice-0.0.1/tests/mcp_server.py +49 -0
  40. toolsplice-0.0.1/tests/test_core.py +472 -0
  41. toolsplice-0.0.1/tests/test_file_processes.py +51 -0
  42. toolsplice-0.0.1/tests/test_full_features.py +622 -0
  43. toolsplice-0.0.1/tests/test_http_proxy_cli.py +284 -0
  44. toolsplice-0.0.1/tests/test_mcp.py +120 -0
  45. toolsplice-0.0.1/tests/test_portable.py +306 -0
  46. toolsplice-0.0.1/tests/test_postgres.py +227 -0
  47. toolsplice-0.0.1/tests/test_recording.py +255 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 toolsplice contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ include LICENSE
2
+ include examples/*.py
3
+ recursive-include tests *.py
@@ -0,0 +1,221 @@
1
+ Metadata-Version: 2.4
2
+ Name: toolsplice
3
+ Version: 0.0.1
4
+ Summary: Framework-independent checked tool handoffs and offline fixtures for Python
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.11
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: jsonschema<5,>=4.23
10
+ Requires-Dist: referencing<1,>=0.30
11
+ Requires-Dist: google-re2<2,>=1.1
12
+ Requires-Dist: rfc8785<1,>=0.1
13
+ Provides-Extra: mcp
14
+ Requires-Dist: mcp<2,>=1.20; extra == "mcp"
15
+ Provides-Extra: postgres
16
+ Requires-Dist: psycopg[binary,pool]<4,>=3.2; extra == "postgres"
17
+ Provides-Extra: http
18
+ Requires-Dist: httpx<1,>=0.27; extra == "http"
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest<10,>=8; extra == "test"
21
+ Requires-Dist: pytest-asyncio<2,>=0.24; extra == "test"
22
+ Requires-Dist: build<2,>=1; extra == "test"
23
+ Requires-Dist: mypy<2,>=1.11; extra == "test"
24
+ Dynamic: license-file
25
+
26
+ # Toolsplice for Python
27
+
28
+ Native, framework-independent SDK for checked tool handoffs, learning, typed bindings and offline maintenance. **0.0.1**, Python **3.11+**. No Node, Agno, model-provider or Cloudflare runtime dependency.
29
+
30
+ This release implements the JavaScript SDK's feature categories. Portable contracts, corrections, shared recordings and learning records use JS wire formats/fingerprints. Generated Python code and project adapters are language-specific. Tests establish the represented cases, not universal equivalence or production readiness.
31
+
32
+ ## Install
33
+
34
+ ```sh
35
+ python -m pip install toolsplice==0.0.1
36
+ python -m pip install 'toolsplice[mcp]==0.0.1' # SDK adapter and proxy transports
37
+ python -m pip install 'toolsplice[postgres]==0.0.1' # Optional database backend
38
+ python -m pip install 'toolsplice[http]==0.0.1' # Optional HTTPX middleware
39
+ ```
40
+
41
+ For local development, install the absolute checkout path to `packages/python`. Core dependencies: jsonschema, referencing, google-re2 and rfc8785, plus transitive dependencies. RE2/rpds-py use native platform components.
42
+
43
+ ## Handoffs
44
+
45
+ ```python
46
+ from toolsplice import ToolContract, prepare_splice
47
+
48
+ source = ToolContract(
49
+ "docs",
50
+ "fetch",
51
+ {"type": "object"},
52
+ {
53
+ "type": "object",
54
+ "properties": {"markdown": {"type": "string"}},
55
+ "required": ["markdown"],
56
+ },
57
+ )
58
+ target = ToolContract(
59
+ "files",
60
+ "save",
61
+ {
62
+ "type": "object",
63
+ "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
64
+ "required": ["path", "content"],
65
+ },
66
+ {"type": "boolean"},
67
+ )
68
+ plan = {
69
+ "format": "toolsplice-splice",
70
+ "formatVersion": 1,
71
+ "source": {"server": "docs", "tool": "fetch", "path": "/markdown"},
72
+ "target": {"server": "files", "tool": "save"},
73
+ "contextSchema": {
74
+ "type": "object",
75
+ "properties": {"path": {"type": "string"}},
76
+ "required": ["path"],
77
+ },
78
+ "bindings": [
79
+ {"to": "/content", "from": ""},
80
+ {"to": "/path", "fromContext": "/path"},
81
+ ],
82
+ }
83
+ handoff = prepare_splice(plan, source, target)
84
+ print(handoff.report) # ready / review / blocked; assumptions and fingerprints
85
+
86
+ # Application supplies async source_caller(request) and target_caller(request).
87
+ # request: {"name": "...", "arguments": {...}}
88
+ # Return {"structuredContent": json_value}, or an MCP content/result envelope.
89
+
90
+
91
+ async def save_document(url: str) -> dict:
92
+ """Fetch and save a document; register this ordinary function in any framework."""
93
+ results = await handoff.run(
94
+ source_caller,
95
+ target_caller,
96
+ {"url": url},
97
+ context={"path": "application-owned-destination.md"},
98
+ allow_review=True,
99
+ timeout=30,
100
+ )
101
+ return {"saved": len(results)}
102
+ ```
103
+
104
+ `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.
105
+
106
+ 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.
107
+
108
+ `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.
109
+
110
+ ## Execution and MCP
111
+
112
+ ```python
113
+ from toolsplice.mcp import mcp_caller
114
+
115
+ source_caller = mcp_caller(source_session)
116
+ target_caller = mcp_caller(target_session)
117
+ ```
118
+
119
+ Sessions are initialized/closed by the application. 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.
120
+
121
+ `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.
122
+
123
+ `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.
124
+
125
+ ## Shared recording, replay and corrections
126
+
127
+ ```python
128
+ from toolsplice import create_splice_recorder, replay_splice_recording
129
+
130
+ recorder = create_splice_recorder(
131
+ plan, source, target, capture="payloads", redact_keys=["customerEmail"]
132
+ )
133
+ await recorder.run(
134
+ source_caller,
135
+ target_caller,
136
+ {"url": url},
137
+ context={"path": path},
138
+ allow_review=True,
139
+ )
140
+ recording = recorder.snapshot()
141
+ report = await replay_splice_recording(recording)
142
+ upgrade = await replay_splice_recording(recording, target_contract=candidate_target)
143
+ ```
144
+
145
+ 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.
146
+
147
+ 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.
148
+
149
+ `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.
150
+
151
+ ## Typed code and projects
152
+
153
+ `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.
154
+
155
+ `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.
156
+
157
+ ## Learning and storage
158
+
159
+ ```python
160
+ from toolsplice import ShapeStore, record_tool_list, record_call, extract
161
+
162
+ store = ShapeStore("/application-owned-volume/toolsplice")
163
+
164
+
165
+ def update(record):
166
+ record_tool_list(record, catalog["tools"])
167
+ record_call(record, "fetch", extract(raw_result))
168
+
169
+
170
+ store.transact("installation-account-name", update)
171
+ ```
172
+
173
+ 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.
174
+
175
+ ```python
176
+ from toolsplice.postgres import PostgresShapeStore
177
+
178
+ store = PostgresShapeStore(database_url, namespace="project-tenant", migrate=False)
179
+ await store.transact("installation-account-name", update)
180
+ await store.close()
181
+ ```
182
+
183
+ 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.
184
+
185
+ 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.
186
+
187
+ ## Proxy and HTTP
188
+
189
+ `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.
190
+
191
+ 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.
192
+
193
+ `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.
194
+
195
+ ## CLI
196
+
197
+ ```sh
198
+ python -m toolsplice init ./new-handoff
199
+ python -m toolsplice project ./new-handoff --allow-review --json
200
+ python -m toolsplice replay recording.json --target-contract next.json --json
201
+ python -m toolsplice proxy --store ./private-learning --name installation -- python server.py
202
+ ```
203
+
204
+ Installed binaries: toolsplice, callshape, mcp-shape. Commands: splice, 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.
205
+
206
+ `--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.
207
+
208
+ ## Bounds and validation
209
+
210
+ 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.
211
+
212
+ 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.
213
+
214
+ ```sh
215
+ python -m pip install -e './packages/python[mcp,http,postgres,test]'
216
+ python -m pytest packages/python/tests
217
+ python packages/python/examples/composite.py
218
+ python -m build packages/python
219
+ ```
220
+
221
+ 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.
@@ -0,0 +1,196 @@
1
+ # Toolsplice for Python
2
+
3
+ Native, framework-independent SDK for checked tool handoffs, learning, typed bindings and offline maintenance. **0.0.1**, Python **3.11+**. No Node, Agno, model-provider or Cloudflare runtime dependency.
4
+
5
+ This release implements the JavaScript SDK's feature categories. Portable contracts, corrections, shared recordings and learning records use JS wire formats/fingerprints. Generated Python code and project adapters are language-specific. Tests establish the represented cases, not universal equivalence or production readiness.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ python -m pip install toolsplice==0.0.1
11
+ python -m pip install 'toolsplice[mcp]==0.0.1' # SDK adapter and proxy transports
12
+ python -m pip install 'toolsplice[postgres]==0.0.1' # Optional database backend
13
+ python -m pip install 'toolsplice[http]==0.0.1' # Optional HTTPX middleware
14
+ ```
15
+
16
+ For local development, install the absolute checkout path to `packages/python`. Core dependencies: jsonschema, referencing, google-re2 and rfc8785, plus transitive dependencies. RE2/rpds-py use native platform components.
17
+
18
+ ## Handoffs
19
+
20
+ ```python
21
+ from toolsplice import ToolContract, prepare_splice
22
+
23
+ source = ToolContract(
24
+ "docs",
25
+ "fetch",
26
+ {"type": "object"},
27
+ {
28
+ "type": "object",
29
+ "properties": {"markdown": {"type": "string"}},
30
+ "required": ["markdown"],
31
+ },
32
+ )
33
+ target = ToolContract(
34
+ "files",
35
+ "save",
36
+ {
37
+ "type": "object",
38
+ "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
39
+ "required": ["path", "content"],
40
+ },
41
+ {"type": "boolean"},
42
+ )
43
+ plan = {
44
+ "format": "toolsplice-splice",
45
+ "formatVersion": 1,
46
+ "source": {"server": "docs", "tool": "fetch", "path": "/markdown"},
47
+ "target": {"server": "files", "tool": "save"},
48
+ "contextSchema": {
49
+ "type": "object",
50
+ "properties": {"path": {"type": "string"}},
51
+ "required": ["path"],
52
+ },
53
+ "bindings": [
54
+ {"to": "/content", "from": ""},
55
+ {"to": "/path", "fromContext": "/path"},
56
+ ],
57
+ }
58
+ handoff = prepare_splice(plan, source, target)
59
+ print(handoff.report) # ready / review / blocked; assumptions and fingerprints
60
+
61
+ # Application supplies async source_caller(request) and target_caller(request).
62
+ # request: {"name": "...", "arguments": {...}}
63
+ # Return {"structuredContent": json_value}, or an MCP content/result envelope.
64
+
65
+
66
+ async def save_document(url: str) -> dict:
67
+ """Fetch and save a document; register this ordinary function in any framework."""
68
+ results = await handoff.run(
69
+ source_caller,
70
+ target_caller,
71
+ {"url": url},
72
+ context={"path": "application-owned-destination.md"},
73
+ allow_review=True,
74
+ timeout=30,
75
+ )
76
+ return {"saved": len(results)}
77
+ ```
78
+
79
+ `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.
80
+
81
+ 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.
82
+
83
+ `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.
84
+
85
+ ## Execution and MCP
86
+
87
+ ```python
88
+ from toolsplice.mcp import mcp_caller
89
+
90
+ source_caller = mcp_caller(source_session)
91
+ target_caller = mcp_caller(target_session)
92
+ ```
93
+
94
+ Sessions are initialized/closed by the application. 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.
95
+
96
+ `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.
97
+
98
+ `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.
99
+
100
+ ## Shared recording, replay and corrections
101
+
102
+ ```python
103
+ from toolsplice import create_splice_recorder, replay_splice_recording
104
+
105
+ recorder = create_splice_recorder(
106
+ plan, source, target, capture="payloads", redact_keys=["customerEmail"]
107
+ )
108
+ await recorder.run(
109
+ source_caller,
110
+ target_caller,
111
+ {"url": url},
112
+ context={"path": path},
113
+ allow_review=True,
114
+ )
115
+ recording = recorder.snapshot()
116
+ report = await replay_splice_recording(recording)
117
+ upgrade = await replay_splice_recording(recording, target_contract=candidate_target)
118
+ ```
119
+
120
+ 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.
121
+
122
+ 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.
123
+
124
+ `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.
125
+
126
+ ## Typed code and projects
127
+
128
+ `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.
129
+
130
+ `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.
131
+
132
+ ## Learning and storage
133
+
134
+ ```python
135
+ from toolsplice import ShapeStore, record_tool_list, record_call, extract
136
+
137
+ store = ShapeStore("/application-owned-volume/toolsplice")
138
+
139
+
140
+ def update(record):
141
+ record_tool_list(record, catalog["tools"])
142
+ record_call(record, "fetch", extract(raw_result))
143
+
144
+
145
+ store.transact("installation-account-name", update)
146
+ ```
147
+
148
+ 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.
149
+
150
+ ```python
151
+ from toolsplice.postgres import PostgresShapeStore
152
+
153
+ store = PostgresShapeStore(database_url, namespace="project-tenant", migrate=False)
154
+ await store.transact("installation-account-name", update)
155
+ await store.close()
156
+ ```
157
+
158
+ 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.
159
+
160
+ 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.
161
+
162
+ ## Proxy and HTTP
163
+
164
+ `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.
165
+
166
+ 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.
167
+
168
+ `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.
169
+
170
+ ## CLI
171
+
172
+ ```sh
173
+ python -m toolsplice init ./new-handoff
174
+ python -m toolsplice project ./new-handoff --allow-review --json
175
+ python -m toolsplice replay recording.json --target-contract next.json --json
176
+ python -m toolsplice proxy --store ./private-learning --name installation -- python server.py
177
+ ```
178
+
179
+ Installed binaries: toolsplice, callshape, mcp-shape. Commands: splice, 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.
180
+
181
+ `--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.
182
+
183
+ ## Bounds and validation
184
+
185
+ 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.
186
+
187
+ 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.
188
+
189
+ ```sh
190
+ python -m pip install -e './packages/python[mcp,http,postgres,test]'
191
+ python -m pytest packages/python/tests
192
+ python packages/python/examples/composite.py
193
+ python -m build packages/python
194
+ ```
195
+
196
+ 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.
@@ -0,0 +1,112 @@
1
+ """Generic composite-tool example: run directly; no agent framework or model call."""
2
+
3
+ import asyncio
4
+ import json
5
+ from pathlib import Path
6
+ from tempfile import TemporaryDirectory
7
+
8
+ from toolsplice import (
9
+ ToolContract,
10
+ prepare_splice,
11
+ create_splice_recorder,
12
+ replay_splice_recording,
13
+ )
14
+
15
+
16
+ async def main():
17
+ source = ToolContract(
18
+ "docs",
19
+ "fetch",
20
+ {"type": "object"},
21
+ {
22
+ "type": "object",
23
+ "properties": {"markdown": {"type": "string"}},
24
+ "required": ["markdown"],
25
+ },
26
+ )
27
+ target = ToolContract(
28
+ "files",
29
+ "save",
30
+ {
31
+ "type": "object",
32
+ "properties": {
33
+ "path": {"type": "string"},
34
+ "content": {"type": "string", "minLength": 1},
35
+ },
36
+ "required": ["path", "content"],
37
+ },
38
+ {
39
+ "type": "object",
40
+ "properties": {"saved": {"type": "boolean"}},
41
+ "required": ["saved"],
42
+ },
43
+ )
44
+ plan = {
45
+ "format": "toolsplice-splice",
46
+ "formatVersion": 1,
47
+ "source": {"server": "docs", "tool": "fetch", "path": "/markdown"},
48
+ "target": {"server": "files", "tool": "save"},
49
+ "contextSchema": {
50
+ "type": "object",
51
+ "properties": {"path": {"type": "string"}},
52
+ "required": ["path"],
53
+ },
54
+ "bindings": [
55
+ {"to": "/content", "from": ""},
56
+ {"to": "/path", "fromContext": "/path"},
57
+ ],
58
+ }
59
+ splice = prepare_splice(plan, source, target)
60
+ calls = {"source": 0, "target": 0}
61
+ markdown = "# Public example\n" + "Example document body.\n" * 3000
62
+
63
+ async def fetch(request):
64
+ calls["source"] += 1
65
+ return {"structuredContent": {"markdown": markdown}}
66
+
67
+ async def save(request):
68
+ calls["target"] += 1
69
+ Path(request["arguments"]["path"]).write_text(request["arguments"]["content"])
70
+ return {"structuredContent": {"saved": True}}
71
+
72
+ with TemporaryDirectory(prefix="toolsplice-python-") as folder:
73
+ path = Path(folder) / "document.md"
74
+ recorder = create_splice_recorder(plan, source, target, capture="payloads")
75
+
76
+ async def save_document(url: str) -> dict:
77
+ """Fetch and save a document; suitable for an ordinary framework tool wrapper."""
78
+ results = await recorder.run(
79
+ fetch,
80
+ save,
81
+ {"url": url},
82
+ context={"path": str(path)},
83
+ allow_review=True,
84
+ )
85
+ return {"saved": len(results)}
86
+
87
+ receipt = await save_document("https://example.com")
88
+ assert path.read_text() == markdown
89
+ before = dict(calls)
90
+ replayed = await replay_splice_recording(recorder.snapshot())
91
+ assert replayed["matched"] and calls == before
92
+ print(
93
+ json.dumps(
94
+ {
95
+ "receipt": receipt,
96
+ "underlyingCalls": calls,
97
+ "sourceMarkdownBytes": len(markdown.encode()),
98
+ "receiptBytes": len(
99
+ json.dumps(receipt, separators=(",", ":")).encode()
100
+ ),
101
+ "replayMatched": replayed["matched"],
102
+ "replayNetworkCalls": replayed["networkCalls"],
103
+ "modelCalls": 0,
104
+ "note": "Synthetic local Python example; bytes are not measured tokens.",
105
+ },
106
+ indent=2,
107
+ )
108
+ )
109
+
110
+
111
+ if __name__ == "__main__":
112
+ asyncio.run(main())
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "toolsplice"
7
+ version = "0.0.1"
8
+ description = "Framework-independent checked tool handoffs and offline fixtures for Python"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ dependencies = ["jsonschema>=4.23,<5", "referencing>=0.30,<1", "google-re2>=1.1,<2", "rfc8785>=0.1,<1"]
13
+
14
+ [project.optional-dependencies]
15
+ mcp = ["mcp>=1.20,<2"]
16
+ postgres = ["psycopg[binary,pool]>=3.2,<4"]
17
+ http = ["httpx>=0.27,<1"]
18
+ test = ["pytest>=8,<10", "pytest-asyncio>=0.24,<2", "build>=1,<2", "mypy>=1.11,<2"]
19
+
20
+ [project.scripts]
21
+ toolsplice = "toolsplice.cli:main"
22
+ callshape = "toolsplice.cli:main"
23
+ mcp-shape = "toolsplice.cli:main"
24
+
25
+ [tool.setuptools.packages.find]
26
+ where = ["src"]
27
+
28
+ [tool.setuptools.package-data]
29
+ toolsplice = ["py.typed"]
30
+
31
+ [tool.pytest.ini_options]
32
+ asyncio_mode = "auto"
33
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+