toolsplice 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +104 -2
  3. package/dist/abortable.d.ts +6 -0
  4. package/dist/abortable.js +50 -0
  5. package/dist/adaptive-read.d.ts +50 -0
  6. package/dist/adaptive-read.js +780 -0
  7. package/dist/answer-wait.d.ts +7 -0
  8. package/dist/answer-wait.js +45 -0
  9. package/dist/cache-reads.d.ts +18 -0
  10. package/dist/cache-reads.js +89 -0
  11. package/dist/calibration-ledger.d.ts +37 -0
  12. package/dist/calibration-ledger.js +148 -0
  13. package/dist/calibration-marker.d.ts +4 -0
  14. package/dist/calibration-marker.js +77 -0
  15. package/dist/catalog-setup.d.ts +33 -0
  16. package/dist/catalog-setup.js +89 -0
  17. package/dist/catalog.d.ts +10 -0
  18. package/dist/catalog.js +42 -0
  19. package/dist/checkpoint-files.d.ts +15 -0
  20. package/dist/checkpoint-files.js +99 -0
  21. package/dist/cli.d.ts +2 -0
  22. package/dist/cli.js +1454 -0
  23. package/dist/coalesce-reads.d.ts +6 -0
  24. package/dist/coalesce-reads.js +33 -0
  25. package/dist/codegen.d.ts +44 -0
  26. package/dist/codegen.js +479 -0
  27. package/dist/contract-caller.d.ts +23 -0
  28. package/dist/contract-caller.js +326 -0
  29. package/dist/contract-corrections.d.ts +35 -0
  30. package/dist/contract-corrections.js +159 -0
  31. package/dist/contract-schema.d.ts +7 -0
  32. package/dist/contract-schema.js +156 -0
  33. package/dist/contracts.d.ts +72 -0
  34. package/dist/contracts.js +370 -0
  35. package/dist/core.d.ts +44 -0
  36. package/dist/core.js +43 -0
  37. package/dist/db-final-answer.d.ts +9 -0
  38. package/dist/db-final-answer.js +62 -0
  39. package/dist/define.d.ts +78 -0
  40. package/dist/define.js +14 -0
  41. package/dist/doctor.d.ts +22 -0
  42. package/dist/doctor.js +91 -0
  43. package/dist/drift.d.ts +23 -0
  44. package/dist/drift.js +111 -0
  45. package/dist/execution.d.ts +38 -0
  46. package/dist/execution.js +66 -0
  47. package/dist/extract.d.ts +34 -0
  48. package/dist/extract.js +73 -0
  49. package/dist/final-answer-stores.d.ts +71 -0
  50. package/dist/final-answer-stores.js +72 -0
  51. package/dist/final-answer.d.ts +32 -0
  52. package/dist/final-answer.js +104 -0
  53. package/dist/impact.d.ts +48 -0
  54. package/dist/impact.js +71 -0
  55. package/dist/index.d.ts +51 -0
  56. package/dist/index.js +47 -0
  57. package/dist/local-tool.d.ts +18 -0
  58. package/dist/local-tool.js +32 -0
  59. package/dist/mcp-apps.d.ts +53 -0
  60. package/dist/mcp-apps.js +32 -0
  61. package/dist/mcp-event-delivery.d.ts +98 -0
  62. package/dist/mcp-event-delivery.js +211 -0
  63. package/dist/mcp-extensions.d.ts +46 -0
  64. package/dist/mcp-extensions.js +200 -0
  65. package/dist/mcp-peer.d.ts +45 -0
  66. package/dist/mcp-peer.js +207 -0
  67. package/dist/mcp-server-card.d.ts +21 -0
  68. package/dist/mcp-server-card.js +54 -0
  69. package/dist/ordered-transport.d.ts +12 -0
  70. package/dist/ordered-transport.js +106 -0
  71. package/dist/page-checkpoint.d.ts +71 -0
  72. package/dist/page-checkpoint.js +286 -0
  73. package/dist/page-read-gate.d.ts +15 -0
  74. package/dist/page-read-gate.js +48 -0
  75. package/dist/pattern.d.ts +3 -0
  76. package/dist/pattern.js +54 -0
  77. package/dist/postgres.d.ts +41 -0
  78. package/dist/postgres.js +264 -0
  79. package/dist/probe.d.ts +29 -0
  80. package/dist/probe.js +121 -0
  81. package/dist/proxy.d.ts +40 -0
  82. package/dist/proxy.js +436 -0
  83. package/dist/read-pages.d.ts +25 -0
  84. package/dist/read-pages.js +85 -0
  85. package/dist/read-policy.d.ts +6 -0
  86. package/dist/read-policy.js +16 -0
  87. package/dist/read-steps.d.ts +12 -0
  88. package/dist/read-steps.js +36 -0
  89. package/dist/result-session.d.ts +109 -0
  90. package/dist/result-session.js +620 -0
  91. package/dist/route-checkpoint.d.ts +3 -0
  92. package/dist/route-checkpoint.js +80 -0
  93. package/dist/route-driver-cli.d.ts +3 -0
  94. package/dist/route-driver-cli.js +43 -0
  95. package/dist/route-evaluation.d.ts +141 -0
  96. package/dist/route-evaluation.js +329 -0
  97. package/dist/row-groups.d.ts +17 -0
  98. package/dist/row-groups.js +79 -0
  99. package/dist/row-query.d.ts +62 -0
  100. package/dist/row-query.js +172 -0
  101. package/dist/rules.d.ts +30 -0
  102. package/dist/rules.js +72 -0
  103. package/dist/run-diagnostics.d.ts +75 -0
  104. package/dist/run-diagnostics.js +212 -0
  105. package/dist/runtime.d.ts +6 -0
  106. package/dist/runtime.js +26 -0
  107. package/dist/schema.d.ts +17 -0
  108. package/dist/schema.js +299 -0
  109. package/dist/search-fetch.d.ts +50 -0
  110. package/dist/search-fetch.js +264 -0
  111. package/dist/shape.d.ts +91 -0
  112. package/dist/shape.js +499 -0
  113. package/dist/skill-files.d.ts +9 -0
  114. package/dist/skill-files.js +49 -0
  115. package/dist/splice-diagnostics.d.ts +44 -0
  116. package/dist/splice-diagnostics.js +88 -0
  117. package/dist/splice-measure.d.ts +33 -0
  118. package/dist/splice-measure.js +55 -0
  119. package/dist/splice-project.d.ts +125 -0
  120. package/dist/splice-project.js +348 -0
  121. package/dist/splice-recording.d.ts +132 -0
  122. package/dist/splice-recording.js +481 -0
  123. package/dist/splice.d.ts +181 -0
  124. package/dist/splice.js +1263 -0
  125. package/dist/sqlite-checkpoint-store.d.ts +5 -0
  126. package/dist/sqlite-checkpoint-store.js +91 -0
  127. package/dist/sqlite-checkpoint-worker.d.ts +1 -0
  128. package/dist/sqlite-checkpoint-worker.js +115 -0
  129. package/dist/storage.d.ts +17 -0
  130. package/dist/storage.js +1 -0
  131. package/dist/store.d.ts +151 -0
  132. package/dist/store.js +735 -0
  133. package/dist/test-difference.d.ts +13 -0
  134. package/dist/test-difference.js +42 -0
  135. package/dist/testing.d.ts +122 -0
  136. package/dist/testing.js +261 -0
  137. package/dist/text-pages.d.ts +24 -0
  138. package/dist/text-pages.js +36 -0
  139. package/dist/tool-discovery.d.ts +59 -0
  140. package/dist/tool-discovery.js +136 -0
  141. package/dist/unevaluated.d.ts +7 -0
  142. package/dist/unevaluated.js +156 -0
  143. package/dist/v2.d.ts +49 -0
  144. package/dist/v2.js +413 -0
  145. package/dist/validate-output.d.ts +3 -0
  146. package/dist/validate-output.js +73 -0
  147. package/dist/version.d.ts +1 -0
  148. package/dist/version.js +1 -0
  149. package/dist/workflow-json.d.ts +8 -0
  150. package/dist/workflow-json.js +74 -0
  151. package/docs/AGENT-FRAMEWORKS.md +431 -0
  152. package/docs/BENCHMARKS.md +43 -0
  153. package/docs/INTEGRATION-QUICKSTART.md +859 -0
  154. package/docs/LEARNING-AND-STORAGE.md +393 -0
  155. package/docs/MCP.md +204 -0
  156. package/docs/PROJECTS-AND-UPGRADES.md +173 -0
  157. package/docs/PYTHON-REFERENCE.md +348 -0
  158. package/docs/PYTHON.md +120 -0
  159. package/docs/RECORDING-AND-CORRECTIONS.md +205 -0
  160. package/docs/TESTING.md +259 -0
  161. package/examples/mcp-app/build.mjs +11 -0
  162. package/examples/mcp-app/view.mjs +22 -0
  163. package/examples/quickstart.mjs +43 -0
  164. package/examples/route-driver.mjs +67 -0
  165. package/integrations/ai.d.mts +36 -0
  166. package/integrations/ai.mjs +178 -0
  167. package/integrations/call-options.mjs +9 -0
  168. package/integrations/langchain.d.mts +31 -0
  169. package/integrations/langchain.mjs +114 -0
  170. package/integrations/managed.mjs +154 -0
  171. package/integrations/types.d.mts +13 -0
  172. package/package.json +139 -4
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)
@@ -0,0 +1,205 @@
1
+ # Record, replay, explain and correct a handoff
2
+
3
+ The v0.9 additions are documented in [projects and candidate-contract checks](PROJECTS-AND-UPGRADES.md). The v0.8 verification section below is historical evidence of that release.
4
+
5
+ Toolsplice v0.8 introduced these features to its standalone Node.js library and CLI. They require no Cloudflare account, service or runtime. The existing execution path still validates all mapped arguments before the first destination call. No model API or provider call is needed to replay or validate a correction.
6
+
7
+ ## Capture one application-owned run
8
+
9
+ ```ts
10
+ import { writeFile } from 'node:fs/promises';
11
+ import { createSpliceRecorder, explainSpliceError, SpliceError } from 'toolsplice';
12
+
13
+ const recorder = createSpliceRecorder(plan, sourceContract, targetContract, {
14
+ capture: 'payloads',
15
+ redactKeys: ['customerEmail'],
16
+ // Supply known secrets from your own configuration if they can occur in text.
17
+ redactValues: secretValues,
18
+ });
19
+
20
+ try {
21
+ await recorder.run(sourceCaller, targetCaller, input, {
22
+ allowReview: true,
23
+ context: { path: 'saved.md' }, // Only if the plan declares contextSchema.
24
+ });
25
+ } catch (error) {
26
+ if (error instanceof SpliceError) {
27
+ console.error(explainSpliceError(plan, error));
28
+ }
29
+ throw error;
30
+ } finally {
31
+ try {
32
+ await writeFile('/private/app-fixtures/run.json',
33
+ JSON.stringify(recorder.snapshot()), { mode: 0o600, flag: 'wx' });
34
+ } catch {
35
+ // Application telemetry can report that capture/storage failed.
36
+ // Preserve the workflow's original outcome; never retry a write here.
37
+ }
38
+ }
39
+ ```
40
+
41
+ The application supplies contracts, connections and storage. Each recorder captures one invocation; create separate recorders for concurrent runs. A snapshot is available after success or failure and returns detached JSON. Snapshot or filesystem failures are handled separately from the workflow. The library neither creates a recording database nor writes a recording file implicitly. Use an application-selected durable directory or persistence backend when records must survive a server restart. Learning stores retain shape information and remain separate from payload recordings.
42
+
43
+ Capture failures do not retry, change or fail the forwarded workflow. The existing executor's validation failures still stop the workflow at the appropriate boundary. Non-JSON data or exhausted capture budgets mark the artifact incomplete, and incomplete artifacts cannot be replayed. A very small artifact cap may also make `snapshot()` fail when even the metadata cannot fit.
44
+
45
+ ## Privacy and limits
46
+
47
+ - **Default capture is `metadata`.** It retains call names/sides, durations, outcome/path diagnostics and fingerprints. It omits plans, contracts, input/context and request/result payloads. Metadata recordings cannot be replayed.
48
+ - **`capture: 'payloads'` is explicit.** It additionally retains the plan, the selected tools from both contracts, invocation input/context, ordered call arguments and raw MCP responses. These may contain confidential data. Capture only workflows and data your application intends to retain.
49
+ - Common credential field names are redacted case-insensitively, including `password`, `authorization`, `apiKey`, `api_key`, `token`, `access_token`, `refresh_token`, `secret` and `client_secret`. `redactKeys` adds names. These names are checked in captured plans/contracts as well as payloads; a property definition named `token` may therefore also require restoration.
50
+ - `redactValues` wholly redacts any captured string containing a configured secret, including prose/JSON text inside MCP content. If a data object's key contains a configured secret, the enclosing object is redacted so that key is not retained in a redaction path. The policy values themselves are not saved.
51
+ - Redaction is **not guaranteed anonymization**. Unknown secrets, personal data and sensitive field names need an application policy. Names, diagnostic paths and hashes can themselves reveal information. Do not publish recordings merely because credential fields were masked.
52
+ - The artifact cap defaults to **5 MiB** and can be configured from **1 KiB to 5 MiB**. Capture uses an aggregate payload budget as well as a final serialized-artifact check. Bounded plain finite JSON and the existing node/depth limits apply. There are at most 1,001 dispatched source/destination calls in a supported single handoff.
53
+
54
+ A recording fingerprint detects accidental content changes. It is not a signature, encryption or proof that an artifact is trustworthy. Share and load fixtures using your application's access controls.
55
+
56
+ ## Replay entirely offline
57
+
58
+ ```ts
59
+ import { replaySpliceRecording } from 'toolsplice';
60
+ const report = await replaySpliceRecording(savedRecording);
61
+ if (!report.matched) throw new Error('Recorded workflow regression');
62
+ ```
63
+
64
+ ```sh
65
+ node dist/cli.js replay recording.json --json
66
+ node dist/cli.js replay recording.json --out replay-report.json --json
67
+ ```
68
+
69
+ Replay builds the adapter from the saved plan/contracts, using the current guard implementation. It consumes saved raw responses in strict source/destination order and verifies names, arguments and the resulting success/failure outcome. Success compares a canonical result fingerprint. Failure compares stage, acknowledged target count and issue codes/paths. No live caller, server process or connection can be supplied. The API also returns replayed results; the CLI reports their count/byte size and omits their values.
70
+
71
+ A matching **expected failure** is a passing regression test. CLI exit codes are:
72
+
73
+ | Exit | Meaning |
74
+ |---|---|
75
+ | 0 | Replay matched its saved outcome, or correction fixtures all passed |
76
+ | 2 | Replay call sequence, arguments or outcome differed |
77
+ | 1 | Artifact/configuration invalid, incomplete, unrestored or correction validation failed |
78
+
79
+ Metadata and incomplete payload recordings are rejected. For redacted payload recordings, supply every redacted artifact path in an application-owned private restoration object:
80
+
81
+ ```json
82
+ {
83
+ "/input/token": "private replacement supplied locally",
84
+ "/calls/0/arguments/token": "private replacement supplied locally"
85
+ }
86
+ ```
87
+
88
+ ```sh
89
+ node dist/cli.js replay recording.json --restorations private-values.json --json
90
+ ```
91
+
92
+ Only the artifact's listed redaction paths can be replaced; all are required. Restorations are copied into an in-memory artifact and are not written to the report. Restored plans/contracts must still satisfy their fingerprints. Restored fixtures are labelled `restored-fixture`; supplied values are not authenticated as the original values. Treat the restoration file as confidential.
93
+
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
+
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
+
125
+ ## Explain a failed field
126
+
127
+ `explainSpliceError(plan, error)` produces path-only diagnostics. For a destination type error on row 1, it can identify:
128
+
129
+ ```json
130
+ {
131
+ "bindingIndex": 0,
132
+ "targetPointer": "/id",
133
+ "origin": "source",
134
+ "pointer": "/assignee/personId",
135
+ "selectionPointer": "/issues",
136
+ "parsedJson": false,
137
+ "rowIndex": 1
138
+ }
139
+ ```
140
+
141
+ Source pointers are relative to the selected value or fanout row. The selection and explicit JSON parsing are reported separately, so a pointer into parsed JSON is not presented as a pointer into the original raw string. Context origins are labelled separately. Literal bindings identify their origin without including the literal value. Diagnostics never serialize the raw exception cause. Required-property or broad schema errors may implicate several bindings; the report does not invent a uniquely responsible field.
142
+
143
+ Saved fixture failures from `toolsplice splice` include the explanation in JSON and field-origin lines in human-readable output. Replay includes an explanation when it reproduces a `SpliceError`.
144
+
145
+ ## Correct an inaccurate provider declaration explicitly
146
+
147
+ A correction manifest replaces entire selected input/output schemas, pins one exact original snapshot and includes both accepted and rejected fixtures for every replacement:
148
+
149
+ ```json
150
+ {
151
+ "format": "toolsplice-correction",
152
+ "formatVersion": 1,
153
+ "baseFingerprint": "<64-character baseline fingerprint>",
154
+ "reason": "This installation accepts the documented query argument; the saved declaration omits it.",
155
+ "changes": [{
156
+ "tool": "read",
157
+ "side": "input",
158
+ "schema": {
159
+ "type": "object",
160
+ "properties": { "query": { "type": "string" } },
161
+ "required": ["query"],
162
+ "additionalProperties": false
163
+ },
164
+ "fixtures": [
165
+ { "name": "text-query", "valid": true, "value": { "query": "public docs" } },
166
+ { "name": "numeric-query", "valid": false, "value": { "query": 7 } }
167
+ ]
168
+ }]
169
+ }
170
+ ```
171
+
172
+ ```ts
173
+ import { applyContractCorrection, prepareSplice } from 'toolsplice';
174
+ const reviewed = await applyContractCorrection(originalContract, manifest);
175
+ // Original remains unchanged; review the schema comparison and fixture results.
176
+ const adapter = prepareSplice(plan, sourceContract, reviewed.corrected);
177
+ ```
178
+
179
+ ```sh
180
+ node dist/cli.js correct baseline.json --correction correction.json --json
181
+ node dist/cli.js correct baseline.json --correction correction.json \
182
+ --out corrected.json --json
183
+ ```
184
+
185
+ The first command validates and reports; the second additionally writes a **new 0600 file**, refusing to overwrite an existing path. No artifact is written until every replacement's fixtures match their expectations. CLI reports omit fixture values. The corrected contract can be supplied explicitly to `splice --source-contract` or `--target-contract`.
186
+
187
+ The API returns detached `original`, `manifest`, `corrected`, fixture results and the schema comparison. Persist the original and manifest beside the corrected artifact if you need the full review history. Corrected snapshots fingerprint the base and manifest references. Corrected output schemas are labelled `outputSource: 'corrected'`, not provider-declared or learned. Existing uncorrected snapshot fingerprints remain unchanged. Older package versions may reject corrected artifacts; use v0.8+ for these new artifacts.
188
+
189
+ Stale baseline fingerprints, no-op replacements, duplicate tool/side changes, unsupported validators and fixture mismatches reject the correction. There are 1–32 changes and 2–32 fixtures per change, each with at least one expected acceptance and one rejection. `originalValid: null` means the original schema was unknown or could not be guarded; it is not evidence of acceptance. Fixtures test schema behavior only, including for read-only probes previously saved from a real provider. They do not call tools, certify semantics or establish that a live server still behaves the same way.
190
+
191
+ The pinned Firecrawl regression in `test/contract-corrections.test.ts` exercises the previously observed `jsonOptions.schema` mismatch. The replacement admits only the reviewed title-extraction schema form and rejects a numeric-title form. It makes zero Firecrawl requests and consumes no provider credits.
192
+
193
+ ## Run the complete local demonstration
194
+
195
+ ```sh
196
+ npm run demo:handoff
197
+ ```
198
+
199
+ The demo uses two native synthetic MCP servers and writes four new Markdown files into a private demo folder. It records a success and a duplicate-batch failure, shuts down both servers, then replays both through the API and CLI. Replay makes zero tool/network calls and performs no writes. The demo checks five negative compiler assertions, source/context/no-data/collision prevention and offline CLI review. It makes ten native MCP tool calls in the original workflows and zero model calls.
200
+
201
+ ## v0.8 verification
202
+
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.
204
+
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.
@@ -0,0 +1,259 @@
1
+ # Rules, regression tests and mock callers
2
+
3
+ Available since **0.0.2**. These APIs are available in full JS, standalone JS core and native Python. They require no agent framework, provider connection or Cloudflare service.
4
+
5
+ ## First test
6
+
7
+ With the package installed in your application:
8
+
9
+ ```sh
10
+ npx toolsplice init ./handoff
11
+ npx toolsplice test ./handoff
12
+ npx toolsplice test ./handoff --json
13
+ npx toolsplice test ./handoff --junit results.xml
14
+ ```
15
+
16
+ From this source checkout, build first and replace `npx toolsplice` with `node dist/cli.js`. Python uses `python -m toolsplice` for the same commands. The two starter tests expect a valid mapping to succeed and invalid source data to stop before the destination call. Passing both is the intended result.
17
+
18
+ `test` accepts a suite filename or a project directory (reads `tests.json`). The CLI resolves `plan`, `sourceContract` and `targetContract` filenames relative to the suite; references must stay inside that directory, including resolved symlinks. Inline JSON artifacts are also accepted. The library API accepts inline artifacts only. Current file contents are loaded on every run.
19
+
20
+ Exit 0: every case matched. Exit 2: one or more expectations failed. Exit 1: invalid artifacts/configuration, including a contract without the selected tool. Reports include case names, call counts, fingerprints and issue codes/paths; they omit arguments and result payloads. JUnit output creates a new 0600 file and refuses overwrites. `project` separately checks generated adapter freshness.
21
+
22
+ ## Start from two real tools
23
+
24
+ Save the two MCP `tools/list` responses as JSON. To see which tools they contain, run:
25
+
26
+ ```sh
27
+ toolsplice init ./handoff --source-catalog firecrawl.json --target-catalog filesystem.json
28
+ ```
29
+
30
+ Choose an identity and tool for each endpoint. Add a sample to see its JSON pointers and the destination's top-level required fields. Both previews leave the project directory uncreated. Add explicit bindings to create it:
31
+
32
+ ```sh
33
+ toolsplice init ./handoff \
34
+ --source-catalog firecrawl.json --source firecrawl:firecrawl_scrape \
35
+ --target-catalog filesystem.json --target filesystem:write_file \
36
+ --fixture scrape-result.json --fixture-format mcp \
37
+ --bind '/content=/markdown' --set '/path="saved.md"'
38
+ toolsplice test ./handoff
39
+ ```
40
+
41
+ Use `--fixture-format mcp` for a raw tool response. The default expects the decoded JSON value. Repeat `--bind '/destination=/source'` for fields or `--set '/destination=<JSON literal>'` for constants. Supply `--input input.json` to also validate saved source request arguments during the project check.
42
+
43
+ Review the expected arguments in `tests.json` against what the downstream tool should receive. The initializer derives this first expectation from your chosen bindings. Subsequent runs compare against it, using the current `plan.json`, contracts and `fixture.json`. This mapping-only test makes zero source and destination calls. A target response belongs in a separate execution test. Generated projects and tests can contain private sample data.
44
+
45
+ ## Turn a failed run into a test
46
+
47
+ ```sh
48
+ toolsplice test --from-recording failed.json --save-case regression.json
49
+ toolsplice test regression.json
50
+ ```
51
+
52
+ The first command verifies the original replay and runs the generated suite before writing a new private file. A reproduced failure reports its stage, the first recorded issue code and path when available, and the destination call count. The suite pins those expectations and exact recorded destination arguments. Correcting the underlying bug can intentionally turn this expected-failure test red; update the expectation when you adopt the fix. Omit `--save-case` to check reproduction without exporting.
53
+
54
+ Use a complete payload recording. Redacted captures require `--restorations private-values.json`, and the exported suite contains the restored values. A mismatch exits 2. If the source or last destination call threw, the suite reproduces that exception and checks how many calls were attempted and how many results were collected. Cancellation timing and incomplete captures cannot be exported. Choose a new path for the output file.
55
+
56
+ For the JS SDK, call `inspectCatalogMapping(config)` or `await initializeSpliceProject(dir, {catalogs: config})`. The Python equivalents are `inspect_catalog_mapping(config)` and `await initialize_splice_project(dir, catalogs=config)`. Both accept the same JSON configuration:
57
+
58
+ ```js
59
+ const config = {
60
+ source: {server: 'firecrawl', tool: 'firecrawl_scrape'},
61
+ target: {server: 'filesystem', tool: 'write_file'},
62
+ sourceCatalog, targetCatalog, fixture, fixtureFormat: 'mcp',
63
+ bindings: [{to: '/content', from: '/markdown'}, {to: '/path', value: 'saved.md'}],
64
+ };
65
+ ```
66
+
67
+ A `mappingOnly: true` case supplies an empty `input`, a successful raw `sourceResult`, and an expectation with `status: "succeeded"`, `targetCalls: 0`, and exact `arguments`. The CLI also accepts a local decoded `sourceFixture` filename in place of `sourceResult` for these cases. Both CLIs can run each other's mapping and execution suites. The map-only pass covers saved source output and all generated arguments. A call to the generated adapter still applies its normal runtime review and input guards.
68
+
69
+ ## Application rules
70
+
71
+ Schemas establish shape and types. Rules compare values across the handoff. Add this to the plan or inline `defineSplice` / `define_splice` definition:
72
+
73
+ ```json
74
+ {
75
+ "contextSchema": {
76
+ "type": "object",
77
+ "properties": {
78
+ "tenant": { "type": "string" },
79
+ "approvedIds": { "type": "array", "items": { "type": "string" } },
80
+ "maxAmount": { "type": "number" }
81
+ },
82
+ "required": ["tenant", "approvedIds", "maxAmount"]
83
+ },
84
+ "rules": [
85
+ { "id": "same-tenant", "left": { "source": "/tenant" }, "op": "equals", "right": { "context": "/tenant" } },
86
+ { "id": "approved-id", "left": { "mapped": "/id" }, "op": "in", "right": { "context": "/approvedIds" } },
87
+ { "id": "within-limit", "left": { "row": "/amount" }, "op": "lte", "right": { "context": "/maxAmount" } }
88
+ ]
89
+ }
90
+ ```
91
+
92
+ Each operand has exactly one key:
93
+
94
+ | Operand | Value selected |
95
+ |---|---|
96
+ | `source` | Whole decoded source output, before selection or parsing |
97
+ | `row` | Selected/parsed value; an individual item with `forEach` |
98
+ | `mapped` | Completed destination argument object |
99
+ | `context` | Per-invocation application context; requires `contextSchema` |
100
+ | `value` | Literal JSON value |
101
+
102
+ References use JSON pointers. `""` selects the entire value. `equals` compares JSON deeply, ignoring object key order. `in` checks deep membership in the right-hand array. `lte` and `gte` compare numbers. There is no coercion: `false`, `0` and `"0"` differ. A missing field rejects; it is distinct from null.
103
+
104
+ Rules run after source/selected-value and mapped-argument validation, for every row, before **any destination call**. A bad later row therefore prevents all destination dispatch. An empty batch makes no destination calls and runs no per-row rules; use `source.expect` for whole-response flags or `source.valueSchema` with `minItems` when an empty batch should reject.
105
+
106
+ Rule plans have preflight status `review` unless another issue blocks them. Inspect `handoff.report` and pass `allowReview: true` / `allow_review=True` explicitly. This does not disable runtime checks. Rules are application-specified conditions, not authentication or proof of content accuracy. Supply trusted context from the application.
107
+
108
+ Failures use `rule-failed`, `rule-field-missing`, `rule-type-mismatch` or `rule-budget-exceeded`, with a path such as `/rows/1/rules/0`. `explainSpliceError` / `explain_error` adds `ruleId` without operand values. Generated adapters, direct execution, dry runs and replay use the same rules.
109
+
110
+ Limits: 1–32 rules with unique IDs matching `[A-Za-z][A-Za-z0-9_-]{0,63}`; references up to 32 segments; membership arrays up to 1,000 items; encoded operand pair up to 5 MiB; cumulative operand encoding up to 16 MiB per mapping. There are no expression strings, arbitrary callbacks or automatic corrective actions.
111
+
112
+ ## Define an editable suite
113
+
114
+ Starting with the `handoff` from the [JavaScript quickstart](../README.md):
115
+
116
+ ```js
117
+ import { runSpliceSuite } from 'toolsplice';
118
+
119
+ const suite = {
120
+ format: 'toolsplice-suite', formatVersion: 1,
121
+ plan: handoff.plan,
122
+ sourceContract: handoff.sourceContract,
123
+ targetContract: handoff.targetContract,
124
+ allowReview: true,
125
+ cases: [
126
+ {
127
+ name: 'saves the correct document', input: {}, context: { tenant: 'acme' },
128
+ sourceResult: { structuredContent: { tenant: 'acme', text: 'Hello' } },
129
+ targetResults: [{ structuredContent: true }],
130
+ expect: {
131
+ status: 'succeeded', targetCalls: 1,
132
+ arguments: [{ content: 'Hello' }], results: [true],
133
+ },
134
+ },
135
+ {
136
+ name: 'wrong tenant makes zero writes', input: {}, context: { tenant: 'acme' },
137
+ sourceResult: { structuredContent: { tenant: 'other', text: 'Hello' } },
138
+ expect: {
139
+ status: 'failed', stage: 'mapping', targetCalls: 0,
140
+ code: 'rule-failed', path: '/rows/0/rules/0',
141
+ },
142
+ },
143
+ ],
144
+ };
145
+ const report = await runSpliceSuite(suite);
146
+ if (report.failed) throw new Error('Handoff regression');
147
+ console.log(report.passed); // 2
148
+ ```
149
+
150
+ Use your ordinary test runner's assertion on `report.failed`. Python calls `await run_splice_suite(suite)` with the same JSON fields and checks `report["failed"] == 0`.
151
+
152
+ Every case needs a unique name, source input and expected status/target call count. Supply a raw source response unless the source call itself throws. Expected failure also needs a stage. Optional `code` and `path` narrow the failure assertion. Optional `arguments` compares all destination argument objects, in order; `results` checks collected outputs on success. Prefer precise failure assertions so an unrelated error cannot satisfy the test.
153
+
154
+ `targetResults` supplies one raw MCP response per destination call that returns. For a thrown source call, set `transportFailure` to `source` and omit `sourceResult`. For a throw on the last destination call, set it to `target` and include only the earlier returned responses. For example, after one success followed by a disconnect, use `expect.targetCalls: 2`, `expect.completedTargets: 1`, and one entry in `targetResults`. The failing attempt may already have had side effects. `expect.sourceCalls` optionally pins the number of source attempts to 0 or 1. `sourceResult` and `targetResults` are MCP envelopes, not decoded values. Unexpected tool calls fail even if an exception would otherwise satisfy a failure expectation. All cases are parsed before running. Suites are bounded to 100 cases, 1,000 total expected destination calls and 5 MiB of JSON.
155
+
156
+ To check a changed contract:
157
+
158
+ ```js
159
+ const report = await runSpliceSuite(suite, { targetContract: candidate });
160
+ ```
161
+
162
+ ```sh
163
+ npx toolsplice test ./handoff --target-contract candidate.json --json
164
+ ```
165
+
166
+ A matching expected failure is a passing regression. This differs from replay's `upgrade.status`, which only establishes upgrade success from a previously successful capture. Neither verifies every possible provider response.
167
+
168
+ ## Start from a capture
169
+
170
+ ```js
171
+ import { suiteFromRecording, runSpliceSuite } from 'toolsplice';
172
+
173
+ const suite = suiteFromRecording(recording, { name: 'saved document' });
174
+ const report = await runSpliceSuite(suite);
175
+ ```
176
+
177
+ Python: `suite_from_recording(recording, name="saved document")`. This verifies the capture's structure/fingerprints and builds a case with exact saved destination arguments and outcome. Running the suite checks whether it still reproduces. Add negative cases for the assumptions important to your application.
178
+
179
+ Conversion needs complete payloads and explicit private `restorations` for redacted paths. A terminal transport exception becomes a generic mock exception. The fixture checks that execution reaches the failing call and preserves earlier call arguments and counts. Incomplete payloads and cancellation timing prevent conversion. Use [recording and replay](RECORDING-AND-CORRECTIONS.md) for capture details. Be deliberate about storing/sharing suites: they contain fixture payloads.
180
+
181
+ ## Test your application's own workflow
182
+
183
+ Replay reruns the saved Toolsplice handoff. To test your current application code, inject mock callers instead:
184
+
185
+ ```js
186
+ import { mockRecordedCalls } from 'toolsplice';
187
+
188
+ const mocks = mockRecordedCalls(recording);
189
+ await yourWorkflow({ source: mocks.source, target: mocks.target });
190
+ mocks.assertDone();
191
+ ```
192
+
193
+ Python: `mocks = mock_recorded_calls(recording)`, inject `mocks.source` / `mocks.target`, then `mocks.assert_done()`. These callers enforce the original cross-endpoint call order and exact arguments. They do not run your workflow for you. An added call, changed arguments or a missing call fails the test. Deliberately captured transport errors become generic mock exceptions; their original causes/timing are not reproduced.
194
+
195
+ For hand-authored tests:
196
+
197
+ ```js
198
+ import { createMockCaller } from 'toolsplice';
199
+
200
+ const read = createMockCaller([
201
+ { name: 'read', arguments: { id: 'a' }, result: { structuredContent: { text: 'Hello' } } },
202
+ { name: 'read', arguments: { id: 'b' }, throws: true },
203
+ ]);
204
+ // Inject read into the application under test; it consumes steps in order.
205
+ // After the workflow and its expected exception handling:
206
+ read.assertDone();
207
+ ```
208
+
209
+ Omit `arguments` to accept any JSON object; otherwise comparison is exact. `result` and `throws: true` are mutually exclusive. `delayMs` (0–1,000) enables cancellation tests, with AbortSignal in JS and normal asyncio cancellation in Python. Calls reserve their step at entry. Independent mocks do not enforce cross-caller order; use `mockRecordedCalls` when that matters.
210
+
211
+ `getCalls()` / `get_calls()` returns detached attempts; `stats()` reports attempts, consumed, remaining and mismatch. `assertDone()` / `assert_done()` rejects unused steps and remains failed after a mismatch even if your application swallowed its exception. Inputs/results and retained calls are bounded; at most 1,000 scripted steps and 5 MiB of retained call JSON. Mocks cannot establish real provider effects, realistic concurrent scheduling or timing equivalence.
212
+
213
+ ## Check an upgrade against a known baseline
214
+
215
+ Run the saved suite against its original contracts and responses first. Then supply a new raw MCP response, a candidate contract, or both. A one-case suite needs no case selector.
216
+
217
+ ```sh
218
+ toolsplice impact ./handoff --candidate-result fresh-scrape.json
219
+ toolsplice impact ./handoff --source-contract next-source.json --target-contract next-target.json --json
220
+ toolsplice impact ./handoff --case "saves the correct document" --candidate-result fresh-scrape.json
221
+ ```
222
+
223
+ Both runs use local fixtures. Fetch the new response separately using the same source arguments if the goal is to compare provider versions. A changed page can legitimately change the expected destination text.
224
+
225
+ | Status | Interpretation |
226
+ |---|---|
227
+ | `fixtures-pass` | The original and candidate runs satisfy the saved expectations, including at least one expected success. |
228
+ | `regression` | The baseline passes, then a candidate assertion fails or a selected tool is absent from a catalog snapshot marked complete. |
229
+ | `baseline-failed` | The original expectations already fail. The candidate has not been evaluated. |
230
+ | `inconclusive` | Only expected failures were available, a supplied response never reached the handoff, or the selected tool is outside a partial snapshot. |
231
+
232
+ The CLI exits 0 for `fixtures-pass`, 2 for the other verdicts and 1 for invalid input. The report gives case counts, the exact names of the substituted samples, the two test reports and their fingerprints. A mapping-only case checks the source response against the destination arguments. Execution cases also exercise the saved source inputs and mock destination responses. Unused candidate responses appear under `unexercisedSourceResults`.
233
+
234
+ The SDK accepts multiple source responses keyed by case name. Use `await assessSpliceImpact(suite, {sourceResults: {"my case": rawMcpResult}})` in JavaScript or `await assess_splice_impact(suite, source_results={"my case": raw_mcp_result})` in Python. Each response uses the raw MCP envelope. The runner detaches the suite and replacement data.
235
+
236
+ Both `test` and `impact` report the first exact argument or result mismatch in `actual.difference`. The JSON pointer starts at the array of mapped arguments or results, so `/0/content` means the first row's content. An argument mismatch also names the contributing bindings, including their source or context pointers. Reports include field names, difference kinds and mismatched array lengths. Fixture values stay out of the report.
237
+
238
+ ## Return a selected destination field
239
+
240
+ Set `target.resultPath` in the plan when the caller only needs one field from each destination response. For example, a handoff that scrapes a page and returns its canonical URL can use the following destination.
241
+
242
+ ```json
243
+ {"server":"firecrawl","tool":"firecrawl_scrape","resultPath":"/metadata/sourceURL"}
244
+ ```
245
+
246
+ Both SDKs validate the full destination response, then select the field using an RFC 6901 JSON pointer. The returned array contains one selected value per completed destination call. A present JSON null is a valid value. A missing field fails at stage `target` with `target-result-field-missing` and its row path. That destination invocation has already occurred. Later rows are skipped. `maxResultBytes` measures the serialized returned array. Source and destination payload guards still apply to the full responses.
247
+
248
+ For catalog setup, add `--result-path '/metadata/sourceURL'` to the `init` command. A saved mapping-only case exercises destination arguments. Use a captured execution case to pin the final response as well. Generated adapters expose the selected return type where the contract describes it.
249
+
250
+ For several fields, use a map of output names to JSON pointers. This Firecrawl example returns a citation from the scrape metadata.
251
+
252
+ ```json
253
+ {"server":"firecrawl","tool":"firecrawl_scrape","resultFields":{"title":"/metadata/ogTitle","url":"/metadata/sourceURL","revision":"/metadata/git_commit_id"}}
254
+ ```
255
+
256
+ The JS and Python CLIs accept the same map with `--result-fields '{"title":"/metadata/ogTitle","url":"/metadata/sourceURL","revision":"/metadata/git_commit_id"}'`. Use either `resultFields` or `resultPath`. Each alias is required in the returned object. A selected JSON null is preserved. A missing field fails the handoff with its original pointer. The result byte limit includes the names and values in the returned object.
257
+
258
+
259
+ A regression case created from a successful recording now includes `expect.resultFingerprint` when the recording contains one. It compares the returned JSON array with the saved SHA-256 fingerprint. This lets CI catch changes to returned values without duplicating the complete result in the expectation. For editable values and a field-level mismatch, use `expect.results`. Choose one of these two assertions per case. Payload-mode recordings still capture the raw tool responses.
@@ -0,0 +1,11 @@
1
+ // Run from an application that has @modelcontextprotocol/ext-apps and esbuild installed.
2
+ import {build} from "esbuild";
3
+ import {writeFile} from "node:fs/promises";
4
+ import {fileURLToPath} from "node:url";
5
+ const output = process.argv[2];
6
+ if (!output) throw new Error("Pass a new output HTML filename.");
7
+ const entry = fileURLToPath(new URL("./view.mjs", import.meta.url));
8
+ const result = await build({entryPoints:[entry],bundle:true,format:"esm",platform:"browser",write:false,minify:true});
9
+ const script = result.outputFiles[0].text.replace(/<\/script/gi, "<\\/script");
10
+ const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Handoff results</title></head><body><output aria-live="polite">Waiting for results…</output><script type="module">${script}</script></body></html>`;
11
+ await writeFile(output, html, {flag:"wx", mode:0o600});
@@ -0,0 +1,22 @@
1
+ // Bundle with @modelcontextprotocol/ext-apps and serve as the HTML of a ui:// resource.
2
+ import { App } from "@modelcontextprotocol/ext-apps";
3
+
4
+ const app = new App({ name: "Toolsplice results", version: "1.0.0" }, {});
5
+ const output = document.querySelector("output");
6
+ app.ontoolresult = (reply) => {
7
+ const results = reply.structuredContent?.results;
8
+ if (reply.isError || !Array.isArray(results)) {
9
+ output.textContent = "The handoff could not return results.";
10
+ return;
11
+ }
12
+ const list = document.createElement("ol");
13
+ for (const item of results) {
14
+ const row = document.createElement("li");
15
+ row.textContent = typeof item === "string" ? item : JSON.stringify(item);
16
+ list.append(row);
17
+ }
18
+ if (results.length) output.replaceChildren(list);
19
+ else output.textContent = "No results.";
20
+ };
21
+ app.onteardown = async () => ({});
22
+ await app.connect();