toolsplice 0.0.0-stage → 0.0.1

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 (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +372 -2
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +923 -0
  5. package/dist/codegen.d.ts +44 -0
  6. package/dist/codegen.js +479 -0
  7. package/dist/contract-caller.d.ts +22 -0
  8. package/dist/contract-caller.js +307 -0
  9. package/dist/contract-corrections.d.ts +35 -0
  10. package/dist/contract-corrections.js +159 -0
  11. package/dist/contract-schema.d.ts +5 -0
  12. package/dist/contract-schema.js +126 -0
  13. package/dist/contracts.d.ts +71 -0
  14. package/dist/contracts.js +366 -0
  15. package/dist/core.d.ts +14 -0
  16. package/dist/core.js +16 -0
  17. package/dist/doctor.d.ts +22 -0
  18. package/dist/doctor.js +91 -0
  19. package/dist/drift.d.ts +23 -0
  20. package/dist/drift.js +111 -0
  21. package/dist/execution.d.ts +38 -0
  22. package/dist/execution.js +66 -0
  23. package/dist/extract.d.ts +34 -0
  24. package/dist/extract.js +73 -0
  25. package/dist/index.d.ts +20 -0
  26. package/dist/index.js +19 -0
  27. package/dist/ordered-transport.d.ts +12 -0
  28. package/dist/ordered-transport.js +106 -0
  29. package/dist/pattern.d.ts +2 -0
  30. package/dist/pattern.js +32 -0
  31. package/dist/postgres.d.ts +41 -0
  32. package/dist/postgres.js +264 -0
  33. package/dist/probe.d.ts +29 -0
  34. package/dist/probe.js +134 -0
  35. package/dist/proxy.d.ts +40 -0
  36. package/dist/proxy.js +436 -0
  37. package/dist/runtime.d.ts +6 -0
  38. package/dist/runtime.js +26 -0
  39. package/dist/schema.d.ts +17 -0
  40. package/dist/schema.js +299 -0
  41. package/dist/shape.d.ts +91 -0
  42. package/dist/shape.js +499 -0
  43. package/dist/splice-diagnostics.d.ts +40 -0
  44. package/dist/splice-diagnostics.js +80 -0
  45. package/dist/splice-project.d.ts +119 -0
  46. package/dist/splice-project.js +296 -0
  47. package/dist/splice-recording.d.ts +105 -0
  48. package/dist/splice-recording.js +464 -0
  49. package/dist/splice.d.ts +84 -0
  50. package/dist/splice.js +1065 -0
  51. package/dist/storage.d.ts +17 -0
  52. package/dist/storage.js +1 -0
  53. package/dist/store.d.ts +151 -0
  54. package/dist/store.js +735 -0
  55. package/dist/v2.d.ts +49 -0
  56. package/dist/v2.js +396 -0
  57. package/dist/validate-output.d.ts +3 -0
  58. package/dist/validate-output.js +73 -0
  59. package/dist/version.d.ts +1 -0
  60. package/dist/version.js +1 -0
  61. package/dist/workflow-json.d.ts +8 -0
  62. package/dist/workflow-json.js +74 -0
  63. package/docs/PROJECTS-AND-UPGRADES.md +115 -0
  64. package/docs/RECORDING-AND-CORRECTIONS.md +176 -0
  65. package/package.json +95 -4
package/dist/proxy.js ADDED
@@ -0,0 +1,436 @@
1
+ import { VERSION } from "./version.js";
2
+ // A pass-through MCP server that sits between an agent and an upstream server,
3
+ // records every tool result, and can optionally tell the agent what each tool returns.
4
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
5
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
6
+ import { CallToolRequestSchema, CallToolResultSchema, GetPromptRequestSchema, ListPromptsRequestSchema, ListResourcesRequestSchema, ListResourceTemplatesRequestSchema, ListToolsRequestSchema, ListToolsResultSchema, PromptListChangedNotificationSchema, SubscribeRequestSchema, UnsubscribeRequestSchema, ResourceUpdatedNotificationSchema, SetLevelRequestSchema, LoggingMessageNotificationSchema, CompleteRequestSchema, CompleteResultSchema, EmptyResultSchema, ReadResourceRequestSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema, } from "@modelcontextprotocol/sdk/types.js";
7
+ import { Ajv } from "ajv";
8
+ import { describeOutput } from "./codegen.js";
9
+ import { orderedTransport } from "./ordered-transport.js";
10
+ import { definitionFingerprint, learnedContract, recordDrift, resetLearning, stableHash } from "./drift.js";
11
+ import { validateOutput } from "./validate-output.js";
12
+ import { extract } from "./extract.js";
13
+ import { toJsonSchema } from "./schema.js";
14
+ import { DEFAULT_OPTIONS, hasEmbeddedJson } from "./shape.js";
15
+ import { applyExamplePolicy, newServer, recordCall, recordToolList } from "./store.js";
16
+ /** Connects to the upstream server and returns a Server ready to be connected to the agent's transport. */
17
+ export async function createProxy(upstream, options) {
18
+ const { store, enrich = "description", minSamples = 1, callTimeoutMs = 600_000, maxDescriptionLength = 2000, notificationDebounceMs = 50 } = options;
19
+ if (!["none", "description", "schema"].includes(enrich))
20
+ throw new Error("Unknown enrichment mode.");
21
+ if (options.examples !== undefined && !["none", "safe", "all"].includes(options.examples))
22
+ throw new Error("Unknown example policy.");
23
+ for (const [name, value, minimum] of [["minSamples", minSamples, 1], ["callTimeoutMs", callTimeoutMs, 1], ["maxDescriptionLength", maxDescriptionLength, 80], ["notificationDebounceMs", notificationDebounceMs, 0]]) {
24
+ if (!Number.isSafeInteger(value) || value < minimum)
25
+ throw new Error(`${name} must be an integer >= ${minimum}`);
26
+ }
27
+ const log = (message) => { try {
28
+ options.log?.(message);
29
+ }
30
+ catch { /* diagnostics cannot fail calls */ } };
31
+ const observeOptions = { ...DEFAULT_OPTIONS, examples: options.examples ?? DEFAULT_OPTIONS.examples };
32
+ const client = new Client({ name: "toolsplice", version: VERSION });
33
+ try {
34
+ await client.connect(orderedTransport(upstream), { signal: options.signal, timeout: options.connectTimeoutMs ?? 30_000 });
35
+ }
36
+ catch (error) {
37
+ await client.close().catch(() => { });
38
+ throw error;
39
+ }
40
+ const info = client.getServerVersion();
41
+ const caps = client.getServerCapabilities() ?? {};
42
+ const serverName = options.serverName ?? info?.name ?? "upstream";
43
+ let record;
44
+ try {
45
+ record = await store.load(serverName);
46
+ }
47
+ catch {
48
+ record = newServer(serverName);
49
+ log("Stored learning could not be loaded; forwarding remains available.");
50
+ }
51
+ let closed = false;
52
+ let learningEpoch = 0;
53
+ const pendingLearning = [];
54
+ let drainingLearning = false;
55
+ function learn(mutate) {
56
+ return new Promise((resolve, reject) => {
57
+ pendingLearning.push({ mutate, resolve, reject });
58
+ if (!drainingLearning) {
59
+ drainingLearning = true;
60
+ // Coalesce results from a code-mode fan-out into one atomic write, rather than fsync
61
+ // the whole record once for every returned item. Ordinary calls wait one event-loop turn.
62
+ setImmediate(() => { void drainLearning(); });
63
+ }
64
+ });
65
+ }
66
+ async function drainLearning() {
67
+ try {
68
+ while (pendingLearning.length) {
69
+ const batch = pendingLearning.splice(0, 20);
70
+ try {
71
+ await doLearn(() => { for (const item of batch)
72
+ item.mutate(); });
73
+ batch.forEach((item) => item.resolve());
74
+ }
75
+ catch (error) {
76
+ batch.forEach((item) => item.reject(error));
77
+ }
78
+ }
79
+ }
80
+ finally {
81
+ drainingLearning = false;
82
+ }
83
+ }
84
+ async function doLearn(mutate) {
85
+ let entered = false;
86
+ learningEpoch++;
87
+ const deadline = Date.now() + 500;
88
+ for (let attempt = 0;; attempt++) {
89
+ if (closed || options.signal?.aborted)
90
+ return;
91
+ try {
92
+ await store.transact(serverName, (latest) => {
93
+ entered = true;
94
+ record = latest;
95
+ if (record.version && info?.version && record.version !== info.version) {
96
+ for (const tool of Object.values(record.tools))
97
+ resetLearning(tool, "server-version");
98
+ }
99
+ record.version = info?.version ?? record.version;
100
+ mutate();
101
+ });
102
+ // Yield with the lock released. A long fan-out queue must leave an acquisition window
103
+ // for another CLI process instead of immediately reacquiring from a microtask.
104
+ await new Promise((resolve) => setTimeout(resolve, 1));
105
+ return;
106
+ }
107
+ catch (error) {
108
+ const code = error && typeof error === "object" && "code" in error ? error.code : undefined;
109
+ if (!entered && ["LOCKED", "CONFLICT"].includes(String(code)) && Date.now() < deadline) {
110
+ const delay = Math.min(30, 3 * (attempt + 1)) + Math.floor(Math.random() * 5);
111
+ await new Promise((resolve) => setTimeout(resolve, delay));
112
+ continue;
113
+ }
114
+ // A write may fail after the callback ran. Never count the same observation twice.
115
+ if (!entered) {
116
+ try {
117
+ mutate();
118
+ }
119
+ catch { /* inference also remains best effort */ }
120
+ }
121
+ log("Could not persist learning; forwarding remains available. Check doctor and the store path.");
122
+ return;
123
+ }
124
+ }
125
+ }
126
+ await learn(() => applyExamplePolicy(record, observeOptions));
127
+ const server = new Server({ name: info?.name ?? serverName, version: info?.version ?? "0.0.0" }, {
128
+ capabilities: {
129
+ ...(caps.tools ? { tools: { listChanged: true } } : {}),
130
+ ...(caps.resources ? { resources: { listChanged: caps.resources.listChanged, subscribe: caps.resources.subscribe } } : {}),
131
+ ...(caps.prompts ? { prompts: { listChanged: caps.prompts.listChanged } } : {}),
132
+ ...(caps.logging ? { logging: {} } : {}),
133
+ ...(caps.completions ? { completions: {} } : {}),
134
+ },
135
+ instructions: client.getInstructions(),
136
+ });
137
+ // Tools whose outputSchema we declared on the agent's behalf (schema mode).
138
+ const declared = new Map();
139
+ const ajv = new Ajv({ strict: false, allErrors: false });
140
+ function forwardOptions(extra, token) {
141
+ return {
142
+ timeout: callTimeoutMs, maxTotalTimeout: callTimeoutMs, signal: extra.signal, resetTimeoutOnProgress: true,
143
+ ...(token === undefined ? {} : { onprogress: (progress) => {
144
+ void extra.sendNotification({ method: "notifications/progress", params: { ...progress, progressToken: token } }).catch(() => { });
145
+ } }),
146
+ };
147
+ }
148
+ let notifyTimer;
149
+ const advertised = new Map();
150
+ const definitions = new Map();
151
+ let scan;
152
+ let stopWatching;
153
+ let refreshTimer;
154
+ function queueChanged() {
155
+ if (closed || notifyTimer)
156
+ return;
157
+ notifyTimer = setTimeout(() => {
158
+ notifyTimer = undefined;
159
+ void server.sendToolListChanged().catch(() => { });
160
+ }, notificationDebounceMs);
161
+ notifyTimer.unref();
162
+ }
163
+ if (caps.tools)
164
+ server.setRequestHandler(ListToolsRequestSchema, async (request, extra) => {
165
+ // Client.listTools eagerly compiles declared output schemas. Discovery must also work for
166
+ // clients that deliberately ignore an unsupported upstream reference/schema.
167
+ const result = await client.request({ method: "tools/list", params: request.params }, ListToolsResultSchema, forwardOptions(extra, request.params?._meta?.progressToken));
168
+ try {
169
+ await learn(() => {
170
+ applyExamplePolicy(record, observeOptions);
171
+ for (const tool of result.tools) {
172
+ const prior = Object.hasOwn(record.tools, tool.name) ? record.tools[tool.name] : undefined;
173
+ if (prior?.inputSchema && definitionFingerprint(prior) !== definitionFingerprint(tool))
174
+ resetLearning(prior, "tool-definition");
175
+ }
176
+ recordToolList(record, result.tools);
177
+ const cursor = request.params?.cursor;
178
+ if (!cursor)
179
+ scan = { expectedCursor: undefined, names: new Set(), seen: new Set() };
180
+ // Reconcile only a complete, uninterrupted cursor chain; arbitrary page requests aren't
181
+ // authoritative snapshots of the whole upstream catalog.
182
+ if (scan && scan.expectedCursor === cursor && (!cursor || !scan.seen.has(cursor))) {
183
+ if (cursor)
184
+ scan.seen.add(cursor);
185
+ result.tools.forEach((t) => scan.names.add(t.name));
186
+ scan.expectedCursor = result.nextCursor;
187
+ }
188
+ else
189
+ scan = undefined;
190
+ if (scan && !result.nextCursor) {
191
+ for (const name of Object.keys(record.tools))
192
+ if (!scan.names.has(name)) {
193
+ delete record.tools[name];
194
+ declared.delete(name);
195
+ advertised.delete(name);
196
+ definitions.delete(name);
197
+ }
198
+ scan = undefined;
199
+ }
200
+ });
201
+ }
202
+ catch {
203
+ log("Could not record tool definitions; forwarding remains available.");
204
+ }
205
+ const tools = result.tools.map((tool) => {
206
+ definitions.set(tool.name, tool);
207
+ let next = tool;
208
+ try {
209
+ if (enrich !== "none")
210
+ next = enrichTool(tool, Object.hasOwn(record.tools, tool.name) ? record.tools[tool.name] : undefined);
211
+ }
212
+ catch {
213
+ log("Could not enrich a tool description; using the upstream definition.");
214
+ }
215
+ advertised.set(tool.name, stableHash({ description: next.description, outputSchema: next.outputSchema }));
216
+ return next;
217
+ });
218
+ return { ...result, tools };
219
+ });
220
+ function enrichTool(tool, rec) {
221
+ if (!rec || rec.shape.count + rec.kinds.text < minSamples)
222
+ return tool;
223
+ // A server that declares and delivers structured output already tells the agent everything.
224
+ if (tool.outputSchema && rec.kinds.structured > 0 && !hasEmbeddedJson(rec.shape))
225
+ return tool;
226
+ let next = tool;
227
+ // The sample count changes on every call. Keep the first count for a structural revision to
228
+ // avoid needlessly invalidating clients' tool caches and prompt caches.
229
+ let summary = describeOutput(rec);
230
+ if (summary)
231
+ summary = summary.replace(/\(learned from \d+ responses?\)/, "(observed; may vary)");
232
+ if (summary && summary.length > maxDescriptionLength)
233
+ summary = summary.slice(0, maxDescriptionLength - 35) + "… [inspect full types with emit-ts]";
234
+ if (summary)
235
+ next = { ...next, description: [tool.description?.trim(), summary].filter(Boolean).join("\n\n") };
236
+ if (enrich === "schema" && !tool.outputSchema && canDeclareSchema(rec)) {
237
+ const schema = toJsonSchema(rec.shape, { mode: "lenient" });
238
+ declared.set(tool.name, ajv.compile(schema));
239
+ next = { ...next, outputSchema: schema };
240
+ }
241
+ return next;
242
+ }
243
+ function canDeclareSchema(rec) {
244
+ const s = rec.shape;
245
+ // Only plain-object outputs that have never come back as text: anything else would make
246
+ // clients that enforce outputSchema reject the result.
247
+ return rec.shape.count >= minSamples && rec.kinds.text === 0 && !!s.object && s.count === s.object.count;
248
+ }
249
+ if (options.watchStore !== false && enrich !== "none") {
250
+ try {
251
+ let refreshing = false, refreshAgain = false;
252
+ const refresh = () => {
253
+ if (closed)
254
+ return;
255
+ if (refreshing) {
256
+ refreshAgain = true;
257
+ return;
258
+ }
259
+ if (refreshTimer)
260
+ return;
261
+ refreshTimer = setTimeout(async () => {
262
+ refreshTimer = undefined;
263
+ if (closed)
264
+ return;
265
+ refreshing = true;
266
+ try {
267
+ if (drainingLearning) {
268
+ refresh();
269
+ return;
270
+ }
271
+ const epoch = learningEpoch;
272
+ const loaded = await store.refresh(serverName);
273
+ if (closed)
274
+ return;
275
+ if (epoch !== learningEpoch || drainingLearning) {
276
+ refresh();
277
+ return;
278
+ }
279
+ const exists = loaded !== undefined;
280
+ const fresh = loaded ?? newServer(serverName, record.version);
281
+ if (fresh.version !== record.version)
282
+ return;
283
+ if (!exists) {
284
+ declared.clear();
285
+ recordToolList(fresh, [...definitions.values()]);
286
+ }
287
+ applyExamplePolicy(fresh, observeOptions);
288
+ record = fresh;
289
+ for (const name of advertised.keys()) {
290
+ const rec = Object.hasOwn(record.tools, name) ? record.tools[name] : undefined;
291
+ if (!rec)
292
+ continue;
293
+ const base = definitions.get(name) ?? { name, description: rec.description, inputSchema: (rec.inputSchema ?? { type: "object" }), outputSchema: rec.outputSchema };
294
+ const next = enrichTool(base, rec);
295
+ const hash = stableHash({ description: next.description, outputSchema: next.outputSchema });
296
+ if (hash !== advertised.get(name)) {
297
+ advertised.set(name, hash);
298
+ queueChanged();
299
+ }
300
+ }
301
+ }
302
+ catch {
303
+ log("Could not refresh shared learning; current descriptions remain available.");
304
+ }
305
+ finally {
306
+ refreshing = false;
307
+ if (refreshAgain) {
308
+ refreshAgain = false;
309
+ refresh();
310
+ }
311
+ }
312
+ }, 50);
313
+ refreshTimer.unref();
314
+ };
315
+ stopWatching = store.watch?.(serverName, refresh, () => log("Shared-store watching encountered an error; learning will refresh on a later update."));
316
+ }
317
+ catch {
318
+ log("Shared-store watching is unavailable; learning still works for this session.");
319
+ }
320
+ }
321
+ if (caps.tools)
322
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
323
+ const name = request.params.name;
324
+ // client.request rather than client.callTool: a proxy should forward results as-is,
325
+ // not reject them for failing the upstream's own outputSchema.
326
+ const result = (await client.request({ method: "tools/call", params: request.params }, CallToolResultSchema, forwardOptions(extra, request.params._meta?.progressToken)));
327
+ let extracted;
328
+ try {
329
+ extracted = extract(result);
330
+ await learn(() => {
331
+ const prior = Object.hasOwn(record.tools, name) ? record.tools[name] : undefined;
332
+ const before = prior ? learnedContract(prior) : undefined;
333
+ const observations = prior ? prior.shape.count + prior.kinds.text + prior.kinds.empty : 0;
334
+ const rec = recordCall(record, name, extracted, observeOptions);
335
+ validateOutput(rec, result);
336
+ const event = recordDrift(rec, before, observations, extracted.kind);
337
+ if (event)
338
+ log(`${name}: observed output shape changed (revision ${rec.drift.revision})`);
339
+ });
340
+ const rec = record.tools[name];
341
+ // Notify only if the definition actually sent to the agent would now differ.
342
+ if (enrich !== "none" && advertised.has(name)) {
343
+ const base = { name, description: rec.description, inputSchema: (rec.inputSchema ?? { type: "object" }), outputSchema: rec.outputSchema };
344
+ const next = enrichTool(base, rec);
345
+ const hash = stableHash({ description: next.description, outputSchema: next.outputSchema });
346
+ if (hash !== advertised.get(name)) {
347
+ advertised.set(name, hash);
348
+ queueChanged();
349
+ }
350
+ }
351
+ }
352
+ catch {
353
+ log("Could not learn a result; returning the upstream result unchanged.");
354
+ return result;
355
+ }
356
+ const validate = declared.get(name);
357
+ if (!validate || result.isError || result.structuredContent)
358
+ return result;
359
+ const value = extracted.kind === "json-text" ? extracted.value : undefined;
360
+ if (isPlainObject(value) && validate(value))
361
+ return { ...result, structuredContent: value };
362
+ // Our declared schema was wrong for this response. Withdraw it so future calls aren't rejected.
363
+ declared.delete(name);
364
+ log(`${name}: learned outputSchema withdrawn after a non-matching response`);
365
+ queueChanged();
366
+ return result;
367
+ });
368
+ if (caps.resources) {
369
+ server.setRequestHandler(ListResourcesRequestSchema, (r, e) => client.listResources(r.params, forwardOptions(e, r.params?._meta?.progressToken)));
370
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, (r, e) => client.listResourceTemplates(r.params, forwardOptions(e, r.params?._meta?.progressToken)));
371
+ server.setRequestHandler(ReadResourceRequestSchema, (r, e) => client.readResource(r.params, forwardOptions(e, r.params._meta?.progressToken)));
372
+ if (caps.resources.subscribe) {
373
+ server.setRequestHandler(SubscribeRequestSchema, (r, e) => client.request(r, EmptyResultSchema, forwardOptions(e, r.params._meta?.progressToken)));
374
+ server.setRequestHandler(UnsubscribeRequestSchema, (r, e) => client.request(r, EmptyResultSchema, forwardOptions(e, r.params._meta?.progressToken)));
375
+ client.setNotificationHandler(ResourceUpdatedNotificationSchema, (n) => server.notification(n));
376
+ }
377
+ }
378
+ if (caps.logging) {
379
+ server.setRequestHandler(SetLevelRequestSchema, (r, e) => client.request(r, EmptyResultSchema, forwardOptions(e, r.params._meta?.progressToken)));
380
+ client.setNotificationHandler(LoggingMessageNotificationSchema, (n) => server.notification(n));
381
+ }
382
+ if (caps.completions)
383
+ server.setRequestHandler(CompleteRequestSchema, (r, e) => client.request(r, CompleteResultSchema, forwardOptions(e, r.params._meta?.progressToken)));
384
+ if (caps.prompts) {
385
+ server.setRequestHandler(ListPromptsRequestSchema, (r, e) => client.listPrompts(r.params, forwardOptions(e, r.params?._meta?.progressToken)));
386
+ server.setRequestHandler(GetPromptRequestSchema, (r, e) => client.getPrompt(r.params, forwardOptions(e, r.params._meta?.progressToken)));
387
+ }
388
+ if (caps.tools)
389
+ client.setNotificationHandler(ToolListChangedNotificationSchema, () => queueChanged());
390
+ if (caps.resources?.listChanged)
391
+ client.setNotificationHandler(ResourceListChangedNotificationSchema, () => server.sendResourceListChanged().catch(() => { }));
392
+ if (caps.prompts?.listChanged)
393
+ client.setNotificationHandler(PromptListChangedNotificationSchema, () => server.sendPromptListChanged().catch(() => { }));
394
+ async function close() {
395
+ if (closed)
396
+ return;
397
+ closed = true;
398
+ // A disconnected host must not leave a backlog retrying an unavailable store.
399
+ for (const item of pendingLearning.splice(0))
400
+ item.resolve();
401
+ if (notifyTimer)
402
+ clearTimeout(notifyTimer);
403
+ if (refreshTimer)
404
+ clearTimeout(refreshTimer);
405
+ stopWatching?.();
406
+ await server.close().catch(() => { });
407
+ // Closing the HTTP transport only aborts local streams; explicitly release an owned MCP
408
+ // session as well. A slow or unavailable endpoint must not keep the CLI alive indefinitely.
409
+ const http = upstream;
410
+ if (typeof http.terminateSession === "function") {
411
+ let timer;
412
+ try {
413
+ await Promise.race([
414
+ http.terminateSession().catch(() => { }),
415
+ new Promise((resolve) => { timer = setTimeout(resolve, 1000); }),
416
+ ]);
417
+ }
418
+ finally {
419
+ if (timer)
420
+ clearTimeout(timer);
421
+ }
422
+ }
423
+ await client.close().catch(() => { });
424
+ }
425
+ client.onclose = () => { void close(); };
426
+ server.onclose = () => { void close(); };
427
+ return {
428
+ server,
429
+ client,
430
+ serverName,
431
+ close,
432
+ };
433
+ }
434
+ function isPlainObject(value) {
435
+ return typeof value === "object" && value !== null && !Array.isArray(value);
436
+ }
@@ -0,0 +1,6 @@
1
+ import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
+ import { type ToolCaller, type BindingCallOptions, type DecodeMode, type ToolFunction } from "./execution.js";
3
+ export * from "./execution.js";
4
+ /** SDK 1.x adapter. Uses request() to preserve raw results before decoding. */
5
+ export declare function createToolCaller(client: Pick<Client, "request">, defaults?: BindingCallOptions): ToolCaller;
6
+ export declare function toolFunctions(client: Client, names: string[], mode?: DecodeMode, timeoutMs?: number): Record<string, ToolFunction>;
@@ -0,0 +1,26 @@
1
+ import { CallToolResultSchema, } from "@modelcontextprotocol/sdk/types.js";
2
+ import { bindingOptions, decode, ToolError, } from "./execution.js";
3
+ export * from "./execution.js";
4
+ /** SDK 1.x adapter. Uses request() to preserve raw results before decoding. */
5
+ export function createToolCaller(client, defaults) {
6
+ bindingOptions(defaults);
7
+ return (request, options) => client.request({ method: "tools/call", params: request }, CallToolResultSchema, bindingOptions(options, defaults));
8
+ }
9
+ export function toolFunctions(client, names, mode = "decoded", timeoutMs = 120_000) {
10
+ // A tool name is a dictionary key, including names such as "__proto__".
11
+ const fns = Object.create(null);
12
+ for (const name of names) {
13
+ fns[name] = async (args = {}) => {
14
+ const result = (await client.request({ method: "tools/call", params: { name, arguments: args } }, CallToolResultSchema, {
15
+ timeout: timeoutMs,
16
+ }));
17
+ try {
18
+ return decode(result, mode);
19
+ }
20
+ catch (error) {
21
+ throw new ToolError(name, error instanceof Error ? error.message : String(error));
22
+ }
23
+ };
24
+ }
25
+ return fns;
26
+ }
@@ -0,0 +1,17 @@
1
+ import { type Shape } from "./shape.js";
2
+ export type JsonSchema = {
3
+ [key: string]: unknown;
4
+ };
5
+ export interface SchemaOptions {
6
+ mode: "docs" | "lenient";
7
+ }
8
+ export declare function toJsonSchema(shape: Shape, options?: SchemaOptions): JsonSchema;
9
+ /** Values that repeat often enough to look like a fixed set (status, kind, priority...). */
10
+ export declare function observedValues(shape: Shape): string[] | undefined;
11
+ /**
12
+ * The key whose array items look like the parent itself: every key of the items also appears on
13
+ * the parent, including the key itself (so the nesting continues at least one more level).
14
+ */
15
+ export declare function findRecursiveKey(shape: Shape): string | undefined;
16
+ /** Objects used as dictionaries (keyed by id or date) should be typed as maps, not as hundreds of fields. */
17
+ export declare function looksLikeMap(shape: Shape): boolean;