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.
- package/LICENSE +21 -0
- package/README.md +104 -2
- package/dist/abortable.d.ts +6 -0
- package/dist/abortable.js +50 -0
- package/dist/adaptive-read.d.ts +50 -0
- package/dist/adaptive-read.js +780 -0
- package/dist/answer-wait.d.ts +7 -0
- package/dist/answer-wait.js +45 -0
- package/dist/cache-reads.d.ts +18 -0
- package/dist/cache-reads.js +89 -0
- package/dist/calibration-ledger.d.ts +37 -0
- package/dist/calibration-ledger.js +148 -0
- package/dist/calibration-marker.d.ts +4 -0
- package/dist/calibration-marker.js +77 -0
- package/dist/catalog-setup.d.ts +33 -0
- package/dist/catalog-setup.js +89 -0
- package/dist/catalog.d.ts +10 -0
- package/dist/catalog.js +42 -0
- package/dist/checkpoint-files.d.ts +15 -0
- package/dist/checkpoint-files.js +99 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +1454 -0
- package/dist/coalesce-reads.d.ts +6 -0
- package/dist/coalesce-reads.js +33 -0
- package/dist/codegen.d.ts +44 -0
- package/dist/codegen.js +479 -0
- package/dist/contract-caller.d.ts +23 -0
- package/dist/contract-caller.js +326 -0
- package/dist/contract-corrections.d.ts +35 -0
- package/dist/contract-corrections.js +159 -0
- package/dist/contract-schema.d.ts +7 -0
- package/dist/contract-schema.js +156 -0
- package/dist/contracts.d.ts +72 -0
- package/dist/contracts.js +370 -0
- package/dist/core.d.ts +44 -0
- package/dist/core.js +43 -0
- package/dist/db-final-answer.d.ts +9 -0
- package/dist/db-final-answer.js +62 -0
- package/dist/define.d.ts +78 -0
- package/dist/define.js +14 -0
- package/dist/doctor.d.ts +22 -0
- package/dist/doctor.js +91 -0
- package/dist/drift.d.ts +23 -0
- package/dist/drift.js +111 -0
- package/dist/execution.d.ts +38 -0
- package/dist/execution.js +66 -0
- package/dist/extract.d.ts +34 -0
- package/dist/extract.js +73 -0
- package/dist/final-answer-stores.d.ts +71 -0
- package/dist/final-answer-stores.js +72 -0
- package/dist/final-answer.d.ts +32 -0
- package/dist/final-answer.js +104 -0
- package/dist/impact.d.ts +48 -0
- package/dist/impact.js +71 -0
- package/dist/index.d.ts +51 -0
- package/dist/index.js +47 -0
- package/dist/local-tool.d.ts +18 -0
- package/dist/local-tool.js +32 -0
- package/dist/mcp-apps.d.ts +53 -0
- package/dist/mcp-apps.js +32 -0
- package/dist/mcp-event-delivery.d.ts +98 -0
- package/dist/mcp-event-delivery.js +211 -0
- package/dist/mcp-extensions.d.ts +46 -0
- package/dist/mcp-extensions.js +200 -0
- package/dist/mcp-peer.d.ts +45 -0
- package/dist/mcp-peer.js +207 -0
- package/dist/mcp-server-card.d.ts +21 -0
- package/dist/mcp-server-card.js +54 -0
- package/dist/ordered-transport.d.ts +12 -0
- package/dist/ordered-transport.js +106 -0
- package/dist/page-checkpoint.d.ts +71 -0
- package/dist/page-checkpoint.js +286 -0
- package/dist/page-read-gate.d.ts +15 -0
- package/dist/page-read-gate.js +48 -0
- package/dist/pattern.d.ts +3 -0
- package/dist/pattern.js +54 -0
- package/dist/postgres.d.ts +41 -0
- package/dist/postgres.js +264 -0
- package/dist/probe.d.ts +29 -0
- package/dist/probe.js +121 -0
- package/dist/proxy.d.ts +40 -0
- package/dist/proxy.js +436 -0
- package/dist/read-pages.d.ts +25 -0
- package/dist/read-pages.js +85 -0
- package/dist/read-policy.d.ts +6 -0
- package/dist/read-policy.js +16 -0
- package/dist/read-steps.d.ts +12 -0
- package/dist/read-steps.js +36 -0
- package/dist/result-session.d.ts +109 -0
- package/dist/result-session.js +620 -0
- package/dist/route-checkpoint.d.ts +3 -0
- package/dist/route-checkpoint.js +80 -0
- package/dist/route-driver-cli.d.ts +3 -0
- package/dist/route-driver-cli.js +43 -0
- package/dist/route-evaluation.d.ts +141 -0
- package/dist/route-evaluation.js +329 -0
- package/dist/row-groups.d.ts +17 -0
- package/dist/row-groups.js +79 -0
- package/dist/row-query.d.ts +62 -0
- package/dist/row-query.js +172 -0
- package/dist/rules.d.ts +30 -0
- package/dist/rules.js +72 -0
- package/dist/run-diagnostics.d.ts +75 -0
- package/dist/run-diagnostics.js +212 -0
- package/dist/runtime.d.ts +6 -0
- package/dist/runtime.js +26 -0
- package/dist/schema.d.ts +17 -0
- package/dist/schema.js +299 -0
- package/dist/search-fetch.d.ts +50 -0
- package/dist/search-fetch.js +264 -0
- package/dist/shape.d.ts +91 -0
- package/dist/shape.js +499 -0
- package/dist/skill-files.d.ts +9 -0
- package/dist/skill-files.js +49 -0
- package/dist/splice-diagnostics.d.ts +44 -0
- package/dist/splice-diagnostics.js +88 -0
- package/dist/splice-measure.d.ts +33 -0
- package/dist/splice-measure.js +55 -0
- package/dist/splice-project.d.ts +125 -0
- package/dist/splice-project.js +348 -0
- package/dist/splice-recording.d.ts +132 -0
- package/dist/splice-recording.js +481 -0
- package/dist/splice.d.ts +181 -0
- package/dist/splice.js +1263 -0
- package/dist/sqlite-checkpoint-store.d.ts +5 -0
- package/dist/sqlite-checkpoint-store.js +91 -0
- package/dist/sqlite-checkpoint-worker.d.ts +1 -0
- package/dist/sqlite-checkpoint-worker.js +115 -0
- package/dist/storage.d.ts +17 -0
- package/dist/storage.js +1 -0
- package/dist/store.d.ts +151 -0
- package/dist/store.js +735 -0
- package/dist/test-difference.d.ts +13 -0
- package/dist/test-difference.js +42 -0
- package/dist/testing.d.ts +122 -0
- package/dist/testing.js +261 -0
- package/dist/text-pages.d.ts +24 -0
- package/dist/text-pages.js +36 -0
- package/dist/tool-discovery.d.ts +59 -0
- package/dist/tool-discovery.js +136 -0
- package/dist/unevaluated.d.ts +7 -0
- package/dist/unevaluated.js +156 -0
- package/dist/v2.d.ts +49 -0
- package/dist/v2.js +413 -0
- package/dist/validate-output.d.ts +3 -0
- package/dist/validate-output.js +73 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +1 -0
- package/dist/workflow-json.d.ts +8 -0
- package/dist/workflow-json.js +74 -0
- package/docs/AGENT-FRAMEWORKS.md +431 -0
- package/docs/BENCHMARKS.md +43 -0
- package/docs/INTEGRATION-QUICKSTART.md +859 -0
- package/docs/LEARNING-AND-STORAGE.md +393 -0
- package/docs/MCP.md +204 -0
- package/docs/PROJECTS-AND-UPGRADES.md +173 -0
- package/docs/PYTHON-REFERENCE.md +348 -0
- package/docs/PYTHON.md +120 -0
- package/docs/RECORDING-AND-CORRECTIONS.md +205 -0
- package/docs/TESTING.md +259 -0
- package/examples/mcp-app/build.mjs +11 -0
- package/examples/mcp-app/view.mjs +22 -0
- package/examples/quickstart.mjs +43 -0
- package/examples/route-driver.mjs +67 -0
- package/integrations/ai.d.mts +36 -0
- package/integrations/ai.mjs +178 -0
- package/integrations/call-options.mjs +9 -0
- package/integrations/langchain.d.mts +31 -0
- package/integrations/langchain.mjs +114 -0
- package/integrations/managed.mjs +154 -0
- package/integrations/types.d.mts +13 -0
- package/package.json +139 -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,25 @@
|
|
|
1
|
+
/** Mark a transient error only when repeating the same read is safe. */
|
|
2
|
+
export declare class RetryablePageError extends Error {
|
|
3
|
+
readonly retryAfterMs?: number | undefined;
|
|
4
|
+
constructor(message: string, retryAfterMs?: number | undefined);
|
|
5
|
+
}
|
|
6
|
+
export interface PageReadOptions {
|
|
7
|
+
/** Attempts per cursor, including the first. Defaults to 1 for ordinary reads and 3 with a checkpoint. Maximum 5. */
|
|
8
|
+
maxReadAttempts?: number;
|
|
9
|
+
/** Cumulative retry delay in milliseconds. Defaults to 5,000 for ordinary reads and 60,000 with a checkpoint. */
|
|
10
|
+
maxRetryWaitMs?: number;
|
|
11
|
+
/** Maximum number of logical pages, including the first. Default 32. */
|
|
12
|
+
maxPages?: number;
|
|
13
|
+
/** Maximum total UTF-8 bytes across all pages. Default 5 MiB. */
|
|
14
|
+
maxBytes?: number;
|
|
15
|
+
signal?: AbortSignal;
|
|
16
|
+
}
|
|
17
|
+
export declare function pageLimits(options: PageReadOptions): {
|
|
18
|
+
maxPages: number;
|
|
19
|
+
maxBytes: number;
|
|
20
|
+
};
|
|
21
|
+
export declare function utf8Bytes(text: string): number;
|
|
22
|
+
/** The consumer validates the page body before the next cursor is followed. */
|
|
23
|
+
export declare function readPages<Page extends {
|
|
24
|
+
nextCursor?: string | null;
|
|
25
|
+
}>(read: (cursor: string | undefined, signal?: AbortSignal) => Page | PromiseLike<Page>, maxPages: number, { signal, maxReadAttempts, maxRetryWaitMs }: PageReadOptions): AsyncGenerator<Page, void, unknown>;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { setTimeout as wait } from "node:timers/promises";
|
|
2
|
+
import { abortable } from "./abortable.js";
|
|
3
|
+
import { JSON_LIMIT } from "./workflow-json.js";
|
|
4
|
+
/** Mark a transient error only when repeating the same read is safe. */
|
|
5
|
+
export class RetryablePageError extends Error {
|
|
6
|
+
retryAfterMs;
|
|
7
|
+
constructor(message, retryAfterMs) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.retryAfterMs = retryAfterMs;
|
|
10
|
+
this.name = "RetryablePageError";
|
|
11
|
+
if (retryAfterMs !== undefined &&
|
|
12
|
+
(!Number.isSafeInteger(retryAfterMs) || retryAfterMs < 0))
|
|
13
|
+
throw new RangeError("retryAfterMs must be a nonnegative integer.");
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export function pageLimits(options) {
|
|
17
|
+
const maxPages = options.maxPages ?? 32, maxBytes = options.maxBytes ?? JSON_LIMIT;
|
|
18
|
+
for (const [n, max, label] of [
|
|
19
|
+
[maxPages, 1000, "maxPages"],
|
|
20
|
+
[maxBytes, 64 * 1024 * 1024, "maxBytes"],
|
|
21
|
+
]) {
|
|
22
|
+
if (!Number.isSafeInteger(n) || n < 1 || n > max)
|
|
23
|
+
throw new RangeError(`${label} must be an integer from 1 through ${max}.`);
|
|
24
|
+
}
|
|
25
|
+
return { maxPages, maxBytes };
|
|
26
|
+
}
|
|
27
|
+
export function utf8Bytes(text) {
|
|
28
|
+
if (/[\uD800-\uDFFF]/u.test(text))
|
|
29
|
+
throw new Error("Invalid UTF-8 page or cursor.");
|
|
30
|
+
return Buffer.byteLength(text);
|
|
31
|
+
}
|
|
32
|
+
/** The consumer validates the page body before the next cursor is followed. */
|
|
33
|
+
export async function* readPages(read, maxPages, { signal, maxReadAttempts = 1, maxRetryWaitMs = 5000 }) {
|
|
34
|
+
if (!Number.isSafeInteger(maxReadAttempts) ||
|
|
35
|
+
maxReadAttempts < 1 ||
|
|
36
|
+
maxReadAttempts > 5)
|
|
37
|
+
throw new RangeError("maxReadAttempts must be an integer from 1 through 5.");
|
|
38
|
+
if (!Number.isSafeInteger(maxRetryWaitMs) ||
|
|
39
|
+
maxRetryWaitMs < 0 ||
|
|
40
|
+
maxRetryWaitMs > 60000)
|
|
41
|
+
throw new RangeError("maxRetryWaitMs must be an integer from 0 through 60000.");
|
|
42
|
+
let remainingWait = maxRetryWaitMs;
|
|
43
|
+
async function readCursor(cursor) {
|
|
44
|
+
for (let attempt = 1;; attempt++) {
|
|
45
|
+
try {
|
|
46
|
+
return await abortable(() => read(cursor, signal), signal);
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
signal?.throwIfAborted();
|
|
50
|
+
if (!(error instanceof RetryablePageError) ||
|
|
51
|
+
attempt >= maxReadAttempts)
|
|
52
|
+
throw error;
|
|
53
|
+
const backoff = 100 * 2 ** (attempt - 1);
|
|
54
|
+
const delay = Math.max(error.retryAfterMs ?? 0, Math.floor(backoff * (1 + Math.random())));
|
|
55
|
+
if (delay > remainingWait)
|
|
56
|
+
throw error;
|
|
57
|
+
remainingWait -= delay;
|
|
58
|
+
try {
|
|
59
|
+
await wait(delay, undefined, { signal });
|
|
60
|
+
}
|
|
61
|
+
catch (reason) {
|
|
62
|
+
signal?.throwIfAborted();
|
|
63
|
+
throw reason;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const seen = new Set();
|
|
69
|
+
let cursor;
|
|
70
|
+
for (let i = 0; i < maxPages; i++) {
|
|
71
|
+
const page = await readCursor(cursor);
|
|
72
|
+
signal?.throwIfAborted();
|
|
73
|
+
yield page;
|
|
74
|
+
const next = page.nextCursor;
|
|
75
|
+
if (next === null || next === undefined)
|
|
76
|
+
return;
|
|
77
|
+
if (typeof next !== "string" || utf8Bytes(next) > 4096)
|
|
78
|
+
throw new Error("Invalid page cursor.");
|
|
79
|
+
if (seen.has(next))
|
|
80
|
+
throw new Error("Upstream repeated a page cursor.");
|
|
81
|
+
seen.add(next);
|
|
82
|
+
cursor = next;
|
|
83
|
+
}
|
|
84
|
+
throw new RangeError("Read exceeded the page limit.");
|
|
85
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Portable execution settings for independent, ordered read waves. */
|
|
2
|
+
export function parseReadPolicy(value) {
|
|
3
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
4
|
+
throw new Error("Invalid recorded read policy.");
|
|
5
|
+
const policy = value;
|
|
6
|
+
if (Object.keys(policy).length !== 2 ||
|
|
7
|
+
!Number.isInteger(policy.concurrency) ||
|
|
8
|
+
Number(policy.concurrency) < 1 ||
|
|
9
|
+
Number(policy.concurrency) > 16 ||
|
|
10
|
+
typeof policy.assumeReadOnly !== "boolean")
|
|
11
|
+
throw new Error("Invalid recorded read policy.");
|
|
12
|
+
return {
|
|
13
|
+
concurrency: Number(policy.concurrency),
|
|
14
|
+
assumeReadOnly: policy.assumeReadOnly,
|
|
15
|
+
};
|
|
16
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type FinalAnswerOptions, type DatabaseFinalAnswerOptions } from "./final-answer.js";
|
|
2
|
+
type Storage = {
|
|
3
|
+
directory: string;
|
|
4
|
+
store?: never;
|
|
5
|
+
} | Pick<DatabaseFinalAnswerOptions, "store" | "directory">;
|
|
6
|
+
/** Re-enter an application workflow after a crash. Only successful named reads are reused. */
|
|
7
|
+
export declare function readSteps(options: Storage & Pick<FinalAnswerOptions, "jobId" | "context">): {
|
|
8
|
+
read<I, T>(name: string, input: I, schema: Record<string, unknown>, work: (input: I) => T | PromiseLike<T>, wait?: {
|
|
9
|
+
waitMs?: number;
|
|
10
|
+
}): Promise<T>;
|
|
11
|
+
};
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { finalAnswerCheckpoint, } from "./final-answer.js";
|
|
2
|
+
import { copyJson, jsonFingerprint } from "./workflow-json.js";
|
|
3
|
+
/** Re-enter an application workflow after a crash. Only successful named reads are reused. */
|
|
4
|
+
export function readSteps(options) {
|
|
5
|
+
const { jobId } = options;
|
|
6
|
+
const context = copyJson(options.context);
|
|
7
|
+
if (typeof jobId !== "string" ||
|
|
8
|
+
!jobId ||
|
|
9
|
+
!context ||
|
|
10
|
+
typeof context !== "object" ||
|
|
11
|
+
Array.isArray(context))
|
|
12
|
+
throw new TypeError("Expected a nonempty job ID and workflow context.");
|
|
13
|
+
if ((options.directory !== undefined) === (options.store !== undefined))
|
|
14
|
+
throw new Error("Choose one checkpoint directory or store.");
|
|
15
|
+
const directory = options.directory, store = options.store;
|
|
16
|
+
return {
|
|
17
|
+
async read(name, input, schema, work, wait) {
|
|
18
|
+
if (typeof name !== "string" ||
|
|
19
|
+
!name.trim() ||
|
|
20
|
+
typeof work !== "function")
|
|
21
|
+
throw new TypeError("Expected a named read and callback.");
|
|
22
|
+
const args = copyJson(input);
|
|
23
|
+
const identity = {
|
|
24
|
+
jobId: "toolsplice:read-step:v1:" + jsonFingerprint([jobId, name]),
|
|
25
|
+
context: { workflow: context, step: name, input: args },
|
|
26
|
+
schema,
|
|
27
|
+
};
|
|
28
|
+
if (store)
|
|
29
|
+
return finalAnswerCheckpoint({ ...identity, store }).run(async (save) => save(await work(args)), wait);
|
|
30
|
+
return finalAnswerCheckpoint({
|
|
31
|
+
...identity,
|
|
32
|
+
directory: directory,
|
|
33
|
+
}).run(async (save) => save(await work(args)), wait);
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|