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.
- package/LICENSE +21 -0
- package/README.md +372 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +923 -0
- package/dist/codegen.d.ts +44 -0
- package/dist/codegen.js +479 -0
- package/dist/contract-caller.d.ts +22 -0
- package/dist/contract-caller.js +307 -0
- package/dist/contract-corrections.d.ts +35 -0
- package/dist/contract-corrections.js +159 -0
- package/dist/contract-schema.d.ts +5 -0
- package/dist/contract-schema.js +126 -0
- package/dist/contracts.d.ts +71 -0
- package/dist/contracts.js +366 -0
- package/dist/core.d.ts +14 -0
- package/dist/core.js +16 -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/index.d.ts +20 -0
- package/dist/index.js +19 -0
- package/dist/ordered-transport.d.ts +12 -0
- package/dist/ordered-transport.js +106 -0
- package/dist/pattern.d.ts +2 -0
- package/dist/pattern.js +32 -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 +134 -0
- package/dist/proxy.d.ts +40 -0
- package/dist/proxy.js +436 -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/shape.d.ts +91 -0
- package/dist/shape.js +499 -0
- package/dist/splice-diagnostics.d.ts +40 -0
- package/dist/splice-diagnostics.js +80 -0
- package/dist/splice-project.d.ts +119 -0
- package/dist/splice-project.js +296 -0
- package/dist/splice-recording.d.ts +105 -0
- package/dist/splice-recording.js +464 -0
- package/dist/splice.d.ts +84 -0
- package/dist/splice.js +1065 -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/v2.d.ts +49 -0
- package/dist/v2.js +396 -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/PROJECTS-AND-UPGRADES.md +115 -0
- package/docs/RECORDING-AND-CORRECTIONS.md +176 -0
- package/package.json +95 -4
package/dist/postgres.js
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { decodeStoredRecord, newServer, ShapeStoreError } from "./store.js";
|
|
2
|
+
function identity(value, label, max) {
|
|
3
|
+
if (!value || value.includes("\0") || Buffer.byteLength(value) > max)
|
|
4
|
+
throw new Error(`${label} must be nonempty, contain no NUL and fit ${max} UTF-8 bytes.`);
|
|
5
|
+
}
|
|
6
|
+
class MutatorFailure {
|
|
7
|
+
original;
|
|
8
|
+
constructor(original) {
|
|
9
|
+
this.original = original;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** PostgreSQL 14+. Owns its connection pool; call close() after all users stop.
|
|
13
|
+
* All updates and deletes acquire the same transaction-scoped advisory lock,
|
|
14
|
+
* including absent rows. A crashed connection releases its locks automatically.
|
|
15
|
+
* No callback retry after entry, and no file/cache fallback after an outage. */
|
|
16
|
+
export class PostgresShapeStore {
|
|
17
|
+
namespace;
|
|
18
|
+
#poolPromise;
|
|
19
|
+
#options;
|
|
20
|
+
readyPromise;
|
|
21
|
+
closed = false;
|
|
22
|
+
watchers = new Set();
|
|
23
|
+
revisions = new Map();
|
|
24
|
+
timeout;
|
|
25
|
+
max;
|
|
26
|
+
pollInterval;
|
|
27
|
+
constructor(options) {
|
|
28
|
+
this.#options = { ...options };
|
|
29
|
+
if (!options.connectionString)
|
|
30
|
+
throw new Error("PostgreSQL connectionString is required.");
|
|
31
|
+
try {
|
|
32
|
+
if (!["postgres:", "postgresql:"].includes(new URL(options.connectionString).protocol))
|
|
33
|
+
throw new Error();
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
throw new Error("PostgreSQL connectionString must be a postgres:// or postgresql:// URL.");
|
|
37
|
+
}
|
|
38
|
+
if (options.migrate !== undefined && typeof options.migrate !== "boolean")
|
|
39
|
+
throw new Error("migrate must be a boolean.");
|
|
40
|
+
this.namespace = options.namespace ?? "default";
|
|
41
|
+
identity(this.namespace, "namespace", 256);
|
|
42
|
+
this.timeout = options.timeoutMs ?? 1000;
|
|
43
|
+
this.max = options.maxConnections ?? 4;
|
|
44
|
+
this.pollInterval = options.pollIntervalMs ?? 1000;
|
|
45
|
+
for (const [label, value, minimum, maximum] of [["timeoutMs", this.timeout, 50, 60000], ["maxConnections", this.max, 1, 64], ["pollIntervalMs", this.pollInterval, 50, 60000]]) {
|
|
46
|
+
if (!Number.isSafeInteger(value) || value < minimum || value > maximum)
|
|
47
|
+
throw new Error(`${label} must be an integer between ${minimum} and ${maximum}.`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
failure(error) {
|
|
51
|
+
if (error instanceof ShapeStoreError)
|
|
52
|
+
return error;
|
|
53
|
+
const value = error && typeof error === "object" ? error : {};
|
|
54
|
+
const code = typeof value.code === "string" ? value.code : "";
|
|
55
|
+
const message = typeof value.message === "string" ? value.message : "";
|
|
56
|
+
// Classify only known driver/SQLSTATE facts. Never retain the raw error, SQL,
|
|
57
|
+
// connection string or message; callers must not retry an uncertain commit.
|
|
58
|
+
const reason = code === "57014" ? "query was canceled; check statement deadlines or administrative cancellation"
|
|
59
|
+
: code === "55P03" ? "could not acquire a lock; check lock deadlines and writer contention"
|
|
60
|
+
: code === "42501" ? "role lacks required database privileges"
|
|
61
|
+
: code === "28P01" || code === "28000" ? "authentication failed; check the configured credentials and authentication policy"
|
|
62
|
+
: code === "ETIMEDOUT" ? "network deadline was exceeded; remote completion may be uncertain"
|
|
63
|
+
: !code && message === "Query read timeout" ? "query-response deadline was exceeded; remote completion may be uncertain"
|
|
64
|
+
: !code && (message === "timeout exceeded when trying to connect" || message === "Connection terminated due to connection timeout")
|
|
65
|
+
? "connection or pool-wait deadline was exceeded; check load, connectivity and timeoutMs"
|
|
66
|
+
: ["ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EAI_AGAIN"].includes(code)
|
|
67
|
+
? "network connection is unavailable; check connectivity and server availability"
|
|
68
|
+
: "check connectivity, permissions and schema version";
|
|
69
|
+
return new ShapeStoreError("IO", `PostgreSQL learning storage is unavailable; ${reason}.`);
|
|
70
|
+
}
|
|
71
|
+
pool() {
|
|
72
|
+
if (this.closed)
|
|
73
|
+
return Promise.reject(new ShapeStoreError("IO", "PostgreSQL learning storage is closed."));
|
|
74
|
+
return this.#poolPromise ??= import("pg").then(({ Pool }) => {
|
|
75
|
+
const pool = new Pool({ connectionString: this.#options.connectionString, max: this.max,
|
|
76
|
+
connectionTimeoutMillis: this.timeout, statement_timeout: this.timeout,
|
|
77
|
+
lock_timeout: this.timeout, idle_in_transaction_session_timeout: this.timeout * 2,
|
|
78
|
+
query_timeout: this.timeout + 500, allowExitOnIdle: true });
|
|
79
|
+
// Idle socket errors must not crash the application. The next operation
|
|
80
|
+
// reports a sanitized error and the pool replaces the failed connection.
|
|
81
|
+
pool.on("error", () => { });
|
|
82
|
+
return pool;
|
|
83
|
+
}).catch(() => { this.#poolPromise = undefined; throw new ShapeStoreError("IO", "PostgreSQL driver unavailable. Install the optional pg package."); });
|
|
84
|
+
}
|
|
85
|
+
async initialize() {
|
|
86
|
+
if (this.closed)
|
|
87
|
+
throw new ShapeStoreError("IO", "PostgreSQL learning storage is closed.");
|
|
88
|
+
if (!this.readyPromise)
|
|
89
|
+
this.readyPromise = this.initializeSchema().catch((error) => { this.readyPromise = undefined; throw this.failure(error); });
|
|
90
|
+
return this.readyPromise;
|
|
91
|
+
}
|
|
92
|
+
async initializeSchema() {
|
|
93
|
+
const pool = await this.pool();
|
|
94
|
+
const client = await pool.connect();
|
|
95
|
+
let destroy = false;
|
|
96
|
+
try {
|
|
97
|
+
if (this.#options.migrate === false) {
|
|
98
|
+
const result = await client.query("SELECT version FROM public.mcp_shape_schema WHERE id = true");
|
|
99
|
+
if (result.rows[0]?.version !== 1)
|
|
100
|
+
throw new Error("Unsupported schema");
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
await client.query("BEGIN ISOLATION LEVEL READ COMMITTED");
|
|
104
|
+
// Stable across package renames: old and new processes must share this migration lock.
|
|
105
|
+
await client.query("SELECT pg_advisory_xact_lock(hashtextextended('mcp-shape:schema', 0))");
|
|
106
|
+
await client.query("CREATE TABLE IF NOT EXISTS public.mcp_shape_schema (id boolean PRIMARY KEY CHECK (id), version integer NOT NULL)");
|
|
107
|
+
const result = await client.query("SELECT version FROM public.mcp_shape_schema WHERE id = true");
|
|
108
|
+
if (result.rows.length && result.rows[0].version !== 1)
|
|
109
|
+
throw new Error("Unsupported schema");
|
|
110
|
+
await client.query(`
|
|
111
|
+
CREATE SEQUENCE IF NOT EXISTS public.mcp_shape_revision;
|
|
112
|
+
CREATE TABLE IF NOT EXISTS public.mcp_shape_records (
|
|
113
|
+
namespace text NOT NULL, name text NOT NULL, record jsonb NOT NULL,
|
|
114
|
+
revision bigint NOT NULL DEFAULT nextval('public.mcp_shape_revision'),
|
|
115
|
+
PRIMARY KEY (namespace, name)
|
|
116
|
+
);
|
|
117
|
+
INSERT INTO public.mcp_shape_schema (id, version) VALUES (true, 1) ON CONFLICT (id) DO NOTHING;
|
|
118
|
+
`);
|
|
119
|
+
await client.query("COMMIT");
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
try {
|
|
123
|
+
await client.query("ROLLBACK");
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
destroy = true;
|
|
127
|
+
}
|
|
128
|
+
throw error;
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
client.release(destroy);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
async refresh(name) {
|
|
135
|
+
identity(name, "server name", 512);
|
|
136
|
+
try {
|
|
137
|
+
await this.initialize();
|
|
138
|
+
const result = await (await this.pool()).query("SELECT record::text AS record, revision::text AS revision FROM public.mcp_shape_records WHERE namespace=$1 AND name=$2", [this.namespace, name]);
|
|
139
|
+
const row = result.rows[0];
|
|
140
|
+
const record = row ? decodeStoredRecord(row.record, name) : undefined;
|
|
141
|
+
this.revisions.set(name, row?.revision);
|
|
142
|
+
return record;
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
throw this.failure(error);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
async load(name, version) {
|
|
149
|
+
const record = await this.refresh(name) ?? newServer(name, version);
|
|
150
|
+
if (version !== undefined)
|
|
151
|
+
record.version = version;
|
|
152
|
+
return record;
|
|
153
|
+
}
|
|
154
|
+
async has(name) { return (await this.refresh(name)) !== undefined; }
|
|
155
|
+
async list() {
|
|
156
|
+
try {
|
|
157
|
+
await this.initialize();
|
|
158
|
+
const result = await (await this.pool()).query("SELECT name FROM public.mcp_shape_records WHERE namespace=$1 ORDER BY name", [this.namespace]);
|
|
159
|
+
return result.rows.map((row) => row.name);
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
throw this.failure(error);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
async transaction(name, action) {
|
|
166
|
+
identity(name, "server name", 512);
|
|
167
|
+
let client, destroy = false;
|
|
168
|
+
try {
|
|
169
|
+
await this.initialize();
|
|
170
|
+
client = await (await this.pool()).connect();
|
|
171
|
+
await client.query("BEGIN ISOLATION LEVEL READ COMMITTED");
|
|
172
|
+
await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", [JSON.stringify([this.namespace, name])]);
|
|
173
|
+
const result = await action(client);
|
|
174
|
+
await client.query("COMMIT");
|
|
175
|
+
return result;
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
if (client) {
|
|
179
|
+
try {
|
|
180
|
+
await client.query("ROLLBACK");
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
destroy = true;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (error instanceof MutatorFailure)
|
|
187
|
+
throw error.original;
|
|
188
|
+
throw this.failure(error);
|
|
189
|
+
}
|
|
190
|
+
finally {
|
|
191
|
+
client?.release(destroy);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
async transact(name, mutate) {
|
|
195
|
+
return this.transaction(name, async (client) => {
|
|
196
|
+
const result = await client.query("SELECT record::text AS record FROM public.mcp_shape_records WHERE namespace=$1 AND name=$2", [this.namespace, name]);
|
|
197
|
+
const record = result.rows.length ? decodeStoredRecord(result.rows[0].record, name) : newServer(name);
|
|
198
|
+
let value;
|
|
199
|
+
try {
|
|
200
|
+
value = mutate(record);
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
throw new MutatorFailure(error);
|
|
204
|
+
}
|
|
205
|
+
if (value !== null && (typeof value === "object" || typeof value === "function") && "then" in value && typeof value.then === "function") {
|
|
206
|
+
// Consume an async callback's rejection before rejecting the unsupported mutator.
|
|
207
|
+
void Promise.resolve(value).catch(() => { });
|
|
208
|
+
throw new MutatorFailure(new TypeError("PostgresShapeStore.transact mutator must be synchronous."));
|
|
209
|
+
}
|
|
210
|
+
const serialized = JSON.stringify(record);
|
|
211
|
+
decodeStoredRecord(serialized, name);
|
|
212
|
+
const written = await client.query(`INSERT INTO public.mcp_shape_records (namespace,name,record) VALUES ($1,$2,$3::jsonb)
|
|
213
|
+
ON CONFLICT (namespace,name) DO UPDATE SET record=EXCLUDED.record,revision=nextval('public.mcp_shape_revision') RETURNING revision::text`, [this.namespace, name, serialized]);
|
|
214
|
+
this.revisions.set(name, written.rows[0].revision);
|
|
215
|
+
return value;
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
async remove(name) {
|
|
219
|
+
await this.transaction(name, async (client) => {
|
|
220
|
+
await client.query("DELETE FROM public.mcp_shape_records WHERE namespace=$1 AND name=$2", [this.namespace, name]);
|
|
221
|
+
});
|
|
222
|
+
this.revisions.delete(name);
|
|
223
|
+
}
|
|
224
|
+
watch(name, onChange, onError) {
|
|
225
|
+
identity(name, "server name", 512);
|
|
226
|
+
if (this.closed)
|
|
227
|
+
throw new ShapeStoreError("IO", "PostgreSQL learning storage is closed.");
|
|
228
|
+
let previous = this.revisions.get(name), busy = false, stopped = false;
|
|
229
|
+
const timer = setInterval(() => {
|
|
230
|
+
if (busy || stopped)
|
|
231
|
+
return;
|
|
232
|
+
busy = true;
|
|
233
|
+
void (async () => {
|
|
234
|
+
await this.initialize();
|
|
235
|
+
const result = await (await this.pool()).query("SELECT revision::text FROM public.mcp_shape_records WHERE namespace=$1 AND name=$2", [this.namespace, name]);
|
|
236
|
+
if (stopped)
|
|
237
|
+
return;
|
|
238
|
+
const revision = result.rows[0]?.revision;
|
|
239
|
+
if (revision !== previous) {
|
|
240
|
+
previous = revision;
|
|
241
|
+
onChange();
|
|
242
|
+
}
|
|
243
|
+
})().catch(() => { if (!stopped) {
|
|
244
|
+
try {
|
|
245
|
+
onError?.();
|
|
246
|
+
}
|
|
247
|
+
catch { }
|
|
248
|
+
} }).finally(() => { busy = false; });
|
|
249
|
+
}, this.pollInterval);
|
|
250
|
+
timer.unref();
|
|
251
|
+
const stop = () => { stopped = true; clearInterval(timer); this.watchers.delete(stop); };
|
|
252
|
+
this.watchers.add(stop);
|
|
253
|
+
return stop;
|
|
254
|
+
}
|
|
255
|
+
async close() {
|
|
256
|
+
if (this.closed)
|
|
257
|
+
return;
|
|
258
|
+
this.closed = true;
|
|
259
|
+
for (const stop of this.watchers)
|
|
260
|
+
stop();
|
|
261
|
+
const pool = await this.#poolPromise?.catch(() => undefined);
|
|
262
|
+
await pool?.end();
|
|
263
|
+
}
|
|
264
|
+
}
|
package/dist/probe.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { LearningStore } from "./storage.js";
|
|
2
|
+
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|
3
|
+
import { type OutputKind } from "./extract.js";
|
|
4
|
+
import type { JsonSchema } from "./schema.js";
|
|
5
|
+
import { type ExamplePolicy } from "./shape.js";
|
|
6
|
+
export interface ProbeOptions {
|
|
7
|
+
store: LearningStore;
|
|
8
|
+
serverName?: string;
|
|
9
|
+
/** Explicit calls per tool. Listing a tool here is the user's opt-in to call it, read-only or not. */
|
|
10
|
+
args?: Record<string, Record<string, unknown>[]>;
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
/** Which real values may be kept as examples (default: safe). */
|
|
14
|
+
examples?: ExamplePolicy;
|
|
15
|
+
log?: (message: string) => void;
|
|
16
|
+
}
|
|
17
|
+
export interface ProbeRow {
|
|
18
|
+
tool: string;
|
|
19
|
+
status: "called" | "skipped" | "failed";
|
|
20
|
+
reason?: string;
|
|
21
|
+
kinds?: OutputKind[];
|
|
22
|
+
}
|
|
23
|
+
export interface ProbeReport {
|
|
24
|
+
serverName: string;
|
|
25
|
+
rows: ProbeRow[];
|
|
26
|
+
}
|
|
27
|
+
export declare function probe(upstream: Transport, options: ProbeOptions): Promise<ProbeReport>;
|
|
28
|
+
/** Builds arguments from defaults, enums and examples. Returns undefined if a required value can't be filled. */
|
|
29
|
+
export declare function synthesizeArgs(schema: JsonSchema | undefined): Record<string, unknown> | undefined;
|
package/dist/probe.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { VERSION } from "./version.js";
|
|
2
|
+
// Bootstraps output types without waiting for real traffic by calling tools that are safe to call:
|
|
3
|
+
// those the server marks read-only, plus any the user explicitly lists with arguments.
|
|
4
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
5
|
+
import { CallToolResultSchema, ListToolsResultSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
6
|
+
import { extract } from "./extract.js";
|
|
7
|
+
import { DEFAULT_OPTIONS } from "./shape.js";
|
|
8
|
+
import { applyExamplePolicy, recordCall, recordToolList } from "./store.js";
|
|
9
|
+
export async function probe(upstream, options) {
|
|
10
|
+
const { store, timeoutMs = 60_000 } = options;
|
|
11
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1)
|
|
12
|
+
throw new Error("timeoutMs must be a positive integer.");
|
|
13
|
+
if (options.examples !== undefined && !["none", "safe", "all"].includes(options.examples))
|
|
14
|
+
throw new Error("Unknown example policy.");
|
|
15
|
+
const log = options.log ?? (() => { });
|
|
16
|
+
const observeOptions = { ...DEFAULT_OPTIONS, examples: options.examples ?? DEFAULT_OPTIONS.examples };
|
|
17
|
+
const client = new Client({ name: "toolsplice-probe", version: VERSION });
|
|
18
|
+
try {
|
|
19
|
+
await client.connect(upstream, { timeout: timeoutMs, signal: options.signal });
|
|
20
|
+
const info = client.getServerVersion();
|
|
21
|
+
const serverName = options.serverName ?? info?.name ?? "upstream";
|
|
22
|
+
await store.load(serverName, info?.version);
|
|
23
|
+
const tools = await listAllTools(client);
|
|
24
|
+
const observations = [];
|
|
25
|
+
const rows = [];
|
|
26
|
+
for (const tool of tools) {
|
|
27
|
+
options.signal?.throwIfAborted();
|
|
28
|
+
const explicit = options.args && Object.hasOwn(options.args, tool.name) ? options.args[tool.name] : undefined;
|
|
29
|
+
const plan = planCalls(tool, explicit);
|
|
30
|
+
if ("skip" in plan) {
|
|
31
|
+
rows.push({ tool: tool.name, status: "skipped", reason: plan.skip });
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
const kinds = [];
|
|
35
|
+
let failure;
|
|
36
|
+
for (const args of plan.calls) {
|
|
37
|
+
try {
|
|
38
|
+
const result = (await client.request({ method: "tools/call", params: { name: tool.name, arguments: args } }, CallToolResultSchema, {
|
|
39
|
+
timeout: timeoutMs,
|
|
40
|
+
signal: options.signal,
|
|
41
|
+
}));
|
|
42
|
+
const extracted = extract(result);
|
|
43
|
+
observations.push({ tool: tool.name, result: extracted });
|
|
44
|
+
kinds.push(extracted.kind);
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
options.signal?.throwIfAborted();
|
|
48
|
+
failure = error instanceof Error ? error.message : String(error);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
log(`${tool.name}: ${kinds.join(", ") || failure}`);
|
|
52
|
+
rows.push(kinds.length ? { tool: tool.name, status: "called", kinds } : { tool: tool.name, status: "failed", reason: failure });
|
|
53
|
+
}
|
|
54
|
+
await store.transact(serverName, (latest) => {
|
|
55
|
+
latest.version = info?.version ?? latest.version;
|
|
56
|
+
recordToolList(latest, tools);
|
|
57
|
+
applyExamplePolicy(latest, observeOptions);
|
|
58
|
+
for (const observation of observations)
|
|
59
|
+
recordCall(latest, observation.tool, observation.result, observeOptions);
|
|
60
|
+
});
|
|
61
|
+
return { serverName, rows };
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
await client.close().catch(() => { });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async function listAllTools(client) {
|
|
68
|
+
const tools = [];
|
|
69
|
+
let cursor;
|
|
70
|
+
const seen = new Set();
|
|
71
|
+
do {
|
|
72
|
+
if (cursor) {
|
|
73
|
+
if (seen.has(cursor))
|
|
74
|
+
throw new Error("Upstream repeated a tools/list cursor; discovery stopped.");
|
|
75
|
+
seen.add(cursor);
|
|
76
|
+
}
|
|
77
|
+
if (seen.size >= 1000)
|
|
78
|
+
throw new Error("Upstream tools/list exceeded the discovery page limit.");
|
|
79
|
+
const page = await client.request({ method: "tools/list", params: cursor ? { cursor } : undefined }, ListToolsResultSchema);
|
|
80
|
+
tools.push(...page.tools);
|
|
81
|
+
cursor = page.nextCursor;
|
|
82
|
+
} while (cursor);
|
|
83
|
+
return tools;
|
|
84
|
+
}
|
|
85
|
+
function planCalls(tool, explicit) {
|
|
86
|
+
if (explicit?.length)
|
|
87
|
+
return { calls: explicit };
|
|
88
|
+
const a = tool.annotations;
|
|
89
|
+
if (!a?.readOnlyHint || a.destructiveHint)
|
|
90
|
+
return { skip: "not marked read-only; add it to --args to call it" };
|
|
91
|
+
const args = synthesizeArgs(tool.inputSchema);
|
|
92
|
+
if (!args)
|
|
93
|
+
return { skip: "needs arguments we can't guess; add it to --args" };
|
|
94
|
+
return { calls: [args] };
|
|
95
|
+
}
|
|
96
|
+
/** Builds arguments from defaults, enums and examples. Returns undefined if a required value can't be filled. */
|
|
97
|
+
export function synthesizeArgs(schema) {
|
|
98
|
+
const props = (schema?.properties ?? {});
|
|
99
|
+
const required = (schema?.required ?? []);
|
|
100
|
+
const args = {};
|
|
101
|
+
for (const key of required) {
|
|
102
|
+
const value = synthesizeValue(Object.hasOwn(props, key) ? props[key] : undefined);
|
|
103
|
+
if (value === undefined)
|
|
104
|
+
return undefined;
|
|
105
|
+
Object.defineProperty(args, key, { value, enumerable: true, writable: true, configurable: true });
|
|
106
|
+
}
|
|
107
|
+
return args;
|
|
108
|
+
}
|
|
109
|
+
function synthesizeValue(schema) {
|
|
110
|
+
if (!schema)
|
|
111
|
+
return undefined;
|
|
112
|
+
if ("default" in schema)
|
|
113
|
+
return schema.default;
|
|
114
|
+
if ("const" in schema)
|
|
115
|
+
return schema.const;
|
|
116
|
+
if (Array.isArray(schema.enum) && schema.enum.length)
|
|
117
|
+
return schema.enum[0];
|
|
118
|
+
if (Array.isArray(schema.examples) && schema.examples.length)
|
|
119
|
+
return schema.examples[0];
|
|
120
|
+
const type = Array.isArray(schema.type) ? schema.type.find((t) => t !== "null") : schema.type;
|
|
121
|
+
switch (type) {
|
|
122
|
+
case "boolean":
|
|
123
|
+
return false;
|
|
124
|
+
case "integer":
|
|
125
|
+
case "number":
|
|
126
|
+
return typeof schema.minimum === "number" ? schema.minimum : 1;
|
|
127
|
+
case "array":
|
|
128
|
+
return typeof schema.minItems === "number" && schema.minItems > 0 ? undefined : [];
|
|
129
|
+
case "object":
|
|
130
|
+
return synthesizeArgs(schema);
|
|
131
|
+
default:
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
}
|
package/dist/proxy.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { LearningStore } from "./storage.js";
|
|
2
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
3
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
4
|
+
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|
5
|
+
import { type ExamplePolicy } from "./shape.js";
|
|
6
|
+
export type EnrichMode = "none" | "description" | "schema";
|
|
7
|
+
export interface ProxyOptions {
|
|
8
|
+
store: LearningStore;
|
|
9
|
+
/** Overrides the name the upstream server reports; used as the store key. */
|
|
10
|
+
serverName?: string;
|
|
11
|
+
/**
|
|
12
|
+
* description: append a one-line summary of the learned output type to each tool description.
|
|
13
|
+
* schema (experimental): also declare a lenient outputSchema and fill in structuredContent.
|
|
14
|
+
*/
|
|
15
|
+
enrich?: EnrichMode;
|
|
16
|
+
/** Responses needed before a learned type is shown to the agent. */
|
|
17
|
+
minSamples?: number;
|
|
18
|
+
/** Which real values may be kept as examples (default: none). */
|
|
19
|
+
examples?: ExamplePolicy;
|
|
20
|
+
/** Upstream tool-call timeout in ms. */
|
|
21
|
+
callTimeoutMs?: number;
|
|
22
|
+
log?: (message: string) => void;
|
|
23
|
+
/** Maximum extra characters appended to a tool description (default: 2000). */
|
|
24
|
+
maxDescriptionLength?: number;
|
|
25
|
+
/** Coalesce changes from concurrent calls before notifying the client (default: 50 ms). */
|
|
26
|
+
notificationDebounceMs?: number;
|
|
27
|
+
/** Refresh descriptions learned by another session sharing this store (default: true). */
|
|
28
|
+
watchStore?: boolean;
|
|
29
|
+
/** Cancellation of initial connection/initialization. Later requests carry their own signals. */
|
|
30
|
+
signal?: AbortSignal;
|
|
31
|
+
connectTimeoutMs?: number;
|
|
32
|
+
}
|
|
33
|
+
export interface Proxy {
|
|
34
|
+
server: Server;
|
|
35
|
+
client: Client;
|
|
36
|
+
serverName: string;
|
|
37
|
+
close(): Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
/** Connects to the upstream server and returns a Server ready to be connected to the agent's transport. */
|
|
40
|
+
export declare function createProxy(upstream: Transport, options: ProxyOptions): Promise<Proxy>;
|