toolsplice 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +104 -2
  3. package/dist/abortable.d.ts +6 -0
  4. package/dist/abortable.js +50 -0
  5. package/dist/adaptive-read.d.ts +50 -0
  6. package/dist/adaptive-read.js +780 -0
  7. package/dist/answer-wait.d.ts +7 -0
  8. package/dist/answer-wait.js +45 -0
  9. package/dist/cache-reads.d.ts +18 -0
  10. package/dist/cache-reads.js +89 -0
  11. package/dist/calibration-ledger.d.ts +37 -0
  12. package/dist/calibration-ledger.js +148 -0
  13. package/dist/calibration-marker.d.ts +4 -0
  14. package/dist/calibration-marker.js +77 -0
  15. package/dist/catalog-setup.d.ts +33 -0
  16. package/dist/catalog-setup.js +89 -0
  17. package/dist/catalog.d.ts +10 -0
  18. package/dist/catalog.js +42 -0
  19. package/dist/checkpoint-files.d.ts +15 -0
  20. package/dist/checkpoint-files.js +99 -0
  21. package/dist/cli.d.ts +2 -0
  22. package/dist/cli.js +1454 -0
  23. package/dist/coalesce-reads.d.ts +6 -0
  24. package/dist/coalesce-reads.js +33 -0
  25. package/dist/codegen.d.ts +44 -0
  26. package/dist/codegen.js +479 -0
  27. package/dist/contract-caller.d.ts +23 -0
  28. package/dist/contract-caller.js +326 -0
  29. package/dist/contract-corrections.d.ts +35 -0
  30. package/dist/contract-corrections.js +159 -0
  31. package/dist/contract-schema.d.ts +7 -0
  32. package/dist/contract-schema.js +156 -0
  33. package/dist/contracts.d.ts +72 -0
  34. package/dist/contracts.js +370 -0
  35. package/dist/core.d.ts +44 -0
  36. package/dist/core.js +43 -0
  37. package/dist/db-final-answer.d.ts +9 -0
  38. package/dist/db-final-answer.js +62 -0
  39. package/dist/define.d.ts +78 -0
  40. package/dist/define.js +14 -0
  41. package/dist/doctor.d.ts +22 -0
  42. package/dist/doctor.js +91 -0
  43. package/dist/drift.d.ts +23 -0
  44. package/dist/drift.js +111 -0
  45. package/dist/execution.d.ts +38 -0
  46. package/dist/execution.js +66 -0
  47. package/dist/extract.d.ts +34 -0
  48. package/dist/extract.js +73 -0
  49. package/dist/final-answer-stores.d.ts +71 -0
  50. package/dist/final-answer-stores.js +72 -0
  51. package/dist/final-answer.d.ts +32 -0
  52. package/dist/final-answer.js +104 -0
  53. package/dist/impact.d.ts +48 -0
  54. package/dist/impact.js +71 -0
  55. package/dist/index.d.ts +51 -0
  56. package/dist/index.js +47 -0
  57. package/dist/local-tool.d.ts +18 -0
  58. package/dist/local-tool.js +32 -0
  59. package/dist/mcp-apps.d.ts +53 -0
  60. package/dist/mcp-apps.js +32 -0
  61. package/dist/mcp-event-delivery.d.ts +98 -0
  62. package/dist/mcp-event-delivery.js +211 -0
  63. package/dist/mcp-extensions.d.ts +46 -0
  64. package/dist/mcp-extensions.js +200 -0
  65. package/dist/mcp-peer.d.ts +45 -0
  66. package/dist/mcp-peer.js +207 -0
  67. package/dist/mcp-server-card.d.ts +21 -0
  68. package/dist/mcp-server-card.js +54 -0
  69. package/dist/ordered-transport.d.ts +12 -0
  70. package/dist/ordered-transport.js +106 -0
  71. package/dist/page-checkpoint.d.ts +71 -0
  72. package/dist/page-checkpoint.js +286 -0
  73. package/dist/page-read-gate.d.ts +15 -0
  74. package/dist/page-read-gate.js +48 -0
  75. package/dist/pattern.d.ts +3 -0
  76. package/dist/pattern.js +54 -0
  77. package/dist/postgres.d.ts +41 -0
  78. package/dist/postgres.js +264 -0
  79. package/dist/probe.d.ts +29 -0
  80. package/dist/probe.js +121 -0
  81. package/dist/proxy.d.ts +40 -0
  82. package/dist/proxy.js +436 -0
  83. package/dist/read-pages.d.ts +25 -0
  84. package/dist/read-pages.js +85 -0
  85. package/dist/read-policy.d.ts +6 -0
  86. package/dist/read-policy.js +16 -0
  87. package/dist/read-steps.d.ts +12 -0
  88. package/dist/read-steps.js +36 -0
  89. package/dist/result-session.d.ts +109 -0
  90. package/dist/result-session.js +620 -0
  91. package/dist/route-checkpoint.d.ts +3 -0
  92. package/dist/route-checkpoint.js +80 -0
  93. package/dist/route-driver-cli.d.ts +3 -0
  94. package/dist/route-driver-cli.js +43 -0
  95. package/dist/route-evaluation.d.ts +141 -0
  96. package/dist/route-evaluation.js +329 -0
  97. package/dist/row-groups.d.ts +17 -0
  98. package/dist/row-groups.js +79 -0
  99. package/dist/row-query.d.ts +62 -0
  100. package/dist/row-query.js +172 -0
  101. package/dist/rules.d.ts +30 -0
  102. package/dist/rules.js +72 -0
  103. package/dist/run-diagnostics.d.ts +75 -0
  104. package/dist/run-diagnostics.js +212 -0
  105. package/dist/runtime.d.ts +6 -0
  106. package/dist/runtime.js +26 -0
  107. package/dist/schema.d.ts +17 -0
  108. package/dist/schema.js +299 -0
  109. package/dist/search-fetch.d.ts +50 -0
  110. package/dist/search-fetch.js +264 -0
  111. package/dist/shape.d.ts +91 -0
  112. package/dist/shape.js +499 -0
  113. package/dist/skill-files.d.ts +9 -0
  114. package/dist/skill-files.js +49 -0
  115. package/dist/splice-diagnostics.d.ts +44 -0
  116. package/dist/splice-diagnostics.js +88 -0
  117. package/dist/splice-measure.d.ts +33 -0
  118. package/dist/splice-measure.js +55 -0
  119. package/dist/splice-project.d.ts +125 -0
  120. package/dist/splice-project.js +348 -0
  121. package/dist/splice-recording.d.ts +132 -0
  122. package/dist/splice-recording.js +481 -0
  123. package/dist/splice.d.ts +181 -0
  124. package/dist/splice.js +1263 -0
  125. package/dist/sqlite-checkpoint-store.d.ts +5 -0
  126. package/dist/sqlite-checkpoint-store.js +91 -0
  127. package/dist/sqlite-checkpoint-worker.d.ts +1 -0
  128. package/dist/sqlite-checkpoint-worker.js +115 -0
  129. package/dist/storage.d.ts +17 -0
  130. package/dist/storage.js +1 -0
  131. package/dist/store.d.ts +151 -0
  132. package/dist/store.js +735 -0
  133. package/dist/test-difference.d.ts +13 -0
  134. package/dist/test-difference.js +42 -0
  135. package/dist/testing.d.ts +122 -0
  136. package/dist/testing.js +261 -0
  137. package/dist/text-pages.d.ts +24 -0
  138. package/dist/text-pages.js +36 -0
  139. package/dist/tool-discovery.d.ts +59 -0
  140. package/dist/tool-discovery.js +136 -0
  141. package/dist/unevaluated.d.ts +7 -0
  142. package/dist/unevaluated.js +156 -0
  143. package/dist/v2.d.ts +49 -0
  144. package/dist/v2.js +413 -0
  145. package/dist/validate-output.d.ts +3 -0
  146. package/dist/validate-output.js +73 -0
  147. package/dist/version.d.ts +1 -0
  148. package/dist/version.js +1 -0
  149. package/dist/workflow-json.d.ts +8 -0
  150. package/dist/workflow-json.js +74 -0
  151. package/docs/AGENT-FRAMEWORKS.md +431 -0
  152. package/docs/BENCHMARKS.md +43 -0
  153. package/docs/INTEGRATION-QUICKSTART.md +859 -0
  154. package/docs/LEARNING-AND-STORAGE.md +393 -0
  155. package/docs/MCP.md +204 -0
  156. package/docs/PROJECTS-AND-UPGRADES.md +173 -0
  157. package/docs/PYTHON-REFERENCE.md +348 -0
  158. package/docs/PYTHON.md +120 -0
  159. package/docs/RECORDING-AND-CORRECTIONS.md +205 -0
  160. package/docs/TESTING.md +259 -0
  161. package/examples/mcp-app/build.mjs +11 -0
  162. package/examples/mcp-app/view.mjs +22 -0
  163. package/examples/quickstart.mjs +43 -0
  164. package/examples/route-driver.mjs +67 -0
  165. package/integrations/ai.d.mts +36 -0
  166. package/integrations/ai.mjs +178 -0
  167. package/integrations/call-options.mjs +9 -0
  168. package/integrations/langchain.d.mts +31 -0
  169. package/integrations/langchain.mjs +114 -0
  170. package/integrations/managed.mjs +154 -0
  171. package/integrations/types.d.mts +13 -0
  172. package/package.json +139 -4
@@ -0,0 +1,393 @@
1
+ # Learning, storage and contract reference
2
+
3
+ Supporting infrastructure retained from Callshape. The main Toolsplice workflow is documented in [README](../README.md). Existing `.mcp-shape` storage and `callshape-contract` snapshot identifiers are retained for compatibility.
4
+
5
+ ## Use with Claude Code or Cursor
6
+
7
+ Build once:
8
+
9
+ ```sh
10
+ npm ci
11
+ npm run build
12
+ ```
13
+
14
+ Generate a config for a server you already use:
15
+
16
+ ```sh
17
+ node dist/cli.js config --name my-server --out toolsplice.generated.json -- your-server-command arg1 arg2
18
+ ```
19
+
20
+ Or wrap one existing stdio entry in a config, preserving the other servers, environment variables, working directory, and other settings:
21
+
22
+ ```sh
23
+ node dist/cli.js config --from /path/to/.mcp.json --server my-server --out toolsplice.generated.json
24
+ ```
25
+
26
+ Review the generated file, then put its `mcpServers` entry in Claude Code's project `.mcp.json` or Cursor's `.cursor/mcp.json`. Restart/reconnect the client. Existing config files are never edited; `--out` refuses to overwrite a file. Generated configs use absolute executable and store paths, so the client's working directory does not change where learning is saved. Give different accounts or installations distinct `--name` values.
27
+
28
+ Use tools normally. Once an output is observed, the proxy adds a description such as:
29
+
30
+ ```text
31
+ Returns JSON in the text content (observed; may vary): { id: number; assignee: { login: string } | null }[]
32
+ ```
33
+
34
+ It sends `notifications/tools/list_changed` when the learned description changes, coalescing concurrent updates. Sessions sharing a store also watch for learned description changes from other sessions. Clients decide when to refresh their tool cache; reconnect if a client does not reload descriptions. Repeating the same shape does not send another notification just because the observation count increased.
35
+
36
+ Config formats: [Claude Code](https://code.claude.com/docs/en/mcp), [Cursor](https://cursor.com/docs/mcp). Current [Claude Code documentation](https://code.claude.com/docs/en/mcp#dynamic-tool-updates) describes automatic tool-list refresh on change notifications. Other clients and older versions may need a reconnect. The local client check verifies configuration parsing, not a model-driven session. Change notifications follow the [MCP tools specification](https://modelcontextprotocol.io/specification/2025-11-25/server/tools).
37
+
38
+ ## Inspect the benefit
39
+
40
+ ```sh
41
+ node dist/cli.js doctor --store /absolute/path/to/.mcp-shape
42
+ node dist/cli.js doctor my-server --json
43
+ node dist/cli.js doctor my-server --check
44
+ ```
45
+
46
+ `doctor` reads saved observations; it does not connect to a server or execute any tools. Its categories distinguish useful declared schemas, learned outputs, unobserved tools, unstructured text, and schema warnings. It also reports whether the last TypeScript export is current or stale. Storage artifacts and their owner-process liveness are reported without removing them. `--check` exits 2 for stale exports, schema warnings, unreadable records, or abandoned/unknown storage artifacts, 1 for command/read failures, otherwise 0.
47
+
48
+ ```text
49
+ my-server v1: 18 tools
50
+ 7 already have useful output schemas
51
+ 6 learned return types ready
52
+ 3 need observations
53
+ 2 return text without inferred structure
54
+ 0 have schema/encoding warnings
55
+ TypeScript export: stale
56
+ ```
57
+
58
+ Generate declarations or inspect a learned schema:
59
+
60
+ ```sh
61
+ node dist/cli.js emit-ts my-server --out my-server-tools.d.ts
62
+ node dist/cli.js schema my-server list_records
63
+ node dist/cli.js show my-server
64
+ ```
65
+
66
+ Exports are based on **observations, not guarantees**. New fields, optionality, types, or output encodings mark exported types stale; repeating an unchanged shape does not. A changed server version or tool input/output contract resets its old learning. Up to 20 structural-change events per tool are retained; they contain paths, not returned values.
67
+
68
+ To remove saved learning (no upstream calls):
69
+
70
+ ```sh
71
+ node dist/cli.js forget my-server
72
+ ```
73
+
74
+ ## Proxy options
75
+
76
+ ```sh
77
+ node dist/cli.js proxy --name my-server --store /private/local/store -- your-server-command args
78
+ node dist/cli.js proxy --url https://example.com/mcp --bearer-env MY_MCP_TOKEN
79
+ ```
80
+
81
+ - **Default:** description enrichment, one successful observation, no examples stored.
82
+ - `--enrich none`: observe only; leave tool descriptions unchanged.
83
+ - `--min-samples 3`: wait for three observations before enriching a tool.
84
+ - `--max-description 1000`: cap the extra description length (default 2000 characters).
85
+ - `--upstream-cwd /path`: preserve a server's working directory.
86
+ - `--timeout 30000`: bound each forwarded request. Cancellation and progress are forwarded.
87
+ - `--quiet`: suppress local diagnostics; protocol stdout stays clean either way.
88
+
89
+ Text, images, resources, errors, `_meta`, and structured results pass through unchanged in default mode. Resource/prompt listing and reads, subscriptions, completion, and logging are forwarded when advertised upstream. The proxy does not advertise client roots, sampling, elicitation, or task-extension support; servers that require those client features need another integration. HTTP supports an environment-supplied bearer token; interactive OAuth is not implemented.
90
+
91
+ SDK 1.x has a known progress-callback race when a stdio notification and its result arrive in one pipe read. The proxy uses an ordered receive wrapper on its upstream connection. Applications controlling their own SDK 1.x client can also use `await client.connect(orderedTransport(transport))` after importing `orderedTransport` from `toolsplice`. This changes no wire data and adds no pings or timing sleeps. It cannot change an existing host's internal SDK; the proxy can forward a progress message correctly even if that host loses the callback. Deterministic upstream-only reproductions are opt-in tests in `test/http.test.ts`.
92
+
93
+ `--enrich schema` is experimental and changes results by adding `structuredContent` for learned object outputs. A future result can violate the previously announced schema: it is withdrawn for later calls, but a strict client may reject that first changed result. Use description mode for ordinary agent traffic.
94
+
95
+ ## Current SDK clients (optional HTTP adapter)
96
+
97
+ The CLI proxy uses the maintained SDK 1.x and negotiates protocols through `2025-11-25`. For an application using the split SDK 2.x packages and the `2026-07-28` protocol, an optional HTTP fetch middleware is exported separately:
98
+
99
+ ```ts
100
+ import { Client, StreamableHTTPClientTransport, applyMiddlewares } from '@modelcontextprotocol/client';
101
+ import { ShapeStore } from 'toolsplice';
102
+ import { createV2Adapter } from 'toolsplice/v2';
103
+
104
+ const client = new Client({ name: 'my-agent', version: '1' }, {
105
+ versionNegotiation: { mode: { pin: '2026-07-28' } },
106
+ });
107
+ const learner = createV2Adapter({
108
+ store: new ShapeStore('/private/local/store'),
109
+ serverName: 'my-endpoint-and-account',
110
+ onChanged: async () => { await client.listTools(undefined, { cacheMode: 'refresh' }); },
111
+ });
112
+ await client.connect(new StreamableHTTPClientTransport(new URL('https://example.com/mcp'), {
113
+ fetch: applyMiddlewares(learner.middleware)(fetch),
114
+ }));
115
+ // Use client.listTools()/callTool() normally.
116
+ // On shutdown:
117
+ await client.close();
118
+ learner.dispose();
119
+ ```
120
+
121
+ This path is tested with the real SDK 2.3.1 and a local SDK 2.x server, including JSON and SSE responses, progress, output recording, and cache refresh. It leaves `input_required` challenges unobserved and unchanged. The SDK retains responsibility for auth and interactive round trips. Use one adapter per endpoint/principal; it is not a replacement HTTP proxy or a stdio adapter. Responses beyond the observation budget pass through without learning.
122
+
123
+ ## What it learns
124
+
125
+ - JSON types, unions, nullability, observed field presence, and optional properties.
126
+ - String formats, likely Unix timestamps, and maps keyed by IDs or dates.
127
+ - JSON hidden inside a string, with parsing instructions and its inner shape.
128
+ - Recursive trees when enough nesting has been observed.
129
+ - JSON/text fallback encodings, plus declared schemas that fail to deliver structured output.
130
+ - Structural mismatches in delivered structured results. This diagnostic does not run upstream regex constraints, validate every format, or fetch external schema references.
131
+
132
+ Always-null fields stay `unknown` until a value is observed. Large, deep or heterogeneous outputs have bounded inference/rendering work and a default 10,000 retained-shape-node limit per tool. Unsampled array tails remain unknown; descriptions retain the sampled item shape as a clearly marked hint. Other exhausted branches can also produce `unknown`. It does not invent parsers for arbitrary prose, automatically map fields between unrelated tools, or choose and execute a tool chain for you.
133
+
134
+ Small observed value sets and examples are available only with `--examples safe` or `--examples all`. `safe` is a heuristic, not a privacy guarantee.
135
+
136
+ ## Privacy and persistence
137
+
138
+ The default `--examples none` keeps no learned string/numeric examples, enum candidates, raw text/error samples, or prefixes. Switching from a permissive policy also removes previously retained examples. **Field names, counts, string lengths/formats, numeric ranges, server descriptions, and declared schemas are still stored.** Those can contain sensitive information; this is local learning, not anonymization. Requests and raw responses are not saved as transcripts. File-backed findings stay in the chosen local folder. Selecting PostgreSQL sends retained findings to your configured database. Enriched descriptions are returned to the MCP client.
139
+
140
+ New store directories use private permissions; writes are atomic and files are owner-readable/writable. Shared sessions update the latest record under a writer lock. A corrupt record is preserved and diagnosed rather than overwritten. Recording failures are best effort: tool forwarding continues, with a stderr diagnostic. A crashed writer's lock requires inspection/removal; active locks are never automatically deleted. Use an absolute private `--store` path outside your repository, or exclude `.mcp-shape/` from version control.
141
+
142
+ ## Choose storage
143
+
144
+ File storage remains the default. Select its folder with `--store /data/toolsplice` or `new ShapeStore('/data/toolsplice')`. In a container, mount persistent storage at that path. Generated configurations resolve file paths to absolute paths. File contention tests run on one host; shared network-filesystem locking across hosts has not been validated.
145
+
146
+ For replicas sharing learning, select the optional PostgreSQL backend instead. It stores findings in the database and needs no local findings folder. PostgreSQL manages its own durable storage and backups.
147
+
148
+ ```sh
149
+ # Make this variable available to the proxy through your process manager,
150
+ # Kubernetes Secret or MCP client's environment configuration.
151
+ # CALLSHAPE_DATABASE_URL contains your PostgreSQL connection URL.
152
+ node dist/cli.js config --name my-server \
153
+ --database-env CALLSHAPE_DATABASE_URL --namespace my-project \
154
+ --out toolsplice.generated.json -- your-server-command args
155
+
156
+ node dist/cli.js doctor my-server \
157
+ --database-env CALLSHAPE_DATABASE_URL --namespace my-project
158
+ ```
159
+
160
+ Use those same storage flags for `proxy`, `probe`, `show`, `schema`, `emit-ts` and `forget`. `--store` and `--database-env` are mutually exclusive. Config generation needs no database connection and includes the environment-variable name, never the URL read from it. The selected database variable is removed from the spawned upstream server's environment; use a dedicated variable for learning storage. Existing environment entries copied with `--from` remain in the generated configuration.
161
+
162
+ `--database-timeout <ms>` sets PostgreSQL connection/pool-wait, lock and statement deadlines independently of the upstream MCP `--timeout`. The range is 50–60,000 ms, default 1,000; generated database configs retain an explicit setting. For example, add `--database-timeout 5000` for a workload that legitimately queues writers. Library users set `timeoutMs` on `PostgresShapeStore`. This does not add retries or change commit uncertainty. Known driver/SQLSTATE failures produce sanitized categories for connection/query deadlines, cancellation, locks, authentication and privileges; raw SQL, driver messages, URLs and credentials are not retained in those storage errors.
163
+
164
+ The `pg` driver is an optional dependency. If installing with `--omit=optional`, file storage and the HTTP adapter still work; install `pg` separately before using PostgreSQL. Library use:
165
+
166
+ ```ts
167
+ import { createProxy } from 'toolsplice';
168
+ import { PostgresShapeStore } from 'toolsplice/postgres';
169
+
170
+ const store = new PostgresShapeStore({
171
+ connectionString: process.env.CALLSHAPE_DATABASE_URL!,
172
+ namespace: 'my-project',
173
+ // migrate: false, // runtime role after schema provisioning
174
+ // timeoutMs: 1000, // connection, statement and lock timeouts
175
+ // maxConnections: 4, // per store instance
176
+ // pollIntervalMs: 1000, // legacy proxy shared-description refresh
177
+ });
178
+ const proxy = await createProxy(upstreamTransport, { store, serverName: 'my-endpoint-and-account' });
179
+ await proxy.server.connect(downstreamTransport);
180
+ // On shutdown, stop all users of this store before closing its pool:
181
+ await proxy.close();
182
+ await store.close();
183
+ ```
184
+
185
+ The same store works with `probe` and `createV2Adapter`. Applications own store lifetime; closing one proxy does not close a store that another proxy may share. Custom backends can implement the exported `LearningStore` interface, whose methods accept synchronous or asynchronous implementations. Transaction mutators must remain synchronous and free of external effects.
186
+
187
+ PostgreSQL transactions serialize updates and deletes against the latest committed record, including the first insert. Connection-scoped process failures release transaction locks automatically. Default example policy and inference limits are the same as file storage. Versioned schema provisioning runs lazily on first use (or explicitly with `await store.initialize()`). Future schema versions are rejected. Existing file findings are **not** imported automatically.
188
+
189
+ By default, provisioning needs permission to create `public.mcp_shape_schema`, `public.mcp_shape_records` and `public.mcp_shape_revision`. For production, provision once with a migration role, then use `--no-migrate` / `migrate: false` with a runtime role. Typical runtime grants, applied by your DBA:
190
+
191
+ ```sql
192
+ GRANT USAGE ON SCHEMA public TO runtime_role;
193
+ GRANT SELECT ON public.mcp_shape_schema TO runtime_role;
194
+ GRANT SELECT, INSERT, UPDATE, DELETE ON public.mcp_shape_records TO runtime_role;
195
+ GRANT USAGE, SELECT ON SEQUENCE public.mcp_shape_revision TO runtime_role;
196
+ ```
197
+
198
+ Namespaces separate project records; they are **not** a database authorization boundary. Use database roles/databases for access isolation. Namespace names allow up to 256 UTF-8 bytes and server identities up to 512 bytes. Configure TLS and database access through your connection URL and normal database deployment controls.
199
+
200
+ Idle legacy proxies poll revisions to refresh shared descriptions; the default interval is one second. During an outage, recording remains best effort and tool results still pass through. Failed observations are not durably queued or replayed, and an uncertain commit is never automatically retried. Later calls reconnect through the pool. No fallback files are created.
201
+
202
+ ## Optional probing
203
+
204
+ You do not need to probe before using the proxy. To learn without ordinary agent traffic, `probe` calls tools the server marks read-only and for which it can construct arguments:
205
+
206
+ ```sh
207
+ node dist/cli.js probe --name my-server --args calls.json -- your-server-command args
208
+ ```
209
+
210
+ ```json
211
+ { "list_records": [{ "project": "demo" }] }
212
+ ```
213
+
214
+ Annotations are upstream hints. Explicit calls in `--args` may write data; list only calls you intend to run. Probing does not use an LLM.
215
+
216
+ ## Library use
217
+
218
+ ```ts
219
+ import { ShapeStore, createProxy, diagnose } from 'toolsplice';
220
+
221
+ const store = new ShapeStore('/private/local/store');
222
+ const proxy = await createProxy(upstreamTransport, { store, serverName: 'my-server' });
223
+ await proxy.server.connect(downstreamTransport);
224
+ // Later:
225
+ const report = diagnose(store.load('my-server'));
226
+ await proxy.close();
227
+ ```
228
+
229
+ `toolFunctions(client, names)` exposes async functions that decode results the same way the exported types describe: structured content, otherwise JSON parsed from text, otherwise text. This can be used in an existing code-mode runtime. It is not itself an execution sandbox.
230
+
231
+ ## Generate callable TypeScript bindings
232
+
233
+ After a tool has been observed, generate a `.ts` source module:
234
+
235
+ ```sh
236
+ node dist/cli.js emit-ts my-server --runtime --out my-server-tools.ts
237
+ ```
238
+
239
+ Compile the generated module with your application. For server `my-server`, it exports `MyServerTools` and `createMyServerTools`:
240
+
241
+ ```ts
242
+ import { createToolCaller } from 'toolsplice';
243
+ import { createMyServerTools } from './my-server-tools.js';
244
+
245
+ // client is an already-connected MCP SDK 1.x Client.
246
+ const tools = createMyServerTools(createToolCaller(client));
247
+ // tools now has the server's actual methods, input types, and learned return types.
248
+ ```
249
+
250
+ For example, the offline demo generates `createIssuesTools` and `createPeopleTools`:
251
+
252
+ ```ts
253
+ const issues = createIssuesTools(createToolCaller(issueClient));
254
+ const people = createPeopleTools(createToolCaller(peopleClient));
255
+ const open = await issues.list_issues({ state: 'open' });
256
+ const summary = await Promise.all(open.map(async issue => {
257
+ const owner = await people.get_person({ id: issue.assignee.personId });
258
+ return { issue: issue.id, owner: owner.person.name };
259
+ }));
260
+ ```
261
+
262
+ Methods accept a second options argument:
263
+
264
+ ```ts
265
+ const abort = new AbortController();
266
+ const request = issues.list_issues({ state: 'open' }, {
267
+ signal: abort.signal,
268
+ timeoutMs: 30_000,
269
+ onProgress: progress => console.log(progress.progress, progress.total),
270
+ });
271
+ // Call abort.abort() to cancel; await request to consume the result or error.
272
+ ```
273
+
274
+ `createToolCaller(client, defaults)` accepts the same default options. Timeouts default to 120 seconds; use a positive integer of at most 2,147,483,647 milliseconds. Cancellation and progress use the SDK protocol. For SDK 1.x progress delivery, connect the client with `orderedTransport(transport)`; this helper addresses a known callback-ordering race and is used in the demo.
275
+
276
+ For an already-connected SDK 2.x client, use the same generated factory with `createV2ToolCaller(client)` from `toolsplice/v2`. This helper requires no SDK 2.x runtime dependency in Toolsplice. Existing HTTP learning middleware remains a separate `createV2Adapter` integration.
277
+
278
+ Bindings prefer `structuredContent`, otherwise decode JSON from text (including a short prose prefix), otherwise return text. An MCP `isError` result throws `ToolError`, whose `tool` identifies the method. SDK transport, timeout, and cancellation errors propagate unchanged. Interactive/deferred results require direct SDK handling and are rejected by these completion-only bindings.
279
+
280
+ Types describe declared inputs and observed/declared outputs; **generated bindings do not validate them at runtime by default**. Opt into a reviewed contract guard below when runtime checks are needed. An unobserved output stays `unknown`. Re-export after learning changes and use `doctor --check` to detect stale exports. Bindings do not create an agent execution sandbox, authenticate clients, or persist intermediate workflow results.
281
+
282
+ Library generation is also available:
283
+
284
+ ```ts
285
+ import { emitBindings } from 'toolsplice';
286
+ const source = emitBindings(await store.load('my-server'), {
287
+ interfaceName: 'MyServerTools',
288
+ });
289
+ // Save source to a .ts file in your application.
290
+ ```
291
+
292
+ `emitModule` and `emit-ts` without `--runtime` still generate declaration-only interfaces. `emitBindings` also accepts `runtimeImport` for a custom runtime module specifier; the default is `toolsplice`.
293
+
294
+ ## Review a contract and check it in CI
295
+
296
+ Create a baseline from saved learning, review it, and commit it with your application:
297
+
298
+ ```sh
299
+ node dist/cli.js snapshot my-server --out contracts/my-server.json
300
+ node dist/cli.js check my-server --baseline contracts/my-server.json --json
301
+ ```
302
+
303
+ The output folder must already exist. `snapshot --out` refuses to overwrite a file. Write a new candidate file and review its diff when you intentionally accept a change; checks never update the baseline. To select just the tools your workflow uses, repeat `--tool`:
304
+
305
+ ```sh
306
+ node dist/cli.js snapshot my-server --tool list_issues --tool get_issue --out contracts/issues.json
307
+ ```
308
+
309
+ These commands read the file/PostgreSQL learning store and make **no upstream calls**. CI needs current observations in its selected store; an unchanged old store cannot detect an upstream deployment change. Use ordinary integration traffic or explicitly configured disposable probe calls to refresh it first. `doctor` helps identify unobserved, limited or mismatched schemas before review. A baseline is a reviewed snapshot of evidence, not a provider commitment or a recorded request/response test suite.
310
+
311
+ `check` exits 0 for an unchanged contract, 2 for a policy failure, and 1 for invalid input/storage errors. By default, **any** contract change fails. `--fail-on breaking` allows changes classified as additive; it still fails changes labeled `review`, including unsupported compatibility cases. Version, encoding, tool annotation and inference-limit changes require review. Removed tools, newly required inputs and weakened output presence are examples of potential breaks. JSON-pointer paths identify changes without copying response values into reports. Reports cap at 500 changes; truncation always fails.
312
+
313
+ Drift checks track changes to declared assertions, including numeric and string bounds. Counters, timestamps, learned numeric ranges, samples, prose descriptions and schema annotations do not cause routine drift. Conservative labels cover simple structural changes; arbitrary JSON Schema compatibility and behavioral/semantic equivalence are not solved. Check defaults should be kept unless you have reviewed the narrower policy for your application.
314
+
315
+ Snapshots contain field names, schemas, server identity/version, tool annotations, observation counts and inference-limit flags. Returned examples and learned value lists are omitted. **Declared `const`/`enum` values and other constraints remain**, because changing them changes the contract; review snapshots before committing. The fingerprint detects accidental modification and ignores traffic counts. It is not a signature, identity attestation, or proof of human approval. Snapshot files are portable inspection artifacts; importing them does not populate or replace the learning database.
316
+
317
+ ## Guard a tool chain at runtime
318
+
319
+ Use the same baseline with a connected client:
320
+
321
+ ```ts
322
+ import { readFile } from 'node:fs/promises';
323
+ import { parseContractSnapshot, createContractCaller, createToolCaller } from 'toolsplice';
324
+ import { createMyServerTools } from './my-server-tools.js';
325
+
326
+ const baseline = parseContractSnapshot(await readFile('contracts/my-server.json', 'utf8'));
327
+ const caller = createContractCaller(createToolCaller(client), baseline);
328
+ const tools = createMyServerTools(caller);
329
+ ```
330
+
331
+ For SDK 2.x, wrap `createV2ToolCaller(client)` instead. Guarding is opt-in and independent of the transparent proxy. The guard checks declared inputs before dispatch and decoded outputs after the tool runs, then returns the raw successful MCP result unchanged for the binding to decode. An invalid first result cannot feed the next tool. Output checks cannot undo effects of a tool that already ran. No retries or automatic baseline updates occur.
332
+
333
+ A `ContractValidationError` carries `tool`, `stage` (`input`, `output`, or `contract`) and `issues` containing paths/keywords, without response values. SDK/transport/abort errors retain their identity; MCP `isError` results keep normal `ToolError` behavior in generated bindings. Cancellation/progress options pass through. Unfinished interactive/deferred results remain the SDK's responsibility. Unknown tool names fail before dispatch.
334
+
335
+ Select observed tools or tools with declared output schemas before constructing a guard: unknown outputs fail setup. Partial inferred branches remain unconstrained; validation cannot invent missing knowledge. `createContractCaller(caller, baseline, { inputs: false })` or `{ outputs: false }` explicitly disables that stage; unknown tool names still fail. Use finite, plain JSON arguments and omit absent optional fields rather than setting them to `undefined`.
336
+
337
+ The guard supports a bounded structural subset of JSON Schema 2020-12 (default) and explicitly declared Draft 7. It checks types, properties, presence, numeric/length bounds, enums/consts, combinations and local pointer references. It evaluates a bounded ASCII regex subset with the non-backtracking RE2JS engine and validates `propertyNames`. It does not fetch external references, coerce values, insert defaults or remove fields. Patterns are limited to 1,024 characters and 64 per input/output schema. The supported subset includes ASCII literals, positive ASCII character classes, grouping, alternation, anchors, quantifiers, and `\d`/`\w`/basic control-character escapes. Outside a character class, `\s` matches the ECMAScript whitespace and line terminators, including nonbreaking space and BOM. Wildcard dots, negated classes, Unicode patterns, whitespace shorthands inside character classes, lookaround and backreferences fail setup; these are not silently ignored. The restricted grammar avoids differing ECMA-262/RE2 matching semantics. `format` and `content*` are treated as annotations. Unsupported assertion keywords/dialects, nested schema resources and Draft 7 `$ref` siblings with assertions fail setup. Because Ajv ignores `__proto__` schema property definitions, those definitions are rejected explicitly; tool names themselves are dictionary keys and remain supported.
338
+
339
+ Schemas are **trusted reviewed configuration**, not an arbitrary-schema sandbox. Per-schema checks allow 5,000 nodes and depth 32; JSON data allows 50,000 nodes and depth 64, with a 5 MiB string budget. Snapshots allow 50,000 nodes/depth 64 and a 5 MiB file limit. `uniqueItems: true` requires `maxItems <= 1000`. Invalid or excessive structures fail the opt-in guard. These bounds and the supported subset can reject otherwise valid large/complex servers; they do not establish a general CPU-time bound for every trusted schema.
340
+
341
+ Library equivalents are `createContractSnapshot(server, { tools: [...] })`, `compareContractSnapshots(before, after)` and `contractCheckFailed(report, 'any' | 'breaking')`.
342
+
343
+ ## Where this fits
344
+
345
+ Code-based tool composition already exists. [Cloudflare Code Mode](https://developers.cloudflare.com/agents/model-context-protocol/codemode/) runs code against MCP tools and keeps intermediate results outside model context. [smolagents](https://huggingface.co/docs/smolagents/en/tutorials/tools) consumes output schemas and parses structured results. [FastMCP](https://github.com/PrefectHQ/fastmcp/blob/main/docs/servers/tools.mdx) generates output schemas from a server function's return annotation.
346
+
347
+ Sample-based type inference is established too: [quicktype](https://quicktype.io/) generates types from JSON samples. [mcp-infer](https://github.com/Emilthelucky/mcp-infer/blob/main/ROADMAP.md) describes deriving MCP definitions from typed TypeScript source at build time. These are related approaches; the integration and learning lifecycle are the focus here.
348
+
349
+ Toolsplice focuses on a narrower gap: learning useful output descriptions from successful traffic when a server has missing schemas, JSON inside text, or changing output shapes. It can supply observations to an existing code-mode workflow. If you own the server, a maintained declared output schema is preferable to inference; if its schema already explains the result adequately, learning may add little value. This is not a claim of complete uniqueness.
350
+
351
+ Learning itself makes no LLM calls. Enriched descriptions add prompt tokens and local recording adds overhead; whether they reduce total cost or improve accuracy depends on the task and client. The checks below establish correctness and durability. The earlier model experiment is limited evidence about agent performance, not a general savings guarantee.
352
+
353
+ ## Next product priorities
354
+
355
+ v0.5.0 adds reviewed snapshots, CI checks, opt-in runtime guards and a demo that proves invalid output cannot feed dependent calls. Callable bindings, SDK adapters and offline composition shipped in v0.4.0. Next priorities:
356
+
357
+ 1. **Prove one real workflow.** Integrate with an existing agent code-execution environment and measure success, turns, total latency and tokens on a representative task. The synthetic demo proves composition works; it does not establish model savings. Build a Python integration after the first TypeScript integration is useful in practice.
358
+ 2. **Portable, validated learning export/import.** Move findings between file storage and PostgreSQL with a dry run, explicit identities and conflict handling. Default to omitting example values. Do not overwrite live learning silently.
359
+ 3. **Per-tool learning controls and retention.** Let deployments exclude tools/fields, expire stale findings, and inspect what metadata will persist before enabling learning.
360
+
361
+ The first product milestone is one real workflow where a developer can explain how Toolsplice helped. Agent accuracy, turns, latency and total token cost need task-level measurement; more infrastructure alone does not establish those benefits. Paid model benchmarks remain separately opt-in.
362
+
363
+ ## Testing
364
+
365
+ ```sh
366
+ npm test # deterministic unit, CLI and local HTTP/protocol tests; no LLM calls
367
+ npm run typecheck
368
+ npm run test:demo # compiles and executes the offline two-server workflow
369
+ npm run test:real # installs pinned reference servers into a disposable directory
370
+ node scripts/verify-package.mjs # packs, installs and exercises a clean consumer
371
+ npm run test:soak -- --seconds 60 --out /tmp/soak.json
372
+ npm run test:contracts:soak -- --seconds 60 --out /tmp/contracts-soak.json
373
+ npm run test:processes -- 500 # 1,000 calls across two independent CLI processes
374
+ # PostgreSQL tests require a disposable database:
375
+ MCP_SHAPE_TEST_DATABASE_URL=... npm run test:postgres
376
+ # Or launch a disposable native PostgreSQL cluster (needs initdb + postgres):
377
+ MCP_SHAPE_PG_BIN=/path/to/pg/bin npm run test:postgres:local
378
+ ```
379
+
380
+ Real-server smoke tests use official filesystem and memory servers with disposable data. The package check does not publish anything. The soak exercises shared sessions, evolving outputs, reconnects, exact observation counts and bounded drift history.
381
+
382
+ ## Earlier model experiment
383
+
384
+ The prototype was evaluated on 13 output-shape-dependent questions, with two trials per arm, using one issue-tracker fixture and the official filesystem server. Models could inspect results before answering. The historical run used the earlier example policy and implementation; it is not a benchmark of every v0.2.0 change.
385
+
386
+ | Model | Approach | Solved | Average turns | Median seconds |
387
+ |---|---|---|---|---|
388
+ | Haiku 4.5 | Parsed results, no output types | 58% | 4.35 | 36.4 |
389
+ | | Full learned types | 81% | 3.15 | 15.3 |
390
+ | Sonnet 5.5 | Parsed results, no output types | 100% | 3.46 | 17.3 |
391
+ | | Full learned types | 100% | 2.54 | 10.1 |
392
+
393
+ Fewer turns and lower median time held up in this small experiment. The accuracy difference did not reach statistical significance; cost savings were inconclusive. One-line descriptions got much of the benefit of full declarations. These tasks were chosen to depend on output shapes and do not establish average savings on arbitrary work. Raw runs and superseded protocols are retained under `bench/results/` for inspection. Paid model benchmarks are optional and are not run by any test command above.
package/docs/MCP.md ADDED
@@ -0,0 +1,204 @@
1
+ # MCP protocol support
2
+
3
+ The current core revision is `2026-07-28`. It uses per-request metadata, `server/discover`, discriminated result types and explicit cache policies. Existing clients can continue using their negotiated older revision. [Version policy](https://modelcontextprotocol.io/docs/2026-07-28/learn/versioning) · [Core changes](https://modelcontextprotocol.io/specification/2026-07-28/changelog)
4
+
5
+ ## Add an MCP App to a handoff
6
+
7
+ An App-enabled handoff exposes a tool and an HTML resource on the same server. The model can call the tool once and read its ordinary fallback. An Apps host can also request the resource and render the structured result in the view. [MCP Apps specification](https://modelcontextprotocol.io/extensions/apps/overview)
8
+
9
+ ```js
10
+ import { readFile } from 'node:fs/promises';
11
+ import { createMcpAppResource } from 'toolsplice';
12
+
13
+ const view = createMcpAppResource({
14
+ uri: 'ui://documents/results.html',
15
+ name: 'Document results',
16
+ html: await readFile('view.html', 'utf8'),
17
+ ui: { prefersBorder: true },
18
+ });
19
+ const tool = handoff.asTool({ name: 'lookup', source, target, ui: view.toolUi });
20
+ ```
21
+
22
+ Return `tool.definition` from your server's `tools/list`, call `tool.call(arguments, options)` in its `tools/call` handler, and return `view.read(uri)` from `resources/read` for the registered URI. A `resources/list` entry is available as `view.definition`. Set the server's tools, resources and `io.modelcontextprotocol/ui` capabilities using your SDK.
23
+
24
+ ```python
25
+ from pathlib import Path
26
+ from toolsplice import create_mcp_app_resource
27
+
28
+ view = create_mcp_app_resource(
29
+ uri="ui://documents/results.html", name="Document results",
30
+ html=Path("view.html").read_text(encoding="utf-8"),
31
+ ui={"prefersBorder": True},
32
+ )
33
+ tool = handoff.as_tool(name="lookup", source=source, target=target, ui=view.tool_ui)
34
+ ```
35
+
36
+ Python SDK 1.x's low-level `Server.read_resource()` decorator expects a sequence of `ReadResourceContents` objects. Preserve both MIME type and resource metadata when adapting the response.
37
+
38
+ ```python
39
+ from mcp.server.lowlevel.helper_types import ReadResourceContents
40
+
41
+ @server.read_resource()
42
+ async def read_resource(uri):
43
+ item = view.read(str(uri))["contents"][0]
44
+ return [ReadResourceContents(
45
+ content=item["text"], mime_type=item["mimeType"], meta=item.get("_meta")
46
+ )]
47
+ ```
48
+
49
+ Tool linkage uses `_meta.ui.resourceUri`. Resource policy belongs to `contents[0]._meta.ui` on the read response, where an Apps host enforces CSP and requested permissions. Provide a bundled view owned by your application. A handoff returns the selected data to that view. The host controls sandboxing and visibility. Use `{...view.toolUi, visibility: ["app"]}` for a tool intended for this server's App. Enforce access control in the server handler.
50
+
51
+ The default resource read policy is `ttlMs: 0` and `cacheScope: "private"`. Configure a public cache explicitly for a shareable static asset. Composite tool success and error replies carry `resultType: "complete"`.
52
+
53
+ ### Try the example view
54
+
55
+ Copy the two files in `examples/mcp-app` into your Node project, install the official view SDK and bundler, and build one HTML file. Python servers can serve the same built file.
56
+
57
+ ```sh
58
+ npm install @modelcontextprotocol/ext-apps
59
+ npm install --save-dev esbuild
60
+ node examples/mcp-app/build.mjs view.html
61
+ ```
62
+
63
+ The view uses the official App handshake, shows each selected handoff result as text, and handles teardown. The server libraries have no browser or Apps SDK runtime dependency.
64
+
65
+ ## Discover an upstream
66
+
67
+ Install the optional current client alongside Toolsplice. JavaScript uses `npm install toolsplice @modelcontextprotocol/client@^2.3`. Python uses `pip install 'toolsplice[mcp2]'`. Use a separate environment when an existing application depends on MCP SDK 1.x.
68
+
69
+ ```sh
70
+ toolsplice discover --url https://mcp.firecrawl.dev/v2/mcp
71
+ toolsplice discover --with-tools --url https://mcp.firecrawl.dev/v2/mcp --out firecrawl.json
72
+ toolsplice catalog --modern --url https://mcp.firecrawl.dev/v2/mcp --out catalog.json
73
+ toolsplice discover --timeout 10000 -- python my_server.py
74
+ ```
75
+
76
+ Both CLIs negotiate the protocol with the upstream. The discovery report includes the negotiated revision, server identity, capabilities, extension settings and available cache hints. Older servers can answer through the SDK's `initialize` fallback. Supply `--bearer-env MCP_TOKEN` to read an HTTP bearer token from the process environment. Catalog discovery calls zero upstream tools.
77
+
78
+ Add `--with-tools` to save the complete paginated tool list alongside the discovery report. Use that same file as `--source-catalog` or `--target-catalog` in `toolsplice init`. Plain `discover` reads capabilities with zero tool listings. Both CLIs enforce the catalog byte limit and reject repeated pagination cursors before saving a file.
79
+
80
+ ### Catch upstream changes while a service runs
81
+
82
+ ```sh
83
+ toolsplice impact ./document-handoff --follow target --url "$TARGET_MCP_URL"
84
+ ```
85
+
86
+ The command subscribes to tool list changes, waits for the upstream to acknowledge the subscription, then checks the current catalog against your saved cases. Each change triggers a fresh listing and an offline replay. A failed check prints the case and field and exits with status 2. The replay makes zero source or destination calls. Use `--follow source` to watch the source schema. Add `--json` for one report per line or `--max-reports 1` to stop after the initial check.
87
+
88
+ This mode requires the current MCP client and a server advertising `tools.listChanged` on the July protocol. A lost subscription exits with status 1. Restarting the command subscribes again and checks the catalog as it exists then. MCP list-change notifications have no replay cursor. [MCP subscriptions](https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/subscriptions)
89
+
90
+ For an already connected official client, pass `createV2ToolCaller(client)` from `toolsplice/v2` or `create_v2_tool_caller(client)` in Python as the source or target caller of a handoff. Keeping the client instance preserves its OAuth provider, per-principal cache, progress and transport settings. Prime its tools catalog before using `x-mcp-header` argument mirroring. [HTTP transport](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http)
91
+
92
+ ## Resume interactive calls and tasks
93
+
94
+ For applications with a JSON-RPC transport, `createMcpPeer` and `create_mcp_peer` apply the July request envelope and manage multi-round calls. The exchange accepts a method and params, assigns a fresh JSON-RPC ID, handles the authenticated transport, and returns the decoded result or throws the RPC error. JavaScript also passes cancellation and deadline options to the exchange. Bind each peer to one negotiated July endpoint and authenticated identity.
95
+
96
+ ```js
97
+ const peer = createMcpPeer(exchange, {
98
+ clientInfo: { name: 'document-service', version: '1' },
99
+ capabilities: { elicitation: { form: {} }, extensions: { 'io.modelcontextprotocol/tasks': {} } },
100
+ onInputRequired: requests => app.presentRequestedInputs(requests),
101
+ onTaskCreated: taskId => jobs.save({ endpoint, account, taskId }),
102
+ });
103
+ const result = await peer.callTool({ name: 'build_report', arguments: { period: 'week' } });
104
+ // A new process with the same endpoint and authenticated account can resume the task.
105
+ const completed = await peer.resumeTask(saved.taskId);
106
+ ```
107
+
108
+ ```python
109
+ peer = create_mcp_peer(
110
+ exchange,
111
+ client_info={"name": "document-service", "version": "1"},
112
+ capabilities={"elicitation": {"form": {}}, "extensions": {"io.modelcontextprotocol/tasks": {}}},
113
+ on_input_required=app.present_requested_inputs,
114
+ on_task_created=lambda task_id: jobs.save(endpoint, account, task_id),
115
+ )
116
+ result = await peer.call_tool({"name": "build_report", "arguments": {"period": "week"}})
117
+ completed = await peer.resume_task(saved.task_id)
118
+ ```
119
+
120
+ The callback persists the handle before the first poll. Resumption sends `tasks/get` against the original peer. Polls honor the server's interval and the operation's deadline. Input handling dispatches only advertised request types and modes. After acknowledging task input, the poller recognizes repeated keys from an eventually consistent server. Use `cancelTask` or `cancel_task` for explicit cancellation. The server acknowledges the request and determines the final outcome. An application can call `resolve` or `resolve_request` for interactive prompt and resource reads. Use `request` when the application needs the raw RPC result and its extension metadata. [Multi-round requests](https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/mrtr) · [Tasks](https://modelcontextprotocol.github.io/ext-tasks/specification/2026-07-28/tasks.html)
121
+
122
+ ## Read a verified skill file
123
+
124
+ ```js
125
+ const skills = await openMcpSkills(peer);
126
+ const page = await skills.listPage();
127
+ const selected = await skills.open(page.skills[0].uri);
128
+ const markdown = await selected.read();
129
+ ```
130
+
131
+ ```python
132
+ skills = await open_mcp_skills(peer)
133
+ page = await skills.list_page()
134
+ selected = await skills.open(page["skills"][0]["uri"])
135
+ markdown = await selected.read()
136
+ ```
137
+
138
+ Install `yaml` alongside the JavaScript package or install `toolsplice[skills]` in Python for the default YAML 1.2 parser. To reuse an existing parser, pass a callback to `open` that takes the source Markdown and returns its frontmatter as a JSON object. A fresh listing supplies the manifest directly. A direct URI or an expired listing uses `skills/get`. Request `refresh: true` in JavaScript's third argument or `refresh=True` in Python for a fresh lookup. The handle keeps its own copy of the static manifest, reads only requested files from the originating peer, and checks the SHA-256 digest and byte length before returning bytes. The entry file also requires a matching frontmatter object. Pass a relative reference or its manifest URI to read a supporting document or binary file. When the server advertises `directoryRead`, use `directoryPage` or `directory_page` to inspect direct children. The pinned manifest continues to control reads. Applications own approval, loading and execution. Dynamic manifests are available through the raw request API. [Skills over MCP](https://modelcontextprotocol.io/extensions/skills/overview)
139
+
140
+ ## Poll an event with checked payloads
141
+
142
+ ```js
143
+ const events = await openMcpEvents(peer);
144
+ const { events: descriptors } = await events.listPage();
145
+ const poll = events.poller(descriptors.find(d => d.name === 'document.ready'), { workspace });
146
+ const batch = await poll(savedCursor, { maxEvents: 20 });
147
+ ```
148
+
149
+ ```python
150
+ events = await open_mcp_events(peer)
151
+ page = await events.list_page()
152
+ descriptor = next(d for d in page["events"] if d["name"] == "document.ready")
153
+ poll = events.poller(descriptor, {"workspace": workspace})
154
+ batch = await poll(saved_cursor, max_events=20)
155
+ ```
156
+
157
+ Use a null cursor to start. The poller validates subscription arguments against the event descriptor before dispatch and checks every occurrence against its payload schema before returning the batch. Persist the returned cursor after your application commits its effects. Scope it to the endpoint, principal, event name and arguments. Handle `truncated` as a gap, drain `hasMore` before waiting `nextPollMs`, and deduplicate event IDs within each subscription. The poller issues one request per invocation. An omitted cursor and an explicit null both produce a null cursor. [Events](https://modelcontextprotocol.io/extensions/events/overview)
158
+
159
+ ### Check a push stream
160
+
161
+ Create one receiver for each `events/stream` request with the JSON-RPC ID assigned by your transport. Send its `params` with the persisted cursor. Route notifications for that ID to the same receiver in wire order.
162
+
163
+ ```js
164
+ const stream = events.pushReceiver(descriptor, { workspace }, requestId);
165
+ const delivery = stream.receive(notification);
166
+ if (delivery.type === 'event') {
167
+ await app.commitDocument(delivery.event.eventId, delivery.event.data, delivery.cursor);
168
+ }
169
+ ```
170
+
171
+ ```python
172
+ stream = events.push_receiver(descriptor, {"workspace": workspace}, request_id)
173
+ delivery = stream.receive(notification)
174
+ if delivery["type"] == "event":
175
+ await app.commit_document(delivery["event"]["eventId"], delivery["event"]["data"], delivery["cursor"])
176
+ ```
177
+
178
+ The receiver checks the subscription ID, the initial `active` confirmation and the event schema. It also returns heartbeats, gap confirmations, recoverable errors and terminal notifications. The transport owns opening the stream, liveness checks, cancellation and reconnects. A new stream gets a new receiver. Use the last committed cursor when reconnecting. [Push delivery and cursors](https://modelcontextprotocol.io/extensions/events/overview)
179
+
180
+ ### Receive a signed webhook
181
+
182
+ Install `standardwebhooks@^1.3` alongside Toolsplice in JavaScript or install `toolsplice[events]` in Python. Give each subscription its own secret, generated from 24 to 64 random bytes and stored with the authenticated endpoint and account. The MCP Events specification defines the `whsec_` prefix and base64 encoding.
183
+
184
+ ```js
185
+ const receive = await events.webhookReceiver(descriptor, { workspace }, {
186
+ secret: savedSecret, subscriptionId: savedId,
187
+ });
188
+ // Inside the POST route, before parsing the request body.
189
+ const delivery = receive(new Uint8Array(await request.arrayBuffer()), request.headers);
190
+ ```
191
+
192
+ ```python
193
+ receive = events.webhook_receiver(descriptor, {"workspace": workspace},
194
+ secret=saved_secret, subscription_id=saved_id)
195
+ delivery = receive(raw_request_bytes, request_headers)
196
+ ```
197
+
198
+ The receiver checks the subscription header, verifies the signature and timestamp against the original body bytes, then validates the event data. A verified event includes the upstream `eventId` and the delivery `messageId`. Persist the effect, cursor and deduplication ID together in application storage. A webhook `gap` or `terminated` message has its own type.
199
+
200
+ For initial endpoint verification, create a receiver with the secret and omit the subscription ID. It accepts only a signed `verification` message. Return `{"challenge": delivery.challenge}` to the server. Bind the ID from the authenticated `events/subscribe` response before accepting events. Your HTTP application serves the route, enforces its request body limit and renews the registration before the server's `refreshBefore` deadline. Toolsplice checks bodies up to 5 MiB. [Events wire specification](https://github.com/modelcontextprotocol/ext-events/blob/main/specification/beta/events/events.mdx) · [Standard Webhooks](https://www.standardwebhooks.com/)
201
+
202
+ ## Advertise a public endpoint
203
+
204
+ `createMcpServerCard({ name, version, description, url, supportedProtocolVersions })` and Python's `create_mcp_server_card(name=..., version=..., description=..., url=..., supported_protocol_versions=[...])` produce a v1 Server Card for a concrete Streamable HTTP endpoint. Publish the returned JSON at the endpoint's `/server-card` path or link it from an AI Catalog. Use live discovery for current capabilities and identity. [Server Cards](https://modelcontextprotocol.io/seps/2127-mcp-server-cards)