@eum-agent/integration-mcp 0.0.0-stage → 1.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/dist/index.js +4420 -0
- package/package.json +53 -3
- package/ui/ui.js +2760 -0
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,4420 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { isAbsolute, posix, win32 } from "node:path";
|
|
5
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
6
|
+
import { PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
7
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
8
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
9
|
+
import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";
|
|
10
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
11
|
+
import { isDeepStrictEqual } from "node:util";
|
|
12
|
+
import { setImmediate } from "node:timers/promises";
|
|
13
|
+
import { createServer } from "node:http";
|
|
14
|
+
import { auth, discoverOAuthServerInfo, refreshAuthorization, selectResourceURL } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
15
|
+
import { OAuthError, ServerError } from "@modelcontextprotocol/sdk/server/auth/errors.js";
|
|
16
|
+
import { Ajv } from "ajv";
|
|
17
|
+
import { Ajv2019 } from "ajv/dist/2019.js";
|
|
18
|
+
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
19
|
+
import addFormats from "ajv-formats";
|
|
20
|
+
//#region src/names.ts
|
|
21
|
+
/**
|
|
22
|
+
* The name rules both halves apply: the gateway's zod in `config.ts` and the
|
|
23
|
+
* settings form in `ui/draft.ts`. Imports nothing, so the browser program can
|
|
24
|
+
* take it without Node types.
|
|
25
|
+
*/
|
|
26
|
+
/** A server's short name: part of every tool and command name it contributes. */
|
|
27
|
+
const SLUG = /^[a-z0-9][a-z0-9-]{0,23}$/;
|
|
28
|
+
/** An environment variable a person configures: a portable shell identifier. */
|
|
29
|
+
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
30
|
+
/** An HTTP header name (RFC 9110 token) that is also a valid credential name. */
|
|
31
|
+
const HEADER_NAME = /^[A-Za-z0-9_][A-Za-z0-9_-]{0,99}$/;
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/config.ts
|
|
34
|
+
const EnvEntrySchema = z.object({
|
|
35
|
+
name: z.string().regex(ENV_NAME, "environment variable names must match ^[A-Za-z_][A-Za-z0-9_]*$").refine((name) => !name.startsWith("YAOGUANG_"), "YAOGUANG_* variables are reserved").describe("Environment variable identifier; YAOGUANG_* is reserved."),
|
|
36
|
+
/** A credential: its value lives in the credential manager as `env.<name>`. */
|
|
37
|
+
secret: z.boolean().describe("True uses an existing env.<name> credential and forbids value; false requires a plain value."),
|
|
38
|
+
/** The plain value; absent for a credential. */
|
|
39
|
+
value: z.string().max(32768).refine((value) => !value.includes("\0"), "invalid environment value").optional().describe("Plain environment value, maximum 32768 UTF-16 code units and no NUL. Omit for a credential.")
|
|
40
|
+
}).strict().refine((entry) => entry.secret || entry.value !== void 0, "a plain variable needs a value").refine((entry) => !entry.secret || entry.value === void 0, "a credential is not stored here");
|
|
41
|
+
/** A local command. `command` is an absolute path or a bare name looked up on PATH. */
|
|
42
|
+
const StdioConfigSchema = z.object({
|
|
43
|
+
command: z.string().refine((command) => command.trim().length > 0 && !command.includes("\0"), "command is required").min(1, "command is required").max(4096).refine((command) => isAbsolute(command) || /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(command) || !/[\\/:]/.test(command), "command must be an absolute path or a bare command name").describe("Executable absolute path or bare PATH name, maximum 4096 UTF-16 code units. Shell command text is not accepted."),
|
|
44
|
+
args: z.array(z.string().max(32768).refine((value) => !value.includes("\0"), "invalid argument")).max(256).default([]).describe("Direct argv array, default empty, maximum 256 arguments; each is at most 32768 UTF-16 code units and contains no NUL."),
|
|
45
|
+
cwd: z.string().refine((cwd) => !cwd.includes("\0") && (isAbsolute(cwd) || /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(cwd)), "cwd must be an absolute path").optional().describe("Optional absolute working directory using host path syntax; no NUL."),
|
|
46
|
+
env: z.array(EnvEntrySchema).max(256).default([]).describe("Environment entries, default empty, maximum 256. Duplicate names must declare equal values.")
|
|
47
|
+
}).strict().refine((config) => config.env.every((entry, index) => config.env.slice(0, index).every((previous) => previous.name !== entry.name || previous.secret === entry.secret && previous.value === entry.value)), "environment variable aliases must have equal values");
|
|
48
|
+
/** A remote Streamable HTTP endpoint. Header values are credentials (`header.<name>`). */
|
|
49
|
+
const HttpConfigSchema = z.object({
|
|
50
|
+
url: z.string().trim().refine((url) => {
|
|
51
|
+
try {
|
|
52
|
+
const parsed = new URL(url);
|
|
53
|
+
return (parsed.protocol === "http:" || parsed.protocol === "https:") && parsed.username === "" && parsed.password === "";
|
|
54
|
+
} catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
}, "url must be an http(s) URL").describe("HTTP or HTTPS MCP endpoint URL without embedded username or password."),
|
|
58
|
+
auth: z.enum([
|
|
59
|
+
"none",
|
|
60
|
+
"headers",
|
|
61
|
+
"oauth"
|
|
62
|
+
]).describe("Authentication mode: none, stored header credentials, or OAuth."),
|
|
63
|
+
headers: z.array(z.string().regex(HEADER_NAME, "invalid header name")).max(64).default([]).describe("Unique header credential names, maximum 64, default empty; allowed only with auth=headers. Values come from header.<name> credentials.")
|
|
64
|
+
}).strict().refine((config) => new Set(config.headers.map((name) => name.toLowerCase())).size === config.headers.length, "header names must be unique").refine((config) => config.auth === "headers" || config.headers.length === 0, "headers are only sent when auth is \"headers\"");
|
|
65
|
+
/** What a person saves; `id` absent creates a server. */
|
|
66
|
+
const SaveServerSchema = z.discriminatedUnion("transport", [z.object({
|
|
67
|
+
id: z.string().uuid().optional(),
|
|
68
|
+
slug: z.string(),
|
|
69
|
+
name: z.string().trim().min(1).max(80),
|
|
70
|
+
transport: z.literal("stdio"),
|
|
71
|
+
config: StdioConfigSchema,
|
|
72
|
+
acknowledge: z.boolean().optional()
|
|
73
|
+
}).strict(), z.object({
|
|
74
|
+
id: z.string().uuid().optional(),
|
|
75
|
+
slug: z.string(),
|
|
76
|
+
name: z.string().trim().min(1).max(80),
|
|
77
|
+
transport: z.literal("http"),
|
|
78
|
+
config: HttpConfigSchema,
|
|
79
|
+
acknowledge: z.boolean().optional()
|
|
80
|
+
}).strict()]);
|
|
81
|
+
/** Refuses a slug that is malformed; uniqueness is the store's. */
|
|
82
|
+
function checkSlug(slug) {
|
|
83
|
+
if (!SLUG.test(slug)) throw new Error(`slug must match ${SLUG.source}`);
|
|
84
|
+
}
|
|
85
|
+
/** What a person acknowledges for a stdio server: the command line, where it
|
|
86
|
+
* runs and which variables it is given. A value change is not in it. */
|
|
87
|
+
function acknowledgementKey(config, platform = process.platform) {
|
|
88
|
+
return JSON.stringify([
|
|
89
|
+
config.command,
|
|
90
|
+
config.args,
|
|
91
|
+
config.cwd ?? null,
|
|
92
|
+
[...new Set(config.env.map((entry) => platform === "win32" ? entry.name.toUpperCase() : entry.name))].sort()
|
|
93
|
+
]);
|
|
94
|
+
}
|
|
95
|
+
/** The credential name that holds a secret environment variable's value. */
|
|
96
|
+
const envCredential = (name) => `env.${name}`;
|
|
97
|
+
/** The credential name that holds a header's value. */
|
|
98
|
+
const headerCredential = (name) => `header.${name}`;
|
|
99
|
+
const OAUTH_TOKENS = "oauth.tokens";
|
|
100
|
+
const OAUTH_CLIENT = "oauth.client";
|
|
101
|
+
/** Every credential name a configuration refers to (OAuth excluded). */
|
|
102
|
+
function credentialNames(record) {
|
|
103
|
+
return record.transport === "stdio" ? record.config.env.filter((entry) => entry.secret).map((entry) => envCredential(entry.name)) : record.config.auth === "headers" ? record.config.headers.map(headerCredential) : [];
|
|
104
|
+
}
|
|
105
|
+
/** Resolves bare executables and the real cwd before their launch is acknowledged. */
|
|
106
|
+
async function resolveStdioConfig(config, commands) {
|
|
107
|
+
const plain = Object.fromEntries(config.env.filter((entry) => !entry.secret).map((entry) => [entry.name, entry.value]));
|
|
108
|
+
const env = commands.environment([commands.childEnvironment(commands.env, "protocol"), plain]);
|
|
109
|
+
const inspected = await commands.inspect(config.command, env);
|
|
110
|
+
if (inspected.status !== "found" || !inspected.path) throw new Error(`command-unavailable: ${inspected.reason}`);
|
|
111
|
+
for (const entry of config.env) {
|
|
112
|
+
if ((commands.platform === "win32" ? entry.name.toUpperCase() : entry.name).startsWith("YAOGUANG_")) throw new Error("configured environment variable is reserved");
|
|
113
|
+
if (/^(?:https?|all|ftp|no)_proxy$/i.test(entry.name)) throw new Error("proxy-environment-managed-by-gateway");
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
...config,
|
|
117
|
+
command: inspected.path,
|
|
118
|
+
cwd: await commands.directory(config.cwd ?? commands.homedir())
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
//#endregion
|
|
122
|
+
//#region src/env.ts
|
|
123
|
+
/**
|
|
124
|
+
* Filters inherited credentials, preserves explicit credentials and refuses reserved names.
|
|
125
|
+
* Each source is validated before layer overrides. The gateway controls proxies; configured
|
|
126
|
+
* proxy names are refused. Values are preserved exactly and never included in errors.
|
|
127
|
+
*/
|
|
128
|
+
function childEnvironment(input) {
|
|
129
|
+
const { commands } = input;
|
|
130
|
+
const configuredSources = [];
|
|
131
|
+
for (const entry of input.config.env) {
|
|
132
|
+
const name = commands.platform === "win32" ? entry.name.toUpperCase() : entry.name;
|
|
133
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(entry.name)) throw new Error("invalid-environment-input");
|
|
134
|
+
if (name.startsWith("YAOGUANG_")) throw new Error("configured environment variable is reserved");
|
|
135
|
+
if (/^(?:https?|all|ftp|no)_proxy$/i.test(name)) throw new Error("proxy-environment-managed-by-gateway");
|
|
136
|
+
const value = entry.secret ? input.secret(entry.name) : entry.value ?? "";
|
|
137
|
+
if (value === void 0) throw new MissingCredentialError(entry.name);
|
|
138
|
+
configuredSources.push({ [entry.name]: value });
|
|
139
|
+
}
|
|
140
|
+
const configured = {};
|
|
141
|
+
for (const source of configuredSources) for (const [name, value] of Object.entries(source)) {
|
|
142
|
+
const key = commands.platform === "win32" ? name.toUpperCase() : name;
|
|
143
|
+
if (Object.hasOwn(configured, key) && configured[key] !== value) throw new Error(`environment-name-conflict: ${key}`);
|
|
144
|
+
configured[key] = value;
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
env: commands.environment([commands.childEnvironment(input.inherited, "protocol"), input.proxy]),
|
|
148
|
+
configuredEnv: commands.environment([configured])
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
/** A configured credential variable has no stored value. */
|
|
152
|
+
var MissingCredentialError = class extends Error {
|
|
153
|
+
/** Variable name whose credential must be supplied. */
|
|
154
|
+
variable;
|
|
155
|
+
/** Reports the missing variable without revealing a credential value. */
|
|
156
|
+
constructor(variable) {
|
|
157
|
+
super(`credential for ${variable} is not set`);
|
|
158
|
+
this.name = "MissingCredentialError";
|
|
159
|
+
this.variable = variable;
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
//#endregion
|
|
163
|
+
//#region src/redact.ts
|
|
164
|
+
/** What replaces a credential found in outward text. */
|
|
165
|
+
const REDACTED = "[已隐去]";
|
|
166
|
+
/** The text a status reason becomes when it contains a credential. */
|
|
167
|
+
const REDACTED_REASON = "原因中含有凭据,已整段隐去";
|
|
168
|
+
/** Fields of an OAuth JSON credential whose values are secrets in their own right. */
|
|
169
|
+
const JSON_SECRETS = [
|
|
170
|
+
"access_token",
|
|
171
|
+
"refresh_token",
|
|
172
|
+
"id_token",
|
|
173
|
+
"client_secret"
|
|
174
|
+
];
|
|
175
|
+
/**
|
|
176
|
+
* The values to compare outward text against, from the credentials a request
|
|
177
|
+
* actually used. A JSON credential (`oauth.tokens`, `oauth.client`) is split
|
|
178
|
+
* into its secret fields as well, because a server echoes a token, never the
|
|
179
|
+
* JSON document holding it. Values shorter than four characters are left out:
|
|
180
|
+
* replacing every occurrence of one would destroy the text without protecting
|
|
181
|
+
* anything a hint (the last four characters) does not already show.
|
|
182
|
+
*/
|
|
183
|
+
function secretValues(raw) {
|
|
184
|
+
const values = /* @__PURE__ */ new Set();
|
|
185
|
+
for (const value of raw) {
|
|
186
|
+
if (value === void 0) continue;
|
|
187
|
+
values.add(value);
|
|
188
|
+
if (!value.startsWith("{")) continue;
|
|
189
|
+
try {
|
|
190
|
+
const parsed = JSON.parse(value);
|
|
191
|
+
for (const key of JSON_SECRETS) {
|
|
192
|
+
const field = parsed[key];
|
|
193
|
+
if (typeof field === "string") values.add(field);
|
|
194
|
+
}
|
|
195
|
+
} catch {}
|
|
196
|
+
}
|
|
197
|
+
return [...values].filter((value) => value.length >= 4).sort((a, b) => b.length - a.length);
|
|
198
|
+
}
|
|
199
|
+
/** Whether `text` contains any of `secrets`. */
|
|
200
|
+
function containsSecret(text, secrets) {
|
|
201
|
+
return secrets.some((secret) => text.includes(secret));
|
|
202
|
+
}
|
|
203
|
+
/** `text` with every occurrence of every secret replaced by `[已隐去]`. */
|
|
204
|
+
function redact(text, secrets) {
|
|
205
|
+
let out = text;
|
|
206
|
+
for (const secret of secrets) if (out.includes(secret)) out = out.split(secret).join(REDACTED);
|
|
207
|
+
return out;
|
|
208
|
+
}
|
|
209
|
+
/** A status reason as it may be shown: hidden whole when it contains a secret. */
|
|
210
|
+
function redactReason(text, secrets) {
|
|
211
|
+
return containsSecret(text, secrets) ? REDACTED_REASON : text;
|
|
212
|
+
}
|
|
213
|
+
//#endregion
|
|
214
|
+
//#region src/transport/limits.ts
|
|
215
|
+
/** Response framing bounds applied before the SDK accumulates or decodes upstream content. */
|
|
216
|
+
/** The maximum complete encoded response admitted by this owner. */
|
|
217
|
+
const RESPONSE_BYTES = 8388608;
|
|
218
|
+
const resourceBudget = new AsyncLocalStorage();
|
|
219
|
+
/** Binds one original resource request to its conservative encoded protocol capacity. */
|
|
220
|
+
function withResourceBudget(maxBytes, request) {
|
|
221
|
+
return resourceBudget.run(maxBytes, request);
|
|
222
|
+
}
|
|
223
|
+
/** Returns the current request's bound without adding vendor fields to the protocol. */
|
|
224
|
+
function responseBudget() {
|
|
225
|
+
const raw = resourceBudget.getStore();
|
|
226
|
+
return raw === void 0 ? RESPONSE_BYTES : Math.min(RESPONSE_BYTES, Math.max(6 * raw, 4 * Math.ceil(raw / 3)) + 65536);
|
|
227
|
+
}
|
|
228
|
+
/** Safe limit failure without an upstream body or credentials. */
|
|
229
|
+
function responseLimit() {
|
|
230
|
+
return Object.assign(/* @__PURE__ */ new Error("MCP response exceeds declared budget"), { code: "read-limit" });
|
|
231
|
+
}
|
|
232
|
+
/** Bounds ordinary bodies and each SSE event while preserving HTTP metadata and cancellation. */
|
|
233
|
+
function boundedFetch(fetch, maxBytes = RESPONSE_BYTES) {
|
|
234
|
+
return async (input, init) => {
|
|
235
|
+
const capacity = Math.min(maxBytes, responseBudget());
|
|
236
|
+
const response = await fetch(input, init);
|
|
237
|
+
if (!response.body) return response;
|
|
238
|
+
const sse = response.headers.get("content-type")?.includes("text/event-stream") ?? false;
|
|
239
|
+
const length = Number(response.headers.get("content-length"));
|
|
240
|
+
if (!sse && Number.isFinite(length) && length > capacity) {
|
|
241
|
+
await response.body.cancel();
|
|
242
|
+
throw responseLimit();
|
|
243
|
+
}
|
|
244
|
+
const reader = response.body.getReader();
|
|
245
|
+
let bytes = 0, lineBytes = 0;
|
|
246
|
+
const body = new ReadableStream({
|
|
247
|
+
async pull(controller) {
|
|
248
|
+
try {
|
|
249
|
+
const next = await reader.read();
|
|
250
|
+
if (next.done) {
|
|
251
|
+
controller.close();
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
if (sse) for (const byte of next.value) {
|
|
255
|
+
bytes++;
|
|
256
|
+
if (bytes > capacity) throw responseLimit();
|
|
257
|
+
if (byte === 10) {
|
|
258
|
+
if (lineBytes === 0 || lineBytes === 1 && previous === 13) bytes = 0;
|
|
259
|
+
lineBytes = 0;
|
|
260
|
+
} else lineBytes++;
|
|
261
|
+
previous = byte;
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
bytes += next.value.byteLength;
|
|
265
|
+
if (bytes > capacity) throw responseLimit();
|
|
266
|
+
}
|
|
267
|
+
controller.enqueue(next.value);
|
|
268
|
+
} catch (error) {
|
|
269
|
+
await reader.cancel(error).catch(() => {});
|
|
270
|
+
controller.error(error);
|
|
271
|
+
}
|
|
272
|
+
},
|
|
273
|
+
cancel: (reason) => reader.cancel(reason)
|
|
274
|
+
});
|
|
275
|
+
let previous = -1;
|
|
276
|
+
const bounded = new Response(body, {
|
|
277
|
+
status: response.status,
|
|
278
|
+
statusText: response.statusText,
|
|
279
|
+
headers: response.headers
|
|
280
|
+
});
|
|
281
|
+
for (const key of [
|
|
282
|
+
"url",
|
|
283
|
+
"redirected",
|
|
284
|
+
"type"
|
|
285
|
+
]) Object.defineProperty(bounded, key, { value: response[key] });
|
|
286
|
+
return bounded;
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
//#endregion
|
|
290
|
+
//#region src/transport/http.ts
|
|
291
|
+
/**
|
|
292
|
+
* A Streamable HTTP transport whose every request goes through the gateway's
|
|
293
|
+
* network service: the endpoint is one a person configured, so it takes the
|
|
294
|
+
* gateway's route and never passes through the allowed-host list. `headers`
|
|
295
|
+
* carries the static header credentials; `authProvider` the OAuth tokens.
|
|
296
|
+
*/
|
|
297
|
+
function httpTransport(input) {
|
|
298
|
+
return new StreamableHTTPClientTransport(new URL(input.url), {
|
|
299
|
+
fetch: boundedFetch(input.fetch),
|
|
300
|
+
requestInit: { headers: { ...input.headers } },
|
|
301
|
+
...input.authProvider ? { authProvider: input.authProvider } : {}
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
//#endregion
|
|
305
|
+
//#region src/transport/output-schema.ts
|
|
306
|
+
function record(value) {
|
|
307
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
308
|
+
}
|
|
309
|
+
function objectOnly(schema) {
|
|
310
|
+
let remaining = 256;
|
|
311
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
312
|
+
const resolve = (ref) => {
|
|
313
|
+
if (typeof ref !== "string" || !ref.startsWith("#/")) return void 0;
|
|
314
|
+
let pointer;
|
|
315
|
+
try {
|
|
316
|
+
pointer = decodeURIComponent(ref.slice(1));
|
|
317
|
+
} catch {
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
let target = schema;
|
|
321
|
+
for (const part of pointer.slice(1).split("/")) {
|
|
322
|
+
if (--remaining < 0 || /~(?:[^01]|$)/.test(part)) return void 0;
|
|
323
|
+
const key = part.replaceAll("~1", "/").replaceAll("~0", "~");
|
|
324
|
+
if (!record(target) || "$id" in target || !Object.hasOwn(target, key)) return void 0;
|
|
325
|
+
target = target[key];
|
|
326
|
+
}
|
|
327
|
+
return target;
|
|
328
|
+
};
|
|
329
|
+
const visit = (node, depth) => {
|
|
330
|
+
if (--remaining < 0 || depth > 64 || !record(node) || ancestors.has(node)) return false;
|
|
331
|
+
if ("$id" in node || "$dynamicRef" in node || "$recursiveRef" in node || "allOf" in node) return false;
|
|
332
|
+
ancestors.add(node);
|
|
333
|
+
try {
|
|
334
|
+
let proven = false;
|
|
335
|
+
if ("type" in node) {
|
|
336
|
+
if (node.type !== "object") return false;
|
|
337
|
+
proven = true;
|
|
338
|
+
}
|
|
339
|
+
if ("$ref" in node) {
|
|
340
|
+
if (!visit(resolve(node.$ref), depth + 1)) return false;
|
|
341
|
+
proven = true;
|
|
342
|
+
}
|
|
343
|
+
for (const key of ["oneOf", "anyOf"]) {
|
|
344
|
+
if (!(key in node)) continue;
|
|
345
|
+
const branches = node[key];
|
|
346
|
+
if (!Array.isArray(branches) || branches.length === 0 || !branches.every((branch) => visit(branch, depth + 1))) return false;
|
|
347
|
+
proven = true;
|
|
348
|
+
}
|
|
349
|
+
return proven;
|
|
350
|
+
} finally {
|
|
351
|
+
ancestors.delete(node);
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
return visit(schema, 0);
|
|
355
|
+
}
|
|
356
|
+
function normalizeResult(result) {
|
|
357
|
+
if (!Array.isArray(result.tools)) return result;
|
|
358
|
+
let changed = false;
|
|
359
|
+
const tools = result.tools.map((tool) => {
|
|
360
|
+
if (!record(tool) || !record(tool.outputSchema)) return tool;
|
|
361
|
+
const schema = tool.outputSchema;
|
|
362
|
+
if ("type" in schema || !objectOnly(schema)) return tool;
|
|
363
|
+
changed = true;
|
|
364
|
+
return {
|
|
365
|
+
...tool,
|
|
366
|
+
outputSchema: {
|
|
367
|
+
...schema,
|
|
368
|
+
type: "object"
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
});
|
|
372
|
+
return changed ? {
|
|
373
|
+
...result,
|
|
374
|
+
tools
|
|
375
|
+
} : result;
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Adds a missing root object type only to provably object-only tool output schemas.
|
|
379
|
+
* Only replies to tracked tools/list requests are normalized; the SDK still parses
|
|
380
|
+
* the complete reply, caches output validators and validates subsequent tool results.
|
|
381
|
+
* Delegates transport ownership, session metadata and protocol negotiation unchanged.
|
|
382
|
+
*/
|
|
383
|
+
function objectOutputSchemas(transport) {
|
|
384
|
+
const pending = /* @__PURE__ */ new Set();
|
|
385
|
+
const wrapped = {
|
|
386
|
+
start() {
|
|
387
|
+
transport.onclose = () => {
|
|
388
|
+
pending.clear();
|
|
389
|
+
wrapped.onclose?.();
|
|
390
|
+
};
|
|
391
|
+
transport.onerror = (error) => wrapped.onerror?.(error);
|
|
392
|
+
transport.onmessage = (message, extra) => {
|
|
393
|
+
if (("result" in message || "error" in message) && message.id !== void 0 && pending.delete(message.id)) {
|
|
394
|
+
if ("result" in message) {
|
|
395
|
+
const result = normalizeResult(message.result);
|
|
396
|
+
if (result !== message.result) {
|
|
397
|
+
wrapped.onmessage?.({
|
|
398
|
+
...message,
|
|
399
|
+
result
|
|
400
|
+
}, extra);
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
wrapped.onmessage?.(message, extra);
|
|
406
|
+
};
|
|
407
|
+
return transport.start();
|
|
408
|
+
},
|
|
409
|
+
async send(message, options) {
|
|
410
|
+
const id = "id" in message ? message.id : void 0;
|
|
411
|
+
if ("method" in message && message.method === "tools/list" && id !== void 0) pending.add(id);
|
|
412
|
+
if ("method" in message && message.method === "notifications/cancelled") {
|
|
413
|
+
const requestId = message.params?.requestId;
|
|
414
|
+
if (typeof requestId === "string" || typeof requestId === "number") pending.delete(requestId);
|
|
415
|
+
}
|
|
416
|
+
try {
|
|
417
|
+
await transport.send(message, options);
|
|
418
|
+
} catch (error) {
|
|
419
|
+
if (id !== void 0) pending.delete(id);
|
|
420
|
+
throw error;
|
|
421
|
+
}
|
|
422
|
+
},
|
|
423
|
+
close: () => transport.close(),
|
|
424
|
+
get sessionId() {
|
|
425
|
+
return transport.sessionId;
|
|
426
|
+
},
|
|
427
|
+
setProtocolVersion: (version) => transport.setProtocolVersion?.(version)
|
|
428
|
+
};
|
|
429
|
+
return wrapped;
|
|
430
|
+
}
|
|
431
|
+
//#endregion
|
|
432
|
+
//#region src/transport/stdio.ts
|
|
433
|
+
/**
|
|
434
|
+
* An MCP transport over a host-owned protocol process: newline-delimited
|
|
435
|
+
* JSON-RPC on its stdin and stdout. The host spawned the process and alone
|
|
436
|
+
* signals it; `close()` asks the host to stop the group and settles once it
|
|
437
|
+
* has, rejecting when the host reports the cleanup failed.
|
|
438
|
+
*/
|
|
439
|
+
var ProcessTransport = class {
|
|
440
|
+
onclose;
|
|
441
|
+
onerror;
|
|
442
|
+
onmessage;
|
|
443
|
+
process;
|
|
444
|
+
buffer = new ReadBuffer();
|
|
445
|
+
responseBounds = /* @__PURE__ */ new Map();
|
|
446
|
+
bufferedBytes = 0;
|
|
447
|
+
closed = false;
|
|
448
|
+
stopping;
|
|
449
|
+
maxBytes;
|
|
450
|
+
constructor(process, maxBytes = RESPONSE_BYTES) {
|
|
451
|
+
this.process = process;
|
|
452
|
+
this.maxBytes = maxBytes;
|
|
453
|
+
}
|
|
454
|
+
async start() {
|
|
455
|
+
const { stdout, stdin } = this.process;
|
|
456
|
+
stdout.on("data", (chunk) => {
|
|
457
|
+
if (this.closed) return;
|
|
458
|
+
let offset = 0;
|
|
459
|
+
while (offset < chunk.length) {
|
|
460
|
+
const end = chunk.indexOf(10, offset);
|
|
461
|
+
const finish = end === -1 ? chunk.length : end + 1;
|
|
462
|
+
const fragment = chunk.subarray(offset, finish);
|
|
463
|
+
this.bufferedBytes += fragment.length;
|
|
464
|
+
const maximum = this.responseBounds.size ? Math.max(...this.responseBounds.values()) : this.maxBytes;
|
|
465
|
+
if (this.bufferedBytes > Math.min(this.maxBytes, maximum)) {
|
|
466
|
+
this.buffer.clear();
|
|
467
|
+
this.onerror?.(responseLimit());
|
|
468
|
+
this.close().catch((error) => this.onerror?.(error));
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
try {
|
|
472
|
+
this.buffer.append(fragment);
|
|
473
|
+
if (end !== -1) {
|
|
474
|
+
this.bufferedBytes = 0;
|
|
475
|
+
const message = this.buffer.readMessage();
|
|
476
|
+
if (message) {
|
|
477
|
+
if ("id" in message && message.id !== void 0) this.responseBounds.delete(message.id);
|
|
478
|
+
this.onmessage?.(message);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
} catch (error) {
|
|
482
|
+
this.bufferedBytes = 0;
|
|
483
|
+
this.buffer.clear();
|
|
484
|
+
this.onerror?.(error);
|
|
485
|
+
}
|
|
486
|
+
offset = finish;
|
|
487
|
+
}
|
|
488
|
+
});
|
|
489
|
+
stdout.on("error", (error) => this.onerror?.(error));
|
|
490
|
+
stdin.on("error", (error) => this.onerror?.(error));
|
|
491
|
+
this.process.exited.then(() => this.finish(), () => this.finish());
|
|
492
|
+
}
|
|
493
|
+
send(message) {
|
|
494
|
+
if (this.closed) return Promise.reject(/* @__PURE__ */ new Error("server process is not running"));
|
|
495
|
+
if ("method" in message && message.method === "notifications/cancelled" && "params" in message) {
|
|
496
|
+
const id = message.params?.requestId;
|
|
497
|
+
if (typeof id === "string" || typeof id === "number") this.responseBounds.delete(id);
|
|
498
|
+
}
|
|
499
|
+
if ("id" in message && message.id !== void 0 && "method" in message) {
|
|
500
|
+
if (this.responseBounds.size >= 1024) return Promise.reject(Object.assign(/* @__PURE__ */ new Error("too many pending MCP requests"), { code: "read-limit" }));
|
|
501
|
+
this.responseBounds.set(message.id, responseBudget());
|
|
502
|
+
}
|
|
503
|
+
return new Promise((resolve, reject) => {
|
|
504
|
+
const { stdin } = this.process;
|
|
505
|
+
const done = (error) => error ? reject(error) : void 0;
|
|
506
|
+
if (stdin.write(serializeMessage(message), done)) resolve();
|
|
507
|
+
else stdin.once("drain", () => resolve());
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
close() {
|
|
511
|
+
this.stopping ??= Promise.resolve().then(() => this.process.stop()).then(() => this.finish()).catch((error) => {
|
|
512
|
+
this.stopping = void 0;
|
|
513
|
+
try {
|
|
514
|
+
this.finish();
|
|
515
|
+
} catch (notification) {
|
|
516
|
+
throw new AggregateError([error, notification], "transport stop and close notification failed", { cause: error });
|
|
517
|
+
}
|
|
518
|
+
throw error;
|
|
519
|
+
});
|
|
520
|
+
return this.stopping;
|
|
521
|
+
}
|
|
522
|
+
/** Whether `close()` was asked for, as opposed to the process ending on its own. */
|
|
523
|
+
get stopRequested() {
|
|
524
|
+
return this.stopping !== void 0;
|
|
525
|
+
}
|
|
526
|
+
/** The promise of the stop in progress, if any. */
|
|
527
|
+
get stopped() {
|
|
528
|
+
return this.stopping;
|
|
529
|
+
}
|
|
530
|
+
finish() {
|
|
531
|
+
if (this.closed) return;
|
|
532
|
+
this.closed = true;
|
|
533
|
+
this.buffer.clear();
|
|
534
|
+
this.responseBounds.clear();
|
|
535
|
+
this.onclose?.();
|
|
536
|
+
}
|
|
537
|
+
};
|
|
538
|
+
//#endregion
|
|
539
|
+
//#region src/connections.ts
|
|
540
|
+
const TIMING = {
|
|
541
|
+
handshakeMs: 3e4,
|
|
542
|
+
backoffMs: 1e3,
|
|
543
|
+
maxBackoffMs: 3e4,
|
|
544
|
+
maxAttempts: 10,
|
|
545
|
+
stableMs: 3e4,
|
|
546
|
+
concurrency: 4,
|
|
547
|
+
stderrSettleMs: 50
|
|
548
|
+
};
|
|
549
|
+
const UNACKNOWLEDGED = "尚未确认以用户权限运行";
|
|
550
|
+
const CREDENTIAL_UNAVAILABLE = "凭据无法读取,请重新填写";
|
|
551
|
+
const CLIENT_INFO = {
|
|
552
|
+
name: "yaoguang",
|
|
553
|
+
version: "1.0.0"
|
|
554
|
+
};
|
|
555
|
+
var Superseded = class extends Error {};
|
|
556
|
+
function isNeedsAuth(error) {
|
|
557
|
+
const name = error?.name;
|
|
558
|
+
return name === "UnauthorizedError" || name === "NeedsAuthorizationError" || error?.constructor?.name === "UnauthorizedError";
|
|
559
|
+
}
|
|
560
|
+
const messageOf$1 = (error) => error instanceof Error ? error.message : String(error);
|
|
561
|
+
/**
|
|
562
|
+
* One connection per enabled server: the state machine, generations, the
|
|
563
|
+
* start queue, handshake deadline, paged listing, serial snapshot updates,
|
|
564
|
+
* reconnection with backoff, and closing.
|
|
565
|
+
*
|
|
566
|
+
* Every change of configuration, enablement, authorization or credentials
|
|
567
|
+
* bumps the server's generation first; anything that resolves afterwards
|
|
568
|
+
* compares its generation before it writes, registers or changes a status.
|
|
569
|
+
*/
|
|
570
|
+
function createConnections(deps) {
|
|
571
|
+
const timing = {
|
|
572
|
+
...TIMING,
|
|
573
|
+
...deps.timing
|
|
574
|
+
};
|
|
575
|
+
const connections = /* @__PURE__ */ new Map();
|
|
576
|
+
let closed = false;
|
|
577
|
+
let active = 0;
|
|
578
|
+
/** Attempts and test connections under way; shutdown waits for each. */
|
|
579
|
+
const running = /* @__PURE__ */ new Set();
|
|
580
|
+
/** Transports of attempts and tests not yet live; shutdown closes them so
|
|
581
|
+
* a handshake in progress ends at once rather than at its deadline. */
|
|
582
|
+
const starting = /* @__PURE__ */ new Set();
|
|
583
|
+
const receipts = /* @__PURE__ */ new Set();
|
|
584
|
+
const pendingStops = /* @__PURE__ */ new Map();
|
|
585
|
+
const cleanupOwners = /* @__PURE__ */ new Map();
|
|
586
|
+
const collections = /* @__PURE__ */ new Set();
|
|
587
|
+
const changed = (id) => {
|
|
588
|
+
let held = false;
|
|
589
|
+
for (const batch of collections) if (batch.ids.has(id)) {
|
|
590
|
+
held = true;
|
|
591
|
+
batch.dirty.add(id);
|
|
592
|
+
}
|
|
593
|
+
if (!held) deps.onChanged(id);
|
|
594
|
+
};
|
|
595
|
+
let shuttingDown;
|
|
596
|
+
const track = (work) => {
|
|
597
|
+
running.add(work);
|
|
598
|
+
work.finally(() => running.delete(work)).catch(() => {});
|
|
599
|
+
return work;
|
|
600
|
+
};
|
|
601
|
+
const waiting = [];
|
|
602
|
+
const acquire = async () => {
|
|
603
|
+
if (active < timing.concurrency) {
|
|
604
|
+
active += 1;
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
await new Promise((resolve) => waiting.push(resolve));
|
|
608
|
+
active += 1;
|
|
609
|
+
};
|
|
610
|
+
const release = () => {
|
|
611
|
+
active -= 1;
|
|
612
|
+
waiting.shift()?.();
|
|
613
|
+
};
|
|
614
|
+
const connection = (id) => {
|
|
615
|
+
let found = connections.get(id);
|
|
616
|
+
if (!found) {
|
|
617
|
+
found = {
|
|
618
|
+
id,
|
|
619
|
+
pending: /* @__PURE__ */ new Set(),
|
|
620
|
+
gen: 0,
|
|
621
|
+
status: { state: "disabled" },
|
|
622
|
+
attempts: 0,
|
|
623
|
+
lastStop: Promise.resolve(),
|
|
624
|
+
queue: Promise.resolve(),
|
|
625
|
+
connected: false
|
|
626
|
+
};
|
|
627
|
+
connections.set(id, found);
|
|
628
|
+
}
|
|
629
|
+
return found;
|
|
630
|
+
};
|
|
631
|
+
const setStatus = (conn, status) => {
|
|
632
|
+
conn.status = status;
|
|
633
|
+
changed(conn.id);
|
|
634
|
+
};
|
|
635
|
+
const clearTimers = (conn) => {
|
|
636
|
+
if (conn.retry) clearTimeout(conn.retry);
|
|
637
|
+
if (conn.stable) clearTimeout(conn.stable);
|
|
638
|
+
conn.retry = void 0;
|
|
639
|
+
conn.stable = void 0;
|
|
640
|
+
};
|
|
641
|
+
const stopTransport = (transport, conn) => {
|
|
642
|
+
pendingStops.set(transport, conn);
|
|
643
|
+
const task = Promise.resolve().then(() => transport.close()).then(() => {
|
|
644
|
+
pendingStops.delete(transport);
|
|
645
|
+
});
|
|
646
|
+
conn.lastStop = task;
|
|
647
|
+
task.catch(() => {});
|
|
648
|
+
return task;
|
|
649
|
+
};
|
|
650
|
+
/** Closes the live transport, retaining failed cleanup for the next drain. */
|
|
651
|
+
const drop = (conn) => {
|
|
652
|
+
const live = conn.live;
|
|
653
|
+
conn.live = void 0;
|
|
654
|
+
if (live) stopTransport(live.transport, conn);
|
|
655
|
+
};
|
|
656
|
+
const withdraw = (conn) => {
|
|
657
|
+
if (conn.snapshot === void 0) return;
|
|
658
|
+
conn.snapshot = void 0;
|
|
659
|
+
deps.onSnapshot(conn.id, void 0);
|
|
660
|
+
};
|
|
661
|
+
const publish = (conn, snapshot) => {
|
|
662
|
+
conn.snapshot = snapshot;
|
|
663
|
+
deps.onSnapshot(conn.id, snapshot);
|
|
664
|
+
};
|
|
665
|
+
/** The credential values and transport one attempt uses. Throws a reason.
|
|
666
|
+
* `secrets` answers the values current at the moment it is called. */
|
|
667
|
+
const prepare = async (record, conn, gen) => {
|
|
668
|
+
const current = () => {
|
|
669
|
+
if (closed || conn.gen !== gen) throw new Superseded();
|
|
670
|
+
};
|
|
671
|
+
const read = (name) => deps.credentials.get(record.id, name);
|
|
672
|
+
if (record.transport === "stdio") {
|
|
673
|
+
const used = [];
|
|
674
|
+
const proxy = (await deps.network.environment()).env;
|
|
675
|
+
const env = childEnvironment({
|
|
676
|
+
commands: deps.commands,
|
|
677
|
+
inherited: deps.inherited?.() ?? deps.commands.env,
|
|
678
|
+
proxy,
|
|
679
|
+
config: record.config,
|
|
680
|
+
secret: (name) => {
|
|
681
|
+
const value = read(envCredential(name));
|
|
682
|
+
used.push(value);
|
|
683
|
+
return value;
|
|
684
|
+
}
|
|
685
|
+
});
|
|
686
|
+
const effective = await deps.commands.inspect(record.config.command, deps.commands.environment([env.env, env.configuredEnv]));
|
|
687
|
+
if (effective.status !== "found" || effective.path !== record.config.command) throw new Error(`command-unavailable: ${effective.reason ?? "command-resolution-changed"}`);
|
|
688
|
+
const cwd = await deps.commands.directory(record.config.cwd ?? deps.commands.homedir());
|
|
689
|
+
if (record.config.cwd !== cwd) throw new Error("cwd-changed: acknowledge the resolved directory again");
|
|
690
|
+
current();
|
|
691
|
+
const attempt = deps.processes.start({
|
|
692
|
+
owner: deps.owner,
|
|
693
|
+
argv: [record.config.command, ...record.config.args],
|
|
694
|
+
cwd,
|
|
695
|
+
env: env.env,
|
|
696
|
+
configuredEnv: env.configuredEnv,
|
|
697
|
+
beforeSpawn: current
|
|
698
|
+
});
|
|
699
|
+
receipts.add(attempt);
|
|
700
|
+
conn.lastReceipt = attempt;
|
|
701
|
+
let cleaned = false;
|
|
702
|
+
attempt.cleaned.then(() => {
|
|
703
|
+
cleaned = true;
|
|
704
|
+
receipts.delete(attempt);
|
|
705
|
+
if (conn.failedStart === attempt) conn.failedStart = void 0;
|
|
706
|
+
if (conn.lastReceipt === attempt) conn.lastStop = Promise.resolve();
|
|
707
|
+
});
|
|
708
|
+
let process_;
|
|
709
|
+
let handedOff = false;
|
|
710
|
+
try {
|
|
711
|
+
process_ = await attempt.ready;
|
|
712
|
+
handedOff = true;
|
|
713
|
+
current();
|
|
714
|
+
} catch (primary) {
|
|
715
|
+
let failure = primary;
|
|
716
|
+
if (handedOff) try {
|
|
717
|
+
await attempt.stop();
|
|
718
|
+
} catch (cleanup) {
|
|
719
|
+
failure = new AggregateError([primary, cleanup], "MCP startup cleanup failed", { cause: primary });
|
|
720
|
+
}
|
|
721
|
+
if (!cleaned) {
|
|
722
|
+
conn.failedStart = attempt;
|
|
723
|
+
conn.lastStop = Promise.reject(failure);
|
|
724
|
+
conn.lastStop.catch(() => {});
|
|
725
|
+
}
|
|
726
|
+
throw failure;
|
|
727
|
+
}
|
|
728
|
+
const fixed = secretValues(used);
|
|
729
|
+
return {
|
|
730
|
+
transport: new ProcessTransport(process_),
|
|
731
|
+
secrets: () => fixed,
|
|
732
|
+
process: process_
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
const headers = {};
|
|
736
|
+
const used = [];
|
|
737
|
+
if (record.config.auth === "headers") for (const name of record.config.headers) {
|
|
738
|
+
const value = read(headerCredential(name));
|
|
739
|
+
if (value === void 0) throw new MissingCredentialError(`header ${name}`);
|
|
740
|
+
headers[name] = value;
|
|
741
|
+
used.push(value);
|
|
742
|
+
}
|
|
743
|
+
const oauth = record.config.auth === "oauth";
|
|
744
|
+
return {
|
|
745
|
+
transport: httpTransport({
|
|
746
|
+
url: record.config.url,
|
|
747
|
+
fetch: deps.network.fetch,
|
|
748
|
+
headers,
|
|
749
|
+
...record.config.auth === "oauth" ? { authProvider: deps.oauth.connectionProvider(record.id, record.config.url) } : {}
|
|
750
|
+
}),
|
|
751
|
+
secrets: () => secretValues(oauth ? [...used, ...deps.oauth.secrets(record.id)] : used)
|
|
752
|
+
};
|
|
753
|
+
};
|
|
754
|
+
/** Lists everything the server declared, page by page, in full. */
|
|
755
|
+
const list = async (client, capabilities, options, only, previous) => {
|
|
756
|
+
const pages = async (fetchPage) => {
|
|
757
|
+
const items = [];
|
|
758
|
+
const seen = /* @__PURE__ */ new Set();
|
|
759
|
+
let cursor;
|
|
760
|
+
do {
|
|
761
|
+
const page = await fetchPage(cursor);
|
|
762
|
+
items.push(...page.items);
|
|
763
|
+
cursor = page.nextCursor;
|
|
764
|
+
if (cursor !== void 0) {
|
|
765
|
+
if (seen.has(cursor)) throw new Error("the server repeated a list cursor");
|
|
766
|
+
seen.add(cursor);
|
|
767
|
+
}
|
|
768
|
+
} while (cursor !== void 0);
|
|
769
|
+
return items;
|
|
770
|
+
};
|
|
771
|
+
/** A kind outside `only` keeps what `previous` had; an undeclared one is empty. */
|
|
772
|
+
const read = async (kind, fetchPage) => {
|
|
773
|
+
if (only !== void 0 && only !== kind) return void 0;
|
|
774
|
+
return capabilities[kind] === void 0 ? [] : await pages(fetchPage);
|
|
775
|
+
};
|
|
776
|
+
const next = (cursor) => cursor ? { cursor } : {};
|
|
777
|
+
const tools = await read("tools", async (cursor) => {
|
|
778
|
+
const page = await client.listTools(next(cursor), options);
|
|
779
|
+
return {
|
|
780
|
+
items: page.tools,
|
|
781
|
+
...page.nextCursor ? { nextCursor: page.nextCursor } : {}
|
|
782
|
+
};
|
|
783
|
+
});
|
|
784
|
+
const resources = await read("resources", async (cursor) => {
|
|
785
|
+
const page = await client.listResources(next(cursor), options);
|
|
786
|
+
return {
|
|
787
|
+
items: page.resources,
|
|
788
|
+
...page.nextCursor ? { nextCursor: page.nextCursor } : {}
|
|
789
|
+
};
|
|
790
|
+
});
|
|
791
|
+
const prompts = await read("prompts", async (cursor) => {
|
|
792
|
+
const page = await client.listPrompts(next(cursor), options);
|
|
793
|
+
return {
|
|
794
|
+
items: page.prompts,
|
|
795
|
+
...page.nextCursor ? { nextCursor: page.nextCursor } : {}
|
|
796
|
+
};
|
|
797
|
+
});
|
|
798
|
+
const description = client.getServerVersion()?.description?.trim();
|
|
799
|
+
return {
|
|
800
|
+
...description ? { description } : {},
|
|
801
|
+
tools: (tools ?? previous?.tools ?? []).map((tool) => ({
|
|
802
|
+
name: tool.name,
|
|
803
|
+
...tool.description ? { description: tool.description } : {},
|
|
804
|
+
inputSchema: tool.inputSchema
|
|
805
|
+
})),
|
|
806
|
+
resources: (resources ?? previous?.resources ?? []).map((resource) => ({
|
|
807
|
+
uri: resource.uri,
|
|
808
|
+
...resource.name ? { name: resource.name } : {},
|
|
809
|
+
...resource.description ? { description: resource.description } : {},
|
|
810
|
+
...resource.mimeType ? { mimeType: resource.mimeType } : {}
|
|
811
|
+
})),
|
|
812
|
+
prompts: (prompts ?? previous?.prompts ?? []).map((prompt) => ({
|
|
813
|
+
name: prompt.name,
|
|
814
|
+
...prompt.description ? { description: prompt.description } : {},
|
|
815
|
+
...prompt.arguments ? { arguments: prompt.arguments } : {}
|
|
816
|
+
}))
|
|
817
|
+
};
|
|
818
|
+
};
|
|
819
|
+
/** Initialize plus the first full listing, inside the handshake deadline. */
|
|
820
|
+
const handshake = async (transport) => {
|
|
821
|
+
const client = new Client(CLIENT_INFO, { capabilities: {} });
|
|
822
|
+
const deadline = new AbortController();
|
|
823
|
+
const timer = setTimeout(() => deadline.abort(), timing.handshakeMs);
|
|
824
|
+
const options = {
|
|
825
|
+
signal: deadline.signal,
|
|
826
|
+
timeout: timing.handshakeMs
|
|
827
|
+
};
|
|
828
|
+
try {
|
|
829
|
+
await client.connect(objectOutputSchemas(transport), options);
|
|
830
|
+
const capabilities = client.getServerCapabilities() ?? {};
|
|
831
|
+
return {
|
|
832
|
+
client,
|
|
833
|
+
capabilities,
|
|
834
|
+
snapshot: await list(client, capabilities, options)
|
|
835
|
+
};
|
|
836
|
+
} catch (error) {
|
|
837
|
+
await client.close().catch(() => {});
|
|
838
|
+
if (deadline.signal.aborted) throw new Error(`handshake timed out after ${Math.round(timing.handshakeMs / 1e3)} s`);
|
|
839
|
+
throw error;
|
|
840
|
+
} finally {
|
|
841
|
+
clearTimeout(timer);
|
|
842
|
+
}
|
|
843
|
+
};
|
|
844
|
+
const stderrReason = async (process_, base) => {
|
|
845
|
+
if (!process_) return base;
|
|
846
|
+
await new Promise((resolve) => setTimeout(resolve, timing.stderrSettleMs));
|
|
847
|
+
const tail = process_.stderrTail().trim();
|
|
848
|
+
return tail ? `${base}: ${tail.slice(-2e3)}` : base;
|
|
849
|
+
};
|
|
850
|
+
const scheduleRetry = (conn, gen, reason) => {
|
|
851
|
+
if (closed || conn.gen !== gen) return;
|
|
852
|
+
conn.attempts += 1;
|
|
853
|
+
if (conn.attempts > timing.maxAttempts) {
|
|
854
|
+
withdraw(conn);
|
|
855
|
+
setStatus(conn, {
|
|
856
|
+
state: "failed",
|
|
857
|
+
reason
|
|
858
|
+
});
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
const delay = Math.min(timing.backoffMs * 2 ** (conn.attempts - 1), timing.maxBackoffMs);
|
|
862
|
+
setStatus(conn, {
|
|
863
|
+
state: "reconnecting",
|
|
864
|
+
reason
|
|
865
|
+
});
|
|
866
|
+
conn.retry = setTimeout(() => {
|
|
867
|
+
conn.retry = void 0;
|
|
868
|
+
attempt(conn, gen);
|
|
869
|
+
}, delay);
|
|
870
|
+
conn.retry.unref?.();
|
|
871
|
+
};
|
|
872
|
+
/** Watches one live connection for an end it did not ask for. */
|
|
873
|
+
const watch = (conn, gen, client, process_, secrets) => {
|
|
874
|
+
client.onclose = () => {
|
|
875
|
+
if (conn.live?.client !== client || conn.gen !== gen || closed) return;
|
|
876
|
+
clearTimers(conn);
|
|
877
|
+
drop(conn);
|
|
878
|
+
stderrReason(process_, process_ ? "server process exited" : "connection closed").then((reason) => {
|
|
879
|
+
if (closed || conn.gen !== gen) return;
|
|
880
|
+
scheduleRetry(conn, gen, redactReason(reason, secrets()));
|
|
881
|
+
});
|
|
882
|
+
};
|
|
883
|
+
const refresh = (kind) => () => {
|
|
884
|
+
conn.queue = conn.queue.then(async () => {
|
|
885
|
+
const live = conn.live;
|
|
886
|
+
if (!live || live.client !== client || conn.gen !== gen) return;
|
|
887
|
+
try {
|
|
888
|
+
const next = await list(client, live.capabilities, { timeout: timing.handshakeMs }, kind, conn.snapshot);
|
|
889
|
+
if (conn.live?.client !== client || conn.gen !== gen) return;
|
|
890
|
+
publish(conn, next);
|
|
891
|
+
changed(conn.id);
|
|
892
|
+
} catch (error) {
|
|
893
|
+
if (closed || conn.gen !== gen) return;
|
|
894
|
+
deps.log.emit({
|
|
895
|
+
level: "warn",
|
|
896
|
+
event: "plugin.event",
|
|
897
|
+
fields: { localCode: "REFRESHING" }
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
});
|
|
901
|
+
};
|
|
902
|
+
client.setNotificationHandler(ToolListChangedNotificationSchema, refresh("tools"));
|
|
903
|
+
client.setNotificationHandler(ResourceListChangedNotificationSchema, refresh("resources"));
|
|
904
|
+
client.setNotificationHandler(PromptListChangedNotificationSchema, refresh("prompts"));
|
|
905
|
+
};
|
|
906
|
+
/** One connection attempt within generation `gen`, tracked for shutdown. */
|
|
907
|
+
const attempt = (conn, gen) => {
|
|
908
|
+
const work = track(attemptOnce(conn, gen));
|
|
909
|
+
conn.pending.add(work);
|
|
910
|
+
work.finally(() => conn.pending.delete(work)).catch(() => {});
|
|
911
|
+
return work;
|
|
912
|
+
};
|
|
913
|
+
const attemptOnce = async (conn, gen) => {
|
|
914
|
+
if (closed || conn.gen !== gen) return;
|
|
915
|
+
const record = deps.store.server(conn.id);
|
|
916
|
+
if (!record) return;
|
|
917
|
+
await acquire();
|
|
918
|
+
let prepared;
|
|
919
|
+
try {
|
|
920
|
+
try {
|
|
921
|
+
await conn.lastStop;
|
|
922
|
+
} catch {
|
|
923
|
+
if (conn.gen !== gen) return;
|
|
924
|
+
withdraw(conn);
|
|
925
|
+
setStatus(conn, {
|
|
926
|
+
state: "failed",
|
|
927
|
+
reason: "the previous server process could not be stopped"
|
|
928
|
+
});
|
|
929
|
+
return;
|
|
930
|
+
}
|
|
931
|
+
if (conn.gen !== gen || closed) return;
|
|
932
|
+
prepared = await prepare(record, conn, gen);
|
|
933
|
+
starting.add(prepared.transport);
|
|
934
|
+
if (conn.gen !== gen || closed) throw new Superseded();
|
|
935
|
+
const { client, capabilities, snapshot } = await handshake(prepared.transport);
|
|
936
|
+
if (conn.gen !== gen || closed) {
|
|
937
|
+
await client.close().catch(() => {});
|
|
938
|
+
throw new Superseded();
|
|
939
|
+
}
|
|
940
|
+
const secretsOf = prepared.secrets;
|
|
941
|
+
conn.live = {
|
|
942
|
+
client,
|
|
943
|
+
transport: prepared.transport,
|
|
944
|
+
capabilities,
|
|
945
|
+
get secrets() {
|
|
946
|
+
return secretsOf();
|
|
947
|
+
}
|
|
948
|
+
};
|
|
949
|
+
conn.connected = true;
|
|
950
|
+
watch(conn, gen, client, prepared.process, prepared.secrets);
|
|
951
|
+
publish(conn, snapshot);
|
|
952
|
+
setStatus(conn, { state: "connected" });
|
|
953
|
+
conn.stable = setTimeout(() => {
|
|
954
|
+
conn.stable = void 0;
|
|
955
|
+
if (conn.gen === gen) conn.attempts = 0;
|
|
956
|
+
}, timing.stableMs);
|
|
957
|
+
conn.stable.unref?.();
|
|
958
|
+
} catch (error) {
|
|
959
|
+
if (prepared && conn.live?.transport !== prepared.transport) stopTransport(prepared.transport, conn);
|
|
960
|
+
if (error instanceof Superseded || conn.gen !== gen || closed) return;
|
|
961
|
+
const secrets = prepared?.secrets() ?? [];
|
|
962
|
+
if (isNeedsAuth(error)) {
|
|
963
|
+
withdraw(conn);
|
|
964
|
+
setStatus(conn, {
|
|
965
|
+
state: "needs-auth",
|
|
966
|
+
reason: redactReason(messageOf$1(error), secrets)
|
|
967
|
+
});
|
|
968
|
+
return;
|
|
969
|
+
}
|
|
970
|
+
if (error?.name === "CredentialUnavailableError") {
|
|
971
|
+
withdraw(conn);
|
|
972
|
+
setStatus(conn, {
|
|
973
|
+
state: "failed",
|
|
974
|
+
reason: CREDENTIAL_UNAVAILABLE
|
|
975
|
+
});
|
|
976
|
+
return;
|
|
977
|
+
}
|
|
978
|
+
const reason = redactReason(await stderrReason(prepared?.process, messageOf$1(error)), secrets);
|
|
979
|
+
if (conn.gen !== gen || closed) return;
|
|
980
|
+
if (conn.connected && !(error instanceof MissingCredentialError)) {
|
|
981
|
+
scheduleRetry(conn, gen, reason);
|
|
982
|
+
return;
|
|
983
|
+
}
|
|
984
|
+
withdraw(conn);
|
|
985
|
+
setStatus(conn, {
|
|
986
|
+
state: "failed",
|
|
987
|
+
reason
|
|
988
|
+
});
|
|
989
|
+
} finally {
|
|
990
|
+
if (prepared) starting.delete(prepared.transport);
|
|
991
|
+
release();
|
|
992
|
+
}
|
|
993
|
+
};
|
|
994
|
+
/** Brings one server's connection in line with its stored record.
|
|
995
|
+
* Returns the initial attempt when an enabled server can connect. */
|
|
996
|
+
const reconcile = (id, options = {}) => {
|
|
997
|
+
if (closed) return;
|
|
998
|
+
const conn = connection(id);
|
|
999
|
+
cleanupOwners.set(id, conn);
|
|
1000
|
+
conn.gen += 1;
|
|
1001
|
+
conn.attempts = 0;
|
|
1002
|
+
conn.connected = false;
|
|
1003
|
+
clearTimers(conn);
|
|
1004
|
+
drop(conn);
|
|
1005
|
+
const record = deps.store.server(id);
|
|
1006
|
+
if (!record) {
|
|
1007
|
+
withdraw(conn);
|
|
1008
|
+
connections.delete(id);
|
|
1009
|
+
changed(conn.id);
|
|
1010
|
+
return;
|
|
1011
|
+
}
|
|
1012
|
+
if (!record.enabled) {
|
|
1013
|
+
withdraw(conn);
|
|
1014
|
+
setStatus(conn, { state: "disabled" });
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
if (record.transport === "stdio" && record.acknowledgedAt === null) {
|
|
1018
|
+
withdraw(conn);
|
|
1019
|
+
setStatus(conn, {
|
|
1020
|
+
state: "failed",
|
|
1021
|
+
reason: UNACKNOWLEDGED
|
|
1022
|
+
});
|
|
1023
|
+
return;
|
|
1024
|
+
}
|
|
1025
|
+
if (record.transport === "http" && record.config.auth === "oauth") {
|
|
1026
|
+
let authorized;
|
|
1027
|
+
try {
|
|
1028
|
+
authorized = deps.oauth.hasTokens(id);
|
|
1029
|
+
} catch {
|
|
1030
|
+
withdraw(conn);
|
|
1031
|
+
setStatus(conn, {
|
|
1032
|
+
state: "failed",
|
|
1033
|
+
reason: CREDENTIAL_UNAVAILABLE
|
|
1034
|
+
});
|
|
1035
|
+
return;
|
|
1036
|
+
}
|
|
1037
|
+
if (!authorized) {
|
|
1038
|
+
withdraw(conn);
|
|
1039
|
+
setStatus(conn, { state: "needs-auth" });
|
|
1040
|
+
return;
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
if (!options.keepSnapshot) withdraw(conn);
|
|
1044
|
+
setStatus(conn, { state: "connecting" });
|
|
1045
|
+
return attempt(conn, conn.gen);
|
|
1046
|
+
};
|
|
1047
|
+
/** The work of `test`, untracked. */
|
|
1048
|
+
const testOnce = async (id) => {
|
|
1049
|
+
if (closed) return {
|
|
1050
|
+
ok: false,
|
|
1051
|
+
reason: "the plugin is stopping"
|
|
1052
|
+
};
|
|
1053
|
+
const record = deps.store.server(id);
|
|
1054
|
+
if (!record) return {
|
|
1055
|
+
ok: false,
|
|
1056
|
+
reason: "no such server"
|
|
1057
|
+
};
|
|
1058
|
+
if (record.transport === "stdio" && record.acknowledgedAt === null) return {
|
|
1059
|
+
ok: false,
|
|
1060
|
+
reason: UNACKNOWLEDGED
|
|
1061
|
+
};
|
|
1062
|
+
const conn = connection(id);
|
|
1063
|
+
const gen = conn.gen;
|
|
1064
|
+
const count = (snapshot) => ({
|
|
1065
|
+
ok: true,
|
|
1066
|
+
tools: snapshot.tools.length,
|
|
1067
|
+
resources: snapshot.resources.length,
|
|
1068
|
+
prompts: snapshot.prompts.length
|
|
1069
|
+
});
|
|
1070
|
+
if (conn?.live && conn.status.state === "connected") {
|
|
1071
|
+
const live = conn.live;
|
|
1072
|
+
try {
|
|
1073
|
+
const snapshot = await list(live.client, live.capabilities, { timeout: timing.handshakeMs });
|
|
1074
|
+
if (closed || conn.gen !== gen || conn.live !== live) return {
|
|
1075
|
+
ok: false,
|
|
1076
|
+
reason: "the connection changed during testing"
|
|
1077
|
+
};
|
|
1078
|
+
publish(conn, snapshot);
|
|
1079
|
+
changed(conn.id);
|
|
1080
|
+
return count(snapshot);
|
|
1081
|
+
} catch (error) {
|
|
1082
|
+
const reason = redactReason(messageOf$1(error), live.secrets);
|
|
1083
|
+
if (!closed && conn.gen === gen && conn.live === live) {
|
|
1084
|
+
conn.gen += 1;
|
|
1085
|
+
clearTimers(conn);
|
|
1086
|
+
drop(conn);
|
|
1087
|
+
withdraw(conn);
|
|
1088
|
+
setStatus(conn, {
|
|
1089
|
+
state: isNeedsAuth(error) ? "needs-auth" : "failed",
|
|
1090
|
+
reason
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
return {
|
|
1094
|
+
ok: false,
|
|
1095
|
+
reason
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
if (record.enabled) {
|
|
1100
|
+
const attempt = reconcile(id, { keepSnapshot: true });
|
|
1101
|
+
const testingGen = conn.gen;
|
|
1102
|
+
await attempt;
|
|
1103
|
+
if (closed) return {
|
|
1104
|
+
ok: false,
|
|
1105
|
+
reason: "the plugin is stopping"
|
|
1106
|
+
};
|
|
1107
|
+
if (conn.gen !== testingGen) return {
|
|
1108
|
+
ok: false,
|
|
1109
|
+
reason: "the connection changed during testing"
|
|
1110
|
+
};
|
|
1111
|
+
if (conn.status.state === "connected" && conn.live && conn.snapshot) return count(conn.snapshot);
|
|
1112
|
+
return {
|
|
1113
|
+
ok: false,
|
|
1114
|
+
reason: conn.status.reason ?? "the server is not connected"
|
|
1115
|
+
};
|
|
1116
|
+
}
|
|
1117
|
+
let prepared;
|
|
1118
|
+
try {
|
|
1119
|
+
if (closed) return {
|
|
1120
|
+
ok: false,
|
|
1121
|
+
reason: "the plugin is stopping"
|
|
1122
|
+
};
|
|
1123
|
+
await conn.lastStop;
|
|
1124
|
+
prepared = await prepare(record, conn, gen);
|
|
1125
|
+
starting.add(prepared.transport);
|
|
1126
|
+
if (closed) throw new Error("the plugin is stopping");
|
|
1127
|
+
const { client, snapshot } = await handshake(prepared.transport);
|
|
1128
|
+
await client.close().catch(() => {});
|
|
1129
|
+
return count(snapshot);
|
|
1130
|
+
} catch (error) {
|
|
1131
|
+
if (error?.name === "CredentialUnavailableError") return {
|
|
1132
|
+
ok: false,
|
|
1133
|
+
reason: CREDENTIAL_UNAVAILABLE
|
|
1134
|
+
};
|
|
1135
|
+
const reason = await stderrReason(prepared?.process, messageOf$1(error));
|
|
1136
|
+
if (closed) return {
|
|
1137
|
+
ok: false,
|
|
1138
|
+
reason: "the plugin is stopping"
|
|
1139
|
+
};
|
|
1140
|
+
return {
|
|
1141
|
+
ok: false,
|
|
1142
|
+
reason: redact(reason, prepared?.secrets() ?? [])
|
|
1143
|
+
};
|
|
1144
|
+
} finally {
|
|
1145
|
+
if (prepared) starting.delete(prepared.transport);
|
|
1146
|
+
if (prepared) await stopTransport(prepared.transport, conn).catch(() => {});
|
|
1147
|
+
}
|
|
1148
|
+
};
|
|
1149
|
+
return {
|
|
1150
|
+
/** Starts every stored server in the background; returns at once. */
|
|
1151
|
+
boot() {
|
|
1152
|
+
for (const record of deps.store.servers()) reconcile(record.id);
|
|
1153
|
+
},
|
|
1154
|
+
reconcile,
|
|
1155
|
+
/** Defers only these servers' notifications, leaving other lifecycle events independent. */
|
|
1156
|
+
async collection(ids, work, publish = true) {
|
|
1157
|
+
const context = {
|
|
1158
|
+
ids: new Set(ids),
|
|
1159
|
+
dirty: /* @__PURE__ */ new Set(),
|
|
1160
|
+
publish
|
|
1161
|
+
};
|
|
1162
|
+
collections.add(context);
|
|
1163
|
+
try {
|
|
1164
|
+
return await work();
|
|
1165
|
+
} finally {
|
|
1166
|
+
collections.delete(context);
|
|
1167
|
+
if (publish && context.dirty.size) deps.onChanged(context.dirty.values().next().value);
|
|
1168
|
+
}
|
|
1169
|
+
},
|
|
1170
|
+
/** Joins actual superseded resources; failed handles stay owned for cleanup retry. */
|
|
1171
|
+
async cleanup(id) {
|
|
1172
|
+
const conn = cleanupOwners.get(id) ?? connections.get(id);
|
|
1173
|
+
if (!conn) return {
|
|
1174
|
+
id,
|
|
1175
|
+
state: "completed"
|
|
1176
|
+
};
|
|
1177
|
+
const failures = [];
|
|
1178
|
+
if (conn.pending.size && (!deps.store.server(id) || !deps.store.server(id).enabled) && conn.lastReceipt) try {
|
|
1179
|
+
await conn.lastReceipt.stop();
|
|
1180
|
+
} catch (error) {
|
|
1181
|
+
failures.push(error);
|
|
1182
|
+
}
|
|
1183
|
+
await Promise.allSettled([...conn.pending]);
|
|
1184
|
+
for (const [transport, owner] of [...pendingStops]) if (owner === conn) try {
|
|
1185
|
+
await stopTransport(transport, conn);
|
|
1186
|
+
} catch (error) {
|
|
1187
|
+
failures.push(error);
|
|
1188
|
+
}
|
|
1189
|
+
if (conn.failedStart) try {
|
|
1190
|
+
await conn.failedStart.stop();
|
|
1191
|
+
} catch (error) {
|
|
1192
|
+
failures.push(error);
|
|
1193
|
+
}
|
|
1194
|
+
if (failures.length) return {
|
|
1195
|
+
id,
|
|
1196
|
+
state: "failed",
|
|
1197
|
+
reason: "cleanup-failed"
|
|
1198
|
+
};
|
|
1199
|
+
cleanupOwners.delete(id);
|
|
1200
|
+
return {
|
|
1201
|
+
id,
|
|
1202
|
+
state: "completed"
|
|
1203
|
+
};
|
|
1204
|
+
},
|
|
1205
|
+
status(id) {
|
|
1206
|
+
return connections.get(id)?.status ?? { state: "disabled" };
|
|
1207
|
+
},
|
|
1208
|
+
snapshot(id) {
|
|
1209
|
+
return connections.get(id)?.snapshot;
|
|
1210
|
+
},
|
|
1211
|
+
/** The live connection, or `undefined` while not connected. */
|
|
1212
|
+
live(id) {
|
|
1213
|
+
const conn = connections.get(id);
|
|
1214
|
+
return conn?.status.state === "connected" ? conn.live : void 0;
|
|
1215
|
+
},
|
|
1216
|
+
/** A call learned the server wants authorization again. */
|
|
1217
|
+
needsAuth(id, reason) {
|
|
1218
|
+
const conn = connections.get(id);
|
|
1219
|
+
if (!conn || closed) return;
|
|
1220
|
+
conn.gen += 1;
|
|
1221
|
+
clearTimers(conn);
|
|
1222
|
+
drop(conn);
|
|
1223
|
+
withdraw(conn);
|
|
1224
|
+
setStatus(conn, {
|
|
1225
|
+
state: "needs-auth",
|
|
1226
|
+
...reason ? { reason } : {}
|
|
1227
|
+
});
|
|
1228
|
+
},
|
|
1229
|
+
/**
|
|
1230
|
+
* Lists capabilities: through the live connection when there is one,
|
|
1231
|
+
* otherwise restores the enabled server's resident connection and status.
|
|
1232
|
+
* Disabled servers use a temporary connection closed before this returns.
|
|
1233
|
+
*/
|
|
1234
|
+
test(id) {
|
|
1235
|
+
return track(testOnce(id));
|
|
1236
|
+
},
|
|
1237
|
+
/** Closes every connection and stops reconnecting; settles once every
|
|
1238
|
+
* process group this plugin started has been stopped, including those of
|
|
1239
|
+
* handshakes and test connections still under way. */
|
|
1240
|
+
shutdown() {
|
|
1241
|
+
closed = true;
|
|
1242
|
+
shuttingDown ??= Promise.resolve().then(async () => {
|
|
1243
|
+
const stops = [];
|
|
1244
|
+
const stopped = /* @__PURE__ */ new Set();
|
|
1245
|
+
for (const conn of connections.values()) {
|
|
1246
|
+
conn.gen += 1;
|
|
1247
|
+
clearTimers(conn);
|
|
1248
|
+
drop(conn);
|
|
1249
|
+
}
|
|
1250
|
+
for (const [transport, conn] of pendingStops) stops.push(stopTransport(transport, conn));
|
|
1251
|
+
for (const transport of starting) stops.push(transport.close());
|
|
1252
|
+
for (const receipt of receipts) {
|
|
1253
|
+
stopped.add(receipt);
|
|
1254
|
+
stops.push(receipt.stop());
|
|
1255
|
+
}
|
|
1256
|
+
const initialStops = Promise.allSettled(stops);
|
|
1257
|
+
await Promise.allSettled([...running]);
|
|
1258
|
+
const lateStops = [];
|
|
1259
|
+
for (const receipt of receipts) if (!stopped.has(receipt)) lateStops.push(receipt.stop());
|
|
1260
|
+
const results = (await Promise.all([initialStops, Promise.allSettled(lateStops)])).flat();
|
|
1261
|
+
results.push(...await Promise.allSettled([...connections.values()].map((conn) => conn.lastStop)));
|
|
1262
|
+
const failures = results.filter((result) => result.status === "rejected");
|
|
1263
|
+
if (failures.length) throw new AggregateError(failures.map((result) => result.reason), "cleanup-failed");
|
|
1264
|
+
}).catch((error) => {
|
|
1265
|
+
shuttingDown = void 0;
|
|
1266
|
+
throw error;
|
|
1267
|
+
});
|
|
1268
|
+
return shuttingDown;
|
|
1269
|
+
},
|
|
1270
|
+
/** Whether the stored stdio configuration carries a confirmation that
|
|
1271
|
+
* still matches it. */
|
|
1272
|
+
acknowledged(record, previous) {
|
|
1273
|
+
if (record.transport !== "stdio" || !previous || previous.transport !== "stdio") return false;
|
|
1274
|
+
return previous.acknowledgedAt !== null && acknowledgementKey(previous.config, deps.commands.platform) === acknowledgementKey(record.config, deps.commands.platform);
|
|
1275
|
+
}
|
|
1276
|
+
};
|
|
1277
|
+
}
|
|
1278
|
+
//#endregion
|
|
1279
|
+
//#region src/batch.ts
|
|
1280
|
+
/** Owner-local bounded collection schemas and safe member settlement. */
|
|
1281
|
+
/** Stable safe error facts; decrypted server credentials never enter this shape. */
|
|
1282
|
+
const MemberError = z.strictObject({
|
|
1283
|
+
code: z.string().max(64),
|
|
1284
|
+
message: z.string().max(512)
|
|
1285
|
+
});
|
|
1286
|
+
/** Declared encoded query capacities, independent of collection/page sizes. */
|
|
1287
|
+
const queryBudgets = {
|
|
1288
|
+
maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
|
|
1289
|
+
maxTotalBytes: z.number().int().min(1).max(8388608).default(8388608)
|
|
1290
|
+
};
|
|
1291
|
+
/** Validates complete input bytes and all declared capacities before any owner IO. */
|
|
1292
|
+
function batchInput(shape, key) {
|
|
1293
|
+
return z.strictObject(shape).superRefine((value, context) => {
|
|
1294
|
+
const input = value;
|
|
1295
|
+
if (Buffer.byteLength(JSON.stringify(value)) > 8388608) context.addIssue({
|
|
1296
|
+
code: "custom",
|
|
1297
|
+
message: "batch input exceeds 8 MiB"
|
|
1298
|
+
});
|
|
1299
|
+
const items = input[key];
|
|
1300
|
+
if (Array.isArray(items) && typeof input.maxItemBytes === "number" && typeof input.maxTotalBytes === "number" && items.length * input.maxItemBytes + 8192 > input.maxTotalBytes) context.addIssue({
|
|
1301
|
+
code: "custom",
|
|
1302
|
+
message: "declared member budgets exceed total budget"
|
|
1303
|
+
});
|
|
1304
|
+
});
|
|
1305
|
+
}
|
|
1306
|
+
/** Publishes an ordered result only with the explicit nonsensitive target projection. */
|
|
1307
|
+
function batchResult(value, target) {
|
|
1308
|
+
const identity = {
|
|
1309
|
+
index: z.number().int().nonnegative(),
|
|
1310
|
+
target
|
|
1311
|
+
};
|
|
1312
|
+
return z.strictObject({ results: z.array(z.discriminatedUnion("ok", [z.strictObject({
|
|
1313
|
+
...identity,
|
|
1314
|
+
ok: z.literal(true),
|
|
1315
|
+
value
|
|
1316
|
+
}), z.strictObject({
|
|
1317
|
+
...identity,
|
|
1318
|
+
ok: z.literal(false),
|
|
1319
|
+
error: MemberError
|
|
1320
|
+
})])) });
|
|
1321
|
+
}
|
|
1322
|
+
/** Keeps committed business facts immutable while reflecting uncertain or retained cleanup. */
|
|
1323
|
+
function operationResult(value) {
|
|
1324
|
+
return z.discriminatedUnion("operationState", [
|
|
1325
|
+
z.strictObject({
|
|
1326
|
+
operationState: z.literal("committed"),
|
|
1327
|
+
operationId: z.uuid(),
|
|
1328
|
+
value
|
|
1329
|
+
}),
|
|
1330
|
+
z.strictObject({
|
|
1331
|
+
operationState: z.literal("admitted"),
|
|
1332
|
+
operationId: z.uuid(),
|
|
1333
|
+
uncertain: z.literal(true)
|
|
1334
|
+
}),
|
|
1335
|
+
z.strictObject({
|
|
1336
|
+
operationState: z.literal("cleanup-pending"),
|
|
1337
|
+
operationId: z.uuid(),
|
|
1338
|
+
value,
|
|
1339
|
+
cleanup: z.array(MemberError)
|
|
1340
|
+
})
|
|
1341
|
+
]);
|
|
1342
|
+
}
|
|
1343
|
+
/** Settles every target in order and enforces complete encoded member and aggregate sizes. */
|
|
1344
|
+
async function settle(targets, work, limits, failure) {
|
|
1345
|
+
const results = [];
|
|
1346
|
+
let bytes = 8192;
|
|
1347
|
+
for (const [index, target] of targets.entries()) try {
|
|
1348
|
+
const item = {
|
|
1349
|
+
index,
|
|
1350
|
+
target,
|
|
1351
|
+
ok: true,
|
|
1352
|
+
value: await work(target, index)
|
|
1353
|
+
};
|
|
1354
|
+
const size = Buffer.byteLength(JSON.stringify(item));
|
|
1355
|
+
if (size > (limits?.maxItemBytes ?? 8388608) || bytes + size > (limits?.maxTotalBytes ?? 8388608)) throw Object.assign(/* @__PURE__ */ new Error("encoded member exceeds declared budget"), { code: "read-limit" });
|
|
1356
|
+
results.push(item);
|
|
1357
|
+
bytes += size;
|
|
1358
|
+
} catch (error) {
|
|
1359
|
+
const item = {
|
|
1360
|
+
index,
|
|
1361
|
+
target,
|
|
1362
|
+
ok: false,
|
|
1363
|
+
error: {
|
|
1364
|
+
code: error instanceof Error && "code" in error && typeof error.code === "string" ? error.code.slice(0, 64) : "operation-failed",
|
|
1365
|
+
message: (failure?.(error, target) ?? (error instanceof Error ? error.message : "Operation failed")).slice(0, 512)
|
|
1366
|
+
}
|
|
1367
|
+
};
|
|
1368
|
+
results.push(item);
|
|
1369
|
+
bytes += Buffer.byteLength(JSON.stringify(item));
|
|
1370
|
+
}
|
|
1371
|
+
return { results };
|
|
1372
|
+
}
|
|
1373
|
+
/** Complete resource declarations reserve raw bytes and worst encoded protocol/output capacity. */
|
|
1374
|
+
function resourceInput(extra, member) {
|
|
1375
|
+
return batchInput({
|
|
1376
|
+
...extra,
|
|
1377
|
+
items: z.array(member).min(1).max(32),
|
|
1378
|
+
maxTotalBytes: z.number().int().min(1).max(4194304).default(4194304)
|
|
1379
|
+
}, "items").superRefine((input, context) => {
|
|
1380
|
+
const declared = input;
|
|
1381
|
+
const items = declared.items;
|
|
1382
|
+
const raw = items.reduce((sum, item) => sum + item.maxBytes, 0);
|
|
1383
|
+
const encoded = items.reduce((sum, item) => sum + Math.max(6 * item.maxBytes, 4 * Math.ceil(item.maxBytes / 3)) + Math.max(65536, Buffer.byteLength(JSON.stringify(item)) + 1024), 8192);
|
|
1384
|
+
if (raw > Number(declared.maxTotalBytes)) context.addIssue({
|
|
1385
|
+
code: "custom",
|
|
1386
|
+
message: "declared raw member budgets exceed total budget"
|
|
1387
|
+
});
|
|
1388
|
+
if (encoded > 8388608) context.addIssue({
|
|
1389
|
+
code: "custom",
|
|
1390
|
+
message: "declared encoded resource budgets exceed 8 MiB"
|
|
1391
|
+
});
|
|
1392
|
+
});
|
|
1393
|
+
}
|
|
1394
|
+
//#endregion
|
|
1395
|
+
//#region src/management.ts
|
|
1396
|
+
/**
|
|
1397
|
+
* Validates and saves one server, optionally selecting a new one for an agent.
|
|
1398
|
+
* Rejects edits whose captured server changed during asynchronous command resolution.
|
|
1399
|
+
*/
|
|
1400
|
+
async function saveServer(deps, input, selectFor, ctx) {
|
|
1401
|
+
const { store, connections, tools, oauth } = deps;
|
|
1402
|
+
checkSlug(input.slug);
|
|
1403
|
+
const previous = input.id === void 0 ? void 0 : store.server(input.id);
|
|
1404
|
+
if (input.id && !previous) throw new Error("no such MCP server");
|
|
1405
|
+
if (previous && previous.slug !== input.slug) throw new Error("a slug cannot be changed");
|
|
1406
|
+
const taken = store.serverBySlug(input.slug);
|
|
1407
|
+
if (taken && taken.id !== previous?.id) throw new Error(`slug "${input.slug}" is already used`);
|
|
1408
|
+
const id = previous?.id ?? randomUUID();
|
|
1409
|
+
const base = {
|
|
1410
|
+
id,
|
|
1411
|
+
slug: input.slug,
|
|
1412
|
+
name: input.name,
|
|
1413
|
+
enabled: previous?.enabled ?? true,
|
|
1414
|
+
createdAt: previous?.createdAt ?? Date.now()
|
|
1415
|
+
};
|
|
1416
|
+
let record;
|
|
1417
|
+
if (input.transport === "stdio") {
|
|
1418
|
+
const draft = {
|
|
1419
|
+
...base,
|
|
1420
|
+
transport: "stdio",
|
|
1421
|
+
config: await resolveStdioConfig(input.config, deps.commands),
|
|
1422
|
+
acknowledgedAt: null
|
|
1423
|
+
};
|
|
1424
|
+
const kept = connections.acknowledged(draft, previous);
|
|
1425
|
+
if (!kept && input.acknowledge !== true) throw new Error("stdio servers must be acknowledged before saving");
|
|
1426
|
+
record = {
|
|
1427
|
+
...draft,
|
|
1428
|
+
acknowledgedAt: kept && previous?.transport === "stdio" ? previous.acknowledgedAt : Date.now()
|
|
1429
|
+
};
|
|
1430
|
+
} else record = {
|
|
1431
|
+
...base,
|
|
1432
|
+
transport: "http",
|
|
1433
|
+
config: input.config,
|
|
1434
|
+
acknowledgedAt: null
|
|
1435
|
+
};
|
|
1436
|
+
if (previous && !isDeepStrictEqual(previous, store.server(previous.id))) throw new Error("MCP server changed while saving; reload before retrying");
|
|
1437
|
+
if (selectFor && previous) throw new Error("initial selection requires a new server");
|
|
1438
|
+
if (selectFor) deps.agentConfig.save([selectFor.agentId], () => store.createSelectedServer(record, selectFor.agentId, selectFor.selected), ctx);
|
|
1439
|
+
else store.saveServer(record);
|
|
1440
|
+
if (previous !== void 0 && record.transport === "http" && (previous.transport !== "http" || previous.config.url !== record.config.url || previous.config.auth !== record.config.auth)) oauth.signOut(id);
|
|
1441
|
+
if (!previous || previous.transport !== record.transport || JSON.stringify(previous.config) !== JSON.stringify(record.config) || previous.acknowledgedAt !== record.acknowledgedAt) connections.reconcile(id);
|
|
1442
|
+
else if (previous.name !== record.name) tools.apply(id, connections.snapshot(id));
|
|
1443
|
+
deps.announce();
|
|
1444
|
+
if (selectFor?.selected) deps.selectionChanged(selectFor.agentId);
|
|
1445
|
+
return record;
|
|
1446
|
+
}
|
|
1447
|
+
//#endregion
|
|
1448
|
+
//#region src/output-schema.ts
|
|
1449
|
+
/** Validates complete owner business results and bounded recoverable delivery failures. */
|
|
1450
|
+
/** Adds the standard failure envelope and bounded text refusals to an owner's result schema. */
|
|
1451
|
+
function toolOutputSchema(body, input, name) {
|
|
1452
|
+
return z.union([
|
|
1453
|
+
body,
|
|
1454
|
+
z.strictObject({
|
|
1455
|
+
ok: z.literal(false),
|
|
1456
|
+
error: z.strictObject({
|
|
1457
|
+
code: z.string().min(1).max(128),
|
|
1458
|
+
message: z.string().refine((value) => [...value].length <= 256).meta({ maxLength: 256 }),
|
|
1459
|
+
retryable: z.boolean(),
|
|
1460
|
+
field: z.string().max(256).optional(),
|
|
1461
|
+
maximum: z.number().finite().optional()
|
|
1462
|
+
}),
|
|
1463
|
+
next: z.strictObject({
|
|
1464
|
+
tool: z.literal(name),
|
|
1465
|
+
arguments: input
|
|
1466
|
+
}).nullable(),
|
|
1467
|
+
execution: z.strictObject({ state: z.enum([
|
|
1468
|
+
"not-started",
|
|
1469
|
+
"committed",
|
|
1470
|
+
"unknown"
|
|
1471
|
+
]) }).optional()
|
|
1472
|
+
}),
|
|
1473
|
+
z.string().max(1024)
|
|
1474
|
+
]);
|
|
1475
|
+
}
|
|
1476
|
+
//#endregion
|
|
1477
|
+
//#region src/cursor-cache.ts
|
|
1478
|
+
const bytesOf = (value) => 2048 + 2 * (value.content?.length ?? 0);
|
|
1479
|
+
/** Owns metadata snapshots; each query and all successor positions share one opaque host lease. */
|
|
1480
|
+
var QueryCursorCache = class extends Map {
|
|
1481
|
+
pending = /* @__PURE__ */ new Map();
|
|
1482
|
+
roots = /* @__PURE__ */ new Map();
|
|
1483
|
+
resources;
|
|
1484
|
+
facts;
|
|
1485
|
+
timer;
|
|
1486
|
+
/** Measures only retained metadata; source IO uses a separate bounded reservation. */
|
|
1487
|
+
constructor(facts, resources) {
|
|
1488
|
+
super();
|
|
1489
|
+
this.facts = facts;
|
|
1490
|
+
this.resources = resources;
|
|
1491
|
+
}
|
|
1492
|
+
retained(root) {
|
|
1493
|
+
let bytes = 0;
|
|
1494
|
+
for (const state of this.values()) if (this.facts(state).initial === root.initial) bytes += bytesOf(this.facts(state));
|
|
1495
|
+
return bytes;
|
|
1496
|
+
}
|
|
1497
|
+
total(root) {
|
|
1498
|
+
return 2048 + 2 * JSON.stringify(root.initial).length + this.retained(root) + root.ioBytes + root.pendingBytes;
|
|
1499
|
+
}
|
|
1500
|
+
settle(root) {
|
|
1501
|
+
if (root.released) return;
|
|
1502
|
+
if (root.active === 0 && this.retained(root) === 0) {
|
|
1503
|
+
root.released = true;
|
|
1504
|
+
root.closing = true;
|
|
1505
|
+
this.roots.delete(root.initial);
|
|
1506
|
+
root.lease.close("completed");
|
|
1507
|
+
if (!this.roots.size && this.timer) {
|
|
1508
|
+
clearInterval(this.timer);
|
|
1509
|
+
this.timer = void 0;
|
|
1510
|
+
}
|
|
1511
|
+
return;
|
|
1512
|
+
}
|
|
1513
|
+
const released = root.heldBytes - this.total(root);
|
|
1514
|
+
if (released > 0) {
|
|
1515
|
+
root.lease.reduce({
|
|
1516
|
+
bytes: released,
|
|
1517
|
+
scratchBytes: 0
|
|
1518
|
+
});
|
|
1519
|
+
root.heldBytes -= released;
|
|
1520
|
+
}
|
|
1521
|
+
if (root.active === 0 && this.retained(root) > 0) root.lease.retain({
|
|
1522
|
+
reason: "public-cursor",
|
|
1523
|
+
idleMs: 6e5,
|
|
1524
|
+
maxAgeMs: 36e5
|
|
1525
|
+
});
|
|
1526
|
+
}
|
|
1527
|
+
invalidate(root) {
|
|
1528
|
+
if (root.released) return;
|
|
1529
|
+
root.closing = true;
|
|
1530
|
+
for (const [key, state] of this) if (this.facts(state).initial === root.initial) super.delete(key);
|
|
1531
|
+
root.pendingBytes = 0;
|
|
1532
|
+
root.lease.close("abandoned");
|
|
1533
|
+
}
|
|
1534
|
+
async enter(call, initial, sourceBytes) {
|
|
1535
|
+
const now = performance.now();
|
|
1536
|
+
for (const root of this.roots.values()) if (now - root.used > 6e5 || now - root.created > 36e5) this.invalidate(root);
|
|
1537
|
+
let root = this.roots.get(initial);
|
|
1538
|
+
if (root?.closing || root?.lease.signal.aborted) throw new Error("cursor_invalid");
|
|
1539
|
+
if (!root) {
|
|
1540
|
+
const resources = this.resources;
|
|
1541
|
+
if (!resources) throw new Error("query_resources_unavailable");
|
|
1542
|
+
const initialBytes = sourceBytes + 2048 + 2 * JSON.stringify(initial).length;
|
|
1543
|
+
root = {
|
|
1544
|
+
initial,
|
|
1545
|
+
lease: await resources.reserve(call, {
|
|
1546
|
+
bytes: sourceBytes + 2048 + 2 * JSON.stringify(initial).length,
|
|
1547
|
+
scratchBytes: 0,
|
|
1548
|
+
cleanup: async () => {
|
|
1549
|
+
const current = this.roots.get(initial);
|
|
1550
|
+
for (const [id, value] of this) if (this.facts(value).initial === initial) super.delete(id);
|
|
1551
|
+
if (current) {
|
|
1552
|
+
current.released = true;
|
|
1553
|
+
current.closing = true;
|
|
1554
|
+
this.roots.delete(initial);
|
|
1555
|
+
}
|
|
1556
|
+
return { status: "complete" };
|
|
1557
|
+
}
|
|
1558
|
+
}),
|
|
1559
|
+
created: now,
|
|
1560
|
+
used: now,
|
|
1561
|
+
active: 0,
|
|
1562
|
+
ioBytes: 0,
|
|
1563
|
+
pendingBytes: 0,
|
|
1564
|
+
closing: false,
|
|
1565
|
+
released: false,
|
|
1566
|
+
heldBytes: initialBytes,
|
|
1567
|
+
call
|
|
1568
|
+
};
|
|
1569
|
+
this.roots.set(initial, root);
|
|
1570
|
+
this.timer ??= setInterval(() => {
|
|
1571
|
+
const current = performance.now();
|
|
1572
|
+
for (const candidate of this.roots.values()) if (current - candidate.used > 6e5 || current - candidate.created > 36e5) this.invalidate(candidate);
|
|
1573
|
+
}, 6e4);
|
|
1574
|
+
this.timer.unref();
|
|
1575
|
+
}
|
|
1576
|
+
root.lease.signal.throwIfAborted();
|
|
1577
|
+
root.call = call;
|
|
1578
|
+
const additional = this.total(root) + sourceBytes - root.heldBytes;
|
|
1579
|
+
if (additional > 0) {
|
|
1580
|
+
await root.lease.grow(call, {
|
|
1581
|
+
bytes: additional,
|
|
1582
|
+
scratchBytes: 0
|
|
1583
|
+
});
|
|
1584
|
+
root.heldBytes += additional;
|
|
1585
|
+
}
|
|
1586
|
+
root.active++;
|
|
1587
|
+
root.ioBytes += sourceBytes;
|
|
1588
|
+
root.used = now;
|
|
1589
|
+
let finished = false;
|
|
1590
|
+
return () => {
|
|
1591
|
+
if (finished) return;
|
|
1592
|
+
finished = true;
|
|
1593
|
+
root.active--;
|
|
1594
|
+
root.ioBytes -= sourceBytes;
|
|
1595
|
+
root.pendingBytes = 0;
|
|
1596
|
+
this.settle(root);
|
|
1597
|
+
};
|
|
1598
|
+
}
|
|
1599
|
+
/** Runs source acquisition under the actual authenticated call, releasing only after its cleanup. */
|
|
1600
|
+
async runExclusive(input, call, action, sourceBytes = 4194304) {
|
|
1601
|
+
const cursor = typeof input === "object" && input !== null && "cursor" in input ? input.cursor : void 0;
|
|
1602
|
+
const saved = cursor === void 0 ? void 0 : this.get(cursor);
|
|
1603
|
+
if (cursor !== void 0 && saved === void 0) return action();
|
|
1604
|
+
const initial = saved === void 0 ? input : this.facts(saved).initial;
|
|
1605
|
+
const existing = this.roots.get(initial);
|
|
1606
|
+
if (existing && (existing.call.sessionId !== call.sessionId || JSON.stringify(existing.call.address) !== JSON.stringify(call.address) || existing.call.historyGeneration !== call.historyGeneration)) return action();
|
|
1607
|
+
let finish;
|
|
1608
|
+
try {
|
|
1609
|
+
finish = await this.enter(call, initial, sourceBytes);
|
|
1610
|
+
return await this.roots.get(initial).lease.withUse(call, action);
|
|
1611
|
+
} catch (error) {
|
|
1612
|
+
if (this.resources?.isAdmissionFailure(error)) throw error;
|
|
1613
|
+
if (!(error instanceof Error) || ![
|
|
1614
|
+
"query_limit_exceeded",
|
|
1615
|
+
"query_resources_unavailable",
|
|
1616
|
+
"cursor_invalid"
|
|
1617
|
+
].includes(error.message)) throw error;
|
|
1618
|
+
return {
|
|
1619
|
+
content: JSON.stringify({
|
|
1620
|
+
ok: false,
|
|
1621
|
+
error: {
|
|
1622
|
+
code: error.message,
|
|
1623
|
+
message: "Shared query capacity or authority is unavailable; restart after releasing older queries.",
|
|
1624
|
+
retryable: false
|
|
1625
|
+
},
|
|
1626
|
+
next: null
|
|
1627
|
+
}),
|
|
1628
|
+
isError: true
|
|
1629
|
+
};
|
|
1630
|
+
} finally {
|
|
1631
|
+
finish?.();
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
/** Joins same-cursor preparation before revalidating and replaying its accepted exact page. */
|
|
1635
|
+
async run(input, call, action, sourceBytes = 4194304) {
|
|
1636
|
+
const cursor = typeof input === "object" && input !== null && "cursor" in input ? input.cursor : void 0;
|
|
1637
|
+
if (cursor === void 0) return this.runExclusive(input, call, action, sourceBytes);
|
|
1638
|
+
const previous = this.pending.get(cursor);
|
|
1639
|
+
let unlock;
|
|
1640
|
+
const gate = new Promise((resolve) => {
|
|
1641
|
+
unlock = resolve;
|
|
1642
|
+
});
|
|
1643
|
+
this.pending.set(cursor, gate);
|
|
1644
|
+
try {
|
|
1645
|
+
await previous;
|
|
1646
|
+
call.signal.throwIfAborted();
|
|
1647
|
+
return await this.runExclusive(input, call, action, sourceBytes);
|
|
1648
|
+
} finally {
|
|
1649
|
+
unlock();
|
|
1650
|
+
if (this.pending.get(cursor) === gate) this.pending.delete(cursor);
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
/** Applies the same resource lifecycle to a native model-tool registration. */
|
|
1654
|
+
wrap(tool, sourceBytes = 4194304) {
|
|
1655
|
+
const execute = tool.execute;
|
|
1656
|
+
return {
|
|
1657
|
+
...tool,
|
|
1658
|
+
execute: (input, call) => this.run(input, call, async () => await execute(input, call), sourceBytes)
|
|
1659
|
+
};
|
|
1660
|
+
}
|
|
1661
|
+
/** Accounts an exact candidate before accepting or retaining its snapshot. */
|
|
1662
|
+
async prepare(initial, content) {
|
|
1663
|
+
const root = this.roots.get(initial);
|
|
1664
|
+
if (!root || root.closing) throw new Error("cursor_invalid");
|
|
1665
|
+
root.lease.signal.throwIfAborted();
|
|
1666
|
+
const bytes = 2048 + 2 * content.length;
|
|
1667
|
+
const additional = this.total(root) - root.pendingBytes + bytes - root.heldBytes;
|
|
1668
|
+
if (additional > 0) {
|
|
1669
|
+
await root.lease.grow(root.call, {
|
|
1670
|
+
bytes: additional,
|
|
1671
|
+
scratchBytes: 0
|
|
1672
|
+
});
|
|
1673
|
+
root.heldBytes += additional;
|
|
1674
|
+
}
|
|
1675
|
+
root.pendingBytes = bytes;
|
|
1676
|
+
}
|
|
1677
|
+
/** Awaits metadata admission before installing a new cursor. */
|
|
1678
|
+
async save(key, value) {
|
|
1679
|
+
const root = this.roots.get(this.facts(value).initial);
|
|
1680
|
+
if (!root || root.closing) throw new Error("cursor_invalid");
|
|
1681
|
+
root.lease.signal.throwIfAborted();
|
|
1682
|
+
const old = super.get(key);
|
|
1683
|
+
const required = this.total(root) + bytesOf(this.facts(value)) - (old === void 0 ? 0 : bytesOf(this.facts(old)));
|
|
1684
|
+
if (required > root.heldBytes) {
|
|
1685
|
+
const bytes = required - root.heldBytes;
|
|
1686
|
+
await root.lease.grow(root.call, {
|
|
1687
|
+
bytes,
|
|
1688
|
+
scratchBytes: 0
|
|
1689
|
+
});
|
|
1690
|
+
root.heldBytes += bytes;
|
|
1691
|
+
}
|
|
1692
|
+
super.set(key, value);
|
|
1693
|
+
return this;
|
|
1694
|
+
}
|
|
1695
|
+
delete(key) {
|
|
1696
|
+
const value = super.get(key), deleted = super.delete(key);
|
|
1697
|
+
if (value !== void 0) {
|
|
1698
|
+
const root = this.roots.get(this.facts(value).initial);
|
|
1699
|
+
if (root) this.settle(root);
|
|
1700
|
+
}
|
|
1701
|
+
return deleted;
|
|
1702
|
+
}
|
|
1703
|
+
/** Drops retained metadata before releasing its shared reservation. */
|
|
1704
|
+
clear() {
|
|
1705
|
+
for (const root of [...this.roots.values()]) this.invalidate(root);
|
|
1706
|
+
}
|
|
1707
|
+
};
|
|
1708
|
+
/** Applies a tighter owner-local memory ceiling while preserving shared resident accounting. */
|
|
1709
|
+
function trimCursorCache(entries, retained) {
|
|
1710
|
+
let bytes = 0;
|
|
1711
|
+
for (const entry of entries.values()) bytes += bytesOf(retained(entry));
|
|
1712
|
+
while (bytes > 8388608 || entries.size > 1024) {
|
|
1713
|
+
const oldest = entries.entries().next().value;
|
|
1714
|
+
if (!oldest) break;
|
|
1715
|
+
bytes -= bytesOf(retained(oldest[1]));
|
|
1716
|
+
entries.delete(oldest[0]);
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
//#endregion
|
|
1720
|
+
//#region src/server-pages.ts
|
|
1721
|
+
/** Header-only server pages and explicit bounded safe-detail fragments. */
|
|
1722
|
+
const Tokens = z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional().describe("Desired delivery tokens; the host may allocate fewer.");
|
|
1723
|
+
const Query = z.union([z.strictObject({ all: z.literal(true).describe("List configured server headers without configuration bodies.") }), z.strictObject({ serverIds: z.array(z.uuid().describe("Exact selected MCP server id.")).min(1).max(64).describe("Selected server ids whose summaries are needed; unknown or unselected members refuse this query.") })]);
|
|
1724
|
+
const Start = z.union([z.strictObject({
|
|
1725
|
+
queries: z.array(Query).min(1).max(64).describe("Ordered directory queries; limit and tokens are shared by the whole page."),
|
|
1726
|
+
view: z.literal("summary").default("summary").describe("Header summaries only; default summary, no configuration bodies."),
|
|
1727
|
+
limit: z.number().int().min(1).max(100).default(50).describe("Maximum total server headers on this page; default 50, hard maximum 100."),
|
|
1728
|
+
outputTokens: Tokens
|
|
1729
|
+
}), z.strictObject({
|
|
1730
|
+
queries: z.tuple([z.strictObject({ serverIds: z.tuple([z.uuid()]).describe("Exactly one selected server id for safe configuration details.") })]).describe("Exactly one query containing exactly one selected server id."),
|
|
1731
|
+
view: z.literal("details").describe("Safe configuration fragments for exactly one selected server."),
|
|
1732
|
+
outputTokens: Tokens
|
|
1733
|
+
})]);
|
|
1734
|
+
const Continue = z.strictObject({
|
|
1735
|
+
cursor: z.string().min(1).max(512).regex(/^[\x21-\x7e]+$/).describe("Opaque continuation; copy next.arguments without changing queries or view."),
|
|
1736
|
+
outputTokens: Tokens
|
|
1737
|
+
});
|
|
1738
|
+
const Input = z.union([Start, Continue]);
|
|
1739
|
+
const Header = z.strictObject({
|
|
1740
|
+
id: z.string(),
|
|
1741
|
+
slug: z.string(),
|
|
1742
|
+
name: z.string(),
|
|
1743
|
+
transport: z.enum(["stdio", "http"]),
|
|
1744
|
+
enabled: z.boolean(),
|
|
1745
|
+
selected: z.boolean(),
|
|
1746
|
+
connectionState: z.string()
|
|
1747
|
+
});
|
|
1748
|
+
const Next = z.strictObject({
|
|
1749
|
+
tool: z.literal("mcp_server_list"),
|
|
1750
|
+
arguments: Continue
|
|
1751
|
+
});
|
|
1752
|
+
const Output = z.strictObject({
|
|
1753
|
+
ok: z.literal(true),
|
|
1754
|
+
complete: z.boolean(),
|
|
1755
|
+
results: z.array(z.union([z.strictObject({
|
|
1756
|
+
index: z.number().int().nonnegative(),
|
|
1757
|
+
ok: z.literal(true),
|
|
1758
|
+
complete: z.boolean(),
|
|
1759
|
+
value: z.union([z.array(Header), z.strictObject({
|
|
1760
|
+
serverId: z.string(),
|
|
1761
|
+
field: z.literal("details"),
|
|
1762
|
+
text: z.string(),
|
|
1763
|
+
range: z.strictObject({
|
|
1764
|
+
offset: z.number(),
|
|
1765
|
+
length: z.number(),
|
|
1766
|
+
complete: z.boolean()
|
|
1767
|
+
})
|
|
1768
|
+
})])
|
|
1769
|
+
}), z.strictObject({
|
|
1770
|
+
index: z.number().int().nonnegative(),
|
|
1771
|
+
ok: z.literal(false),
|
|
1772
|
+
complete: z.literal(true),
|
|
1773
|
+
error: z.strictObject({
|
|
1774
|
+
code: z.string(),
|
|
1775
|
+
message: z.string().refine((value) => [...value].length <= 256).meta({ maxLength: 256 })
|
|
1776
|
+
})
|
|
1777
|
+
})])),
|
|
1778
|
+
next: Next.nullable(),
|
|
1779
|
+
effective: z.strictObject({
|
|
1780
|
+
limit: z.number(),
|
|
1781
|
+
outputTokens: z.number()
|
|
1782
|
+
})
|
|
1783
|
+
});
|
|
1784
|
+
/** Builds exact pages over native headers; a details call opens only one selected configuration. */
|
|
1785
|
+
function serverPages(deps) {
|
|
1786
|
+
const cursors = new QueryCursorCache((state) => ({
|
|
1787
|
+
initial: state.position.initial,
|
|
1788
|
+
content: state.result && "content" in state.result ? state.result.content : void 0
|
|
1789
|
+
}), deps.resources);
|
|
1790
|
+
const sourceVersion = () => {
|
|
1791
|
+
const hash = createHash("sha256").update(String(deps.store.directoryVersion()));
|
|
1792
|
+
for (const secret of [...deps.secrets()].sort()) hash.update(JSON.stringify(secret));
|
|
1793
|
+
return hash.digest("hex");
|
|
1794
|
+
};
|
|
1795
|
+
const failure = (code, message, next = null) => ({
|
|
1796
|
+
content: JSON.stringify({
|
|
1797
|
+
ok: false,
|
|
1798
|
+
error: {
|
|
1799
|
+
code,
|
|
1800
|
+
message,
|
|
1801
|
+
retryable: next !== null
|
|
1802
|
+
},
|
|
1803
|
+
next
|
|
1804
|
+
}),
|
|
1805
|
+
isError: true
|
|
1806
|
+
});
|
|
1807
|
+
return cursors.wrap({
|
|
1808
|
+
name: "mcp_server_list",
|
|
1809
|
+
preload: false,
|
|
1810
|
+
description: "Read bounded MCP server summaries by default. view=details accepts exactly one selected server id and pages its safe configuration. Follow next.arguments; complete tool definitions use tool_search.",
|
|
1811
|
+
inputSchema: Input,
|
|
1812
|
+
outputSchema: toolOutputSchema(Output, Input, "mcp_server_list"),
|
|
1813
|
+
deliveryKind: "exact-page",
|
|
1814
|
+
async execute(input, call) {
|
|
1815
|
+
call.signal.throwIfAborted();
|
|
1816
|
+
const now = performance.now(), address = JSON.stringify(call.address), saved = "cursor" in input ? cursors.get(input.cursor) : void 0;
|
|
1817
|
+
if ("cursor" in input && !saved) return failure("cursor_invalid", "Unknown server cursor.");
|
|
1818
|
+
if (saved && (saved.session !== call.sessionId || saved.address !== address || saved.generation !== call.historyGeneration)) return failure("cursor_invalid", "Cursor does not belong to this effective session.");
|
|
1819
|
+
if (saved && (now - saved.used > 6e5 || now - saved.created > 36e5)) return failure("cursor_expired", "Start the server query again.", {
|
|
1820
|
+
tool: "mcp_server_list",
|
|
1821
|
+
arguments: saved.position.initial
|
|
1822
|
+
});
|
|
1823
|
+
const p = saved?.position ?? {
|
|
1824
|
+
initial: input,
|
|
1825
|
+
index: 0,
|
|
1826
|
+
offset: 0,
|
|
1827
|
+
version: sourceVersion()
|
|
1828
|
+
};
|
|
1829
|
+
if (p.version !== sourceVersion()) return failure("source_changed", "Server catalogue changed; start again.", {
|
|
1830
|
+
tool: "mcp_server_list",
|
|
1831
|
+
arguments: p.initial
|
|
1832
|
+
});
|
|
1833
|
+
if (saved?.result) {
|
|
1834
|
+
const cost = call.output.measure(saved.result);
|
|
1835
|
+
if (cost > call.output.outputTokens) return failure("page_too_small", "The saved exact server page needs a larger independent allocation.", cost <= call.output.maximumTokens ? {
|
|
1836
|
+
tool: "mcp_server_list",
|
|
1837
|
+
arguments: {
|
|
1838
|
+
...input,
|
|
1839
|
+
outputTokens: cost
|
|
1840
|
+
}
|
|
1841
|
+
} : null);
|
|
1842
|
+
call.output.acceptExact(saved.result);
|
|
1843
|
+
saved.used = now;
|
|
1844
|
+
return saved.result;
|
|
1845
|
+
}
|
|
1846
|
+
const limit = p.initial.view === "summary" ? p.initial.limit : 1, cursor = randomUUID(), query = p.initial.queries[p.index], last = p.index === p.initial.queries.length - 1;
|
|
1847
|
+
let following, result;
|
|
1848
|
+
const build = (row, complete) => ({ content: JSON.stringify({
|
|
1849
|
+
ok: true,
|
|
1850
|
+
complete: complete && last,
|
|
1851
|
+
results: [row],
|
|
1852
|
+
next: complete && last ? null : {
|
|
1853
|
+
tool: "mcp_server_list",
|
|
1854
|
+
arguments: { cursor }
|
|
1855
|
+
},
|
|
1856
|
+
effective: {
|
|
1857
|
+
limit,
|
|
1858
|
+
outputTokens: call.output.outputTokens
|
|
1859
|
+
}
|
|
1860
|
+
}) });
|
|
1861
|
+
try {
|
|
1862
|
+
if (p.initial.view === "details") {
|
|
1863
|
+
const id = p.initial.queries[0].serverIds[0], window = unicodeWindow(JSON.stringify(deps.details(id, call)), p.offset, Math.min(32768, Math.max(1, call.output.outputTokens * 4))), remaining = window.points;
|
|
1864
|
+
let length = Math.min(remaining.length, call.output.outputTokens * 4);
|
|
1865
|
+
const make = (n) => build({
|
|
1866
|
+
index: 0,
|
|
1867
|
+
ok: true,
|
|
1868
|
+
complete: window.complete && n === remaining.length,
|
|
1869
|
+
value: {
|
|
1870
|
+
serverId: id,
|
|
1871
|
+
field: "details",
|
|
1872
|
+
text: remaining.slice(0, n).join(""),
|
|
1873
|
+
range: {
|
|
1874
|
+
offset: p.offset,
|
|
1875
|
+
length: n,
|
|
1876
|
+
complete: window.complete && n === remaining.length
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
}, window.complete && n === remaining.length);
|
|
1880
|
+
result = make(length);
|
|
1881
|
+
if (call.output.measure(result) > call.output.outputTokens) {
|
|
1882
|
+
let low = 0, high = length;
|
|
1883
|
+
while (low < high) {
|
|
1884
|
+
const mid = Math.ceil((low + high) / 2);
|
|
1885
|
+
if (call.output.measure(make(mid)) <= call.output.outputTokens) low = mid;
|
|
1886
|
+
else high = mid - 1;
|
|
1887
|
+
}
|
|
1888
|
+
length = low;
|
|
1889
|
+
result = make(length);
|
|
1890
|
+
}
|
|
1891
|
+
if (length === 0 && remaining.length > 0) return failure("page_too_small", "Detail metadata does not fit this allowance.");
|
|
1892
|
+
if (!window.complete || length < remaining.length) following = {
|
|
1893
|
+
...p,
|
|
1894
|
+
offset: p.offset + length
|
|
1895
|
+
};
|
|
1896
|
+
} else {
|
|
1897
|
+
const ids = "serverIds" in query ? query.serverIds : void 0;
|
|
1898
|
+
if (ids && !p.after && deps.store.headerPage(call.address.agentId, void 0, 100, ids).items.length !== new Set(ids).size) throw Object.assign(/* @__PURE__ */ new Error("One or more servers are unavailable to this agent."), { code: "not-found" });
|
|
1899
|
+
const page = deps.store.headerPage(call.address.agentId, p.after, limit, ids), secrets = deps.secrets(), items = page.items.map((item) => ({
|
|
1900
|
+
...item,
|
|
1901
|
+
name: redact(item.name, secrets),
|
|
1902
|
+
slug: redact(item.slug, secrets),
|
|
1903
|
+
connectionState: deps.state(item.id)
|
|
1904
|
+
}));
|
|
1905
|
+
let count = items.length;
|
|
1906
|
+
const make = (n) => build({
|
|
1907
|
+
index: p.index,
|
|
1908
|
+
ok: true,
|
|
1909
|
+
complete: page.complete && n === items.length,
|
|
1910
|
+
value: items.slice(0, n)
|
|
1911
|
+
}, page.complete && n === items.length);
|
|
1912
|
+
result = make(count);
|
|
1913
|
+
if (count > 0 && call.output.measure(result) > call.output.outputTokens) {
|
|
1914
|
+
let low = 1;
|
|
1915
|
+
let high = count - 1;
|
|
1916
|
+
count = 0;
|
|
1917
|
+
while (low + 4 <= high) {
|
|
1918
|
+
await setImmediate();
|
|
1919
|
+
call.signal.throwIfAborted();
|
|
1920
|
+
const candidateCount = Math.floor((low + high) / 2);
|
|
1921
|
+
const candidate = make(candidateCount);
|
|
1922
|
+
if (call.output.measure(candidate) <= call.output.outputTokens) {
|
|
1923
|
+
count = candidateCount;
|
|
1924
|
+
result = candidate;
|
|
1925
|
+
low = candidateCount + 1;
|
|
1926
|
+
} else high = candidateCount - 1;
|
|
1927
|
+
}
|
|
1928
|
+
for (let candidateCount = high; candidateCount >= low; candidateCount -= 1) {
|
|
1929
|
+
await setImmediate();
|
|
1930
|
+
call.signal.throwIfAborted();
|
|
1931
|
+
const candidate = make(candidateCount);
|
|
1932
|
+
if (call.output.measure(candidate) <= call.output.outputTokens) {
|
|
1933
|
+
count = candidateCount;
|
|
1934
|
+
result = candidate;
|
|
1935
|
+
break;
|
|
1936
|
+
}
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1939
|
+
if (count === 0 && items.length > 0) return failure("page_too_small", "One server summary does not fit this allowance.");
|
|
1940
|
+
if (!(page.complete && count === items.length)) following = {
|
|
1941
|
+
...p,
|
|
1942
|
+
after: items[count - 1].id
|
|
1943
|
+
};
|
|
1944
|
+
else if (!last) following = {
|
|
1945
|
+
...p,
|
|
1946
|
+
index: p.index + 1,
|
|
1947
|
+
after: void 0
|
|
1948
|
+
};
|
|
1949
|
+
}
|
|
1950
|
+
} catch (error) {
|
|
1951
|
+
call.signal.throwIfAborted();
|
|
1952
|
+
result = build({
|
|
1953
|
+
index: p.index,
|
|
1954
|
+
ok: false,
|
|
1955
|
+
complete: true,
|
|
1956
|
+
error: {
|
|
1957
|
+
code: error.code ?? "source_unavailable",
|
|
1958
|
+
message: "Server query is unavailable to this agent."
|
|
1959
|
+
}
|
|
1960
|
+
}, true);
|
|
1961
|
+
if (!last) following = {
|
|
1962
|
+
...p,
|
|
1963
|
+
index: p.index + 1,
|
|
1964
|
+
after: void 0,
|
|
1965
|
+
offset: 0
|
|
1966
|
+
};
|
|
1967
|
+
}
|
|
1968
|
+
if (call.output.measure(result) > call.output.outputTokens) return failure("page_too_small", "Server page metadata does not fit this allowance.");
|
|
1969
|
+
await cursors.prepare(p.initial, result.content);
|
|
1970
|
+
call.output.acceptExact(result);
|
|
1971
|
+
if (following) {
|
|
1972
|
+
for (const [key, state] of cursors) if (now - state.created > 36e5 || state.session === call.sessionId && state.generation !== call.historyGeneration) cursors.delete(key);
|
|
1973
|
+
while (cursors.size >= 4096) {
|
|
1974
|
+
const oldest = cursors.keys().next().value;
|
|
1975
|
+
if (oldest) cursors.delete(oldest);
|
|
1976
|
+
}
|
|
1977
|
+
await cursors.save(cursor, {
|
|
1978
|
+
position: following,
|
|
1979
|
+
session: call.sessionId,
|
|
1980
|
+
address,
|
|
1981
|
+
generation: call.historyGeneration,
|
|
1982
|
+
created: saved?.created ?? now,
|
|
1983
|
+
used: now
|
|
1984
|
+
});
|
|
1985
|
+
}
|
|
1986
|
+
if (saved) {
|
|
1987
|
+
saved.result = result;
|
|
1988
|
+
trimCursorCache(cursors, (state) => ({
|
|
1989
|
+
initial: state.position.initial,
|
|
1990
|
+
content: state.result && "content" in state.result ? state.result.content : void 0
|
|
1991
|
+
}));
|
|
1992
|
+
saved.used = now;
|
|
1993
|
+
}
|
|
1994
|
+
trimCursorCache(cursors, (state) => ({
|
|
1995
|
+
initial: state.position.initial,
|
|
1996
|
+
content: state.result && "content" in state.result ? state.result.content : void 0
|
|
1997
|
+
}));
|
|
1998
|
+
return result;
|
|
1999
|
+
}
|
|
2000
|
+
});
|
|
2001
|
+
}
|
|
2002
|
+
/** Builds a bounded Unicode window without allocating an array for the complete source. */
|
|
2003
|
+
function unicodeWindow(text, offset, maximum) {
|
|
2004
|
+
let unit = 0, skipped = 0;
|
|
2005
|
+
while (unit < text.length && skipped < offset) {
|
|
2006
|
+
unit += text.codePointAt(unit) > 65535 ? 2 : 1;
|
|
2007
|
+
skipped++;
|
|
2008
|
+
}
|
|
2009
|
+
const points = [];
|
|
2010
|
+
while (unit < text.length && points.length < maximum) {
|
|
2011
|
+
const size = text.codePointAt(unit) > 65535 ? 2 : 1;
|
|
2012
|
+
points.push(text.slice(unit, unit + size));
|
|
2013
|
+
unit += size;
|
|
2014
|
+
}
|
|
2015
|
+
return {
|
|
2016
|
+
points,
|
|
2017
|
+
complete: unit === text.length
|
|
2018
|
+
};
|
|
2019
|
+
}
|
|
2020
|
+
//#endregion
|
|
2021
|
+
//#region src/tool-names.ts
|
|
2022
|
+
/** Canonical names shared by tool registration and browser presentation. */
|
|
2023
|
+
const TOOL_NAMES = [
|
|
2024
|
+
"mcp_server_list",
|
|
2025
|
+
"mcp_server_create",
|
|
2026
|
+
"mcp_server_update",
|
|
2027
|
+
"mcp_server_set_selected"
|
|
2028
|
+
];
|
|
2029
|
+
//#endregion
|
|
2030
|
+
//#region src/management-tools.ts
|
|
2031
|
+
/** Strict plugin configuration for individually disabling management tools. */
|
|
2032
|
+
const McpConfig = z.object({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).strict().default({ disabled: [] });
|
|
2033
|
+
/** One server's creation, `transport` paired with its own `config`. */
|
|
2034
|
+
const CreatePaired = z.discriminatedUnion("transport", [z.object({
|
|
2035
|
+
slug: z.string().describe("Unique mapped-name prefix matching ^[a-z0-9][a-z0-9-]{0,23}$; cannot be changed after creation."),
|
|
2036
|
+
name: z.string().trim().min(1).max(80).describe("Server display name, 1–80 UTF-16 code units after trimming."),
|
|
2037
|
+
transport: z.literal("stdio"),
|
|
2038
|
+
config: StdioConfigSchema,
|
|
2039
|
+
select: z.boolean().default(true).describe("Select the new server for this Agent after approval; default true.")
|
|
2040
|
+
}).strict(), z.object({
|
|
2041
|
+
slug: z.string().describe("Unique mapped-name prefix matching ^[a-z0-9][a-z0-9-]{0,23}$; cannot be changed after creation."),
|
|
2042
|
+
name: z.string().trim().min(1).max(80).describe("Server display name, 1–80 UTF-16 code units after trimming."),
|
|
2043
|
+
transport: z.literal("http"),
|
|
2044
|
+
config: HttpConfigSchema,
|
|
2045
|
+
select: z.boolean().default(true).describe("Select the new server for this Agent after approval; default true.")
|
|
2046
|
+
}).strict()]);
|
|
2047
|
+
/** The parameters as the model sees them: one object, because an
|
|
2048
|
+
* OpenAI-compatible endpoint refuses a tool whose top level is not
|
|
2049
|
+
* `type: "object"`. The pairing `CreatePaired` states is checked here. */
|
|
2050
|
+
const Create = z.object({
|
|
2051
|
+
slug: z.string().describe("Unique mapped-name prefix matching ^[a-z0-9][a-z0-9-]{0,23}$; cannot be changed after creation."),
|
|
2052
|
+
name: z.string().trim().min(1).max(80).describe("Server display name, 1–80 UTF-16 code units after trimming."),
|
|
2053
|
+
transport: z.enum(["stdio", "http"]).describe("Transport paired with its matching config: local stdio command or remote HTTP endpoint."),
|
|
2054
|
+
config: z.union([StdioConfigSchema, HttpConfigSchema]).describe("Complete configuration matching transport; credentials are referenced by names, never included as plain values."),
|
|
2055
|
+
select: z.boolean().default(true).describe("Select the new server for this Agent after approval; default true.")
|
|
2056
|
+
}).strict().superRefine((value, ctx) => {
|
|
2057
|
+
if (!CreatePaired.safeParse(value).success) ctx.addIssue({
|
|
2058
|
+
code: "custom",
|
|
2059
|
+
path: ["config"],
|
|
2060
|
+
message: `config does not match transport ${value.transport}`
|
|
2061
|
+
});
|
|
2062
|
+
});
|
|
2063
|
+
const Update = z.object({
|
|
2064
|
+
serverId: z.string().uuid().describe("Exact configured MCP server UUID from mcp_server_list."),
|
|
2065
|
+
name: z.string().trim().min(1).max(80).optional().describe("Replacement display name, 1–80 UTF-16 code units after trimming; omit to retain."),
|
|
2066
|
+
config: z.union([StdioConfigSchema, HttpConfigSchema]).optional().describe("Complete replacement configuration matching the existing transport; omit to retain."),
|
|
2067
|
+
expectedRevision: z.string().optional().describe("Observed configuration revision; a mismatch refuses the update before writing.")
|
|
2068
|
+
}).strict().refine((value) => value.name !== void 0 || value.config !== void 0, "a change is required");
|
|
2069
|
+
const Select = z.object({
|
|
2070
|
+
serverId: z.string().uuid().describe("Exact configured MCP server UUID from mcp_server_list."),
|
|
2071
|
+
selected: z.boolean().describe("Whether this Agent selects the server after the approved change.")
|
|
2072
|
+
}).strict();
|
|
2073
|
+
const SelectInput = batchInput({
|
|
2074
|
+
operationId: z.uuid().describe("New UUID for this selection operation; reuse only when retrying the identical operation."),
|
|
2075
|
+
changes: z.array(Select).min(1).max(64).describe("Selection changes, 1–64 members under one approval and transaction.")
|
|
2076
|
+
}, "changes");
|
|
2077
|
+
const MutationOutput = z.strictObject({
|
|
2078
|
+
ok: z.literal(true),
|
|
2079
|
+
committed: z.literal(true),
|
|
2080
|
+
status: z.literal("ok"),
|
|
2081
|
+
data: z.union([
|
|
2082
|
+
z.strictObject({
|
|
2083
|
+
serverId: z.string(),
|
|
2084
|
+
selected: z.boolean(),
|
|
2085
|
+
summary: z.string().max(256)
|
|
2086
|
+
}),
|
|
2087
|
+
z.strictObject({
|
|
2088
|
+
serverId: z.string(),
|
|
2089
|
+
revision: z.string(),
|
|
2090
|
+
summary: z.string().max(256)
|
|
2091
|
+
}),
|
|
2092
|
+
z.strictObject({ summary: z.string().max(256) }),
|
|
2093
|
+
z.strictObject({
|
|
2094
|
+
operationId: z.uuid(),
|
|
2095
|
+
operationState: z.enum(["admitted", "committed"]),
|
|
2096
|
+
value: z.strictObject({
|
|
2097
|
+
serverIds: z.array(z.string()),
|
|
2098
|
+
revision: z.number(),
|
|
2099
|
+
contentHash: z.string()
|
|
2100
|
+
})
|
|
2101
|
+
})
|
|
2102
|
+
])
|
|
2103
|
+
});
|
|
2104
|
+
const revisionOf = (record) => createHash("sha256").update(JSON.stringify(record)).digest("hex");
|
|
2105
|
+
const fail = (code, message) => {
|
|
2106
|
+
throw Object.assign(new Error(message), { code });
|
|
2107
|
+
};
|
|
2108
|
+
/** Registers the five model-facing management tools. */
|
|
2109
|
+
function registerMcpManagementTools(deps) {
|
|
2110
|
+
const { store, connections, credentials, oauth } = deps;
|
|
2111
|
+
const requireServer = (serverId) => {
|
|
2112
|
+
const record = store.server(serverId);
|
|
2113
|
+
if (!record) throw new Error("no such MCP server");
|
|
2114
|
+
return record;
|
|
2115
|
+
};
|
|
2116
|
+
const requireSelected = (serverId, agentId) => {
|
|
2117
|
+
const record = requireServer(serverId);
|
|
2118
|
+
if (!store.isSelected(agentId, serverId)) throw new Error("this server is not selected by this agent");
|
|
2119
|
+
return record;
|
|
2120
|
+
};
|
|
2121
|
+
const secretsOf = (serverId) => {
|
|
2122
|
+
return secretValues([...credentials.list(serverId).filter((status) => status.set).map((status) => credentials.get(serverId, status.name)), ...oauth.secrets(serverId)]);
|
|
2123
|
+
};
|
|
2124
|
+
const allSecrets = () => {
|
|
2125
|
+
const values = [];
|
|
2126
|
+
let after;
|
|
2127
|
+
while (true) {
|
|
2128
|
+
const page = store.headerPage("", after, 100);
|
|
2129
|
+
for (const row of page.items) values.push(...secretsOf(row.id));
|
|
2130
|
+
if (page.complete) break;
|
|
2131
|
+
after = page.items.at(-1).id;
|
|
2132
|
+
}
|
|
2133
|
+
return secretValues(values);
|
|
2134
|
+
};
|
|
2135
|
+
const sanitize = (value, secrets) => {
|
|
2136
|
+
if (typeof value === "string") return redact(value, secrets);
|
|
2137
|
+
if (Array.isArray(value)) return value.map((item) => sanitize(item, secrets));
|
|
2138
|
+
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sanitize(item, secrets)]));
|
|
2139
|
+
return value;
|
|
2140
|
+
};
|
|
2141
|
+
const safeConfig = (record) => sanitize(record.config, allSecrets());
|
|
2142
|
+
const changedExecutionParty = (before, after) => {
|
|
2143
|
+
if (before.transport !== after.transport) return true;
|
|
2144
|
+
return before.transport === "stdio" && after.transport === "stdio" ? JSON.stringify([
|
|
2145
|
+
before.config.command,
|
|
2146
|
+
before.config.args,
|
|
2147
|
+
before.config.cwd
|
|
2148
|
+
]) !== JSON.stringify([
|
|
2149
|
+
after.config.command,
|
|
2150
|
+
after.config.args,
|
|
2151
|
+
after.config.cwd
|
|
2152
|
+
]) : before.transport === "http" && after.transport === "http" && JSON.stringify([before.config.url, before.config.auth]) !== JSON.stringify([after.config.url, after.config.auth]);
|
|
2153
|
+
};
|
|
2154
|
+
const credentialRebind = (before, after) => changedExecutionParty(before, after) && (credentials.list(before.id).some((status) => status.set) || before.transport === "http" && before.config.auth === "oauth" && oauth.status(before.id).authorized);
|
|
2155
|
+
const containsKnownSecret = (value, secrets) => {
|
|
2156
|
+
if (typeof value === "string") return secrets.some((secret) => value.includes(secret));
|
|
2157
|
+
if (Array.isArray(value)) return value.some((item) => containsKnownSecret(item, secrets));
|
|
2158
|
+
return value !== null && typeof value === "object" && Object.values(value).some((item) => containsKnownSecret(item, secrets));
|
|
2159
|
+
};
|
|
2160
|
+
const readResult = (data) => ({ content: JSON.stringify({
|
|
2161
|
+
ok: true,
|
|
2162
|
+
committed: true,
|
|
2163
|
+
status: "ok",
|
|
2164
|
+
data
|
|
2165
|
+
}) });
|
|
2166
|
+
const serverDetail = (serverId, agentId) => {
|
|
2167
|
+
try {
|
|
2168
|
+
const record = requireSelected(serverId, agentId);
|
|
2169
|
+
return sanitize({
|
|
2170
|
+
id: record.id,
|
|
2171
|
+
slug: record.slug,
|
|
2172
|
+
name: record.name,
|
|
2173
|
+
transport: record.transport,
|
|
2174
|
+
enabled: record.enabled,
|
|
2175
|
+
config: safeConfig(record),
|
|
2176
|
+
revision: revisionOf(record),
|
|
2177
|
+
agentIds: store.agentsOf(serverId),
|
|
2178
|
+
credentials: credentials.list(serverId).map(({ name, set }) => ({
|
|
2179
|
+
name,
|
|
2180
|
+
set
|
|
2181
|
+
})),
|
|
2182
|
+
connectionState: connections.status(serverId).state,
|
|
2183
|
+
...record.transport === "http" && record.config.auth === "oauth" ? { oauthAuthorized: oauth.status(serverId).authorized } : {}
|
|
2184
|
+
}, allSecrets());
|
|
2185
|
+
} catch (cause) {
|
|
2186
|
+
throw Object.assign(/* @__PURE__ */ new Error("MCP server details are unavailable."), { code: cause?.name === "CredentialUnavailableError" ? "credential-unavailable" : "not-found" });
|
|
2187
|
+
}
|
|
2188
|
+
};
|
|
2189
|
+
deps.register(serverPages({
|
|
2190
|
+
resources: deps.resources,
|
|
2191
|
+
store,
|
|
2192
|
+
secrets: allSecrets,
|
|
2193
|
+
state: (id) => connections.status(id).state,
|
|
2194
|
+
details: (id, call) => serverDetail(id, deps.definitions.read(call).agentId)
|
|
2195
|
+
}));
|
|
2196
|
+
deps.register({
|
|
2197
|
+
name: "mcp_server_create",
|
|
2198
|
+
preload: false,
|
|
2199
|
+
description: "Create an MCP server and optionally select it for this agent after approval.",
|
|
2200
|
+
inputSchema: Create,
|
|
2201
|
+
outputSchema: toolOutputSchema(MutationOutput, Create, "mcp_server_create"),
|
|
2202
|
+
deliveryKind: "receipt",
|
|
2203
|
+
async execute(fields, ctx) {
|
|
2204
|
+
let input = CreatePaired.parse(fields);
|
|
2205
|
+
const agentId = deps.definitions.read(ctx).agentId;
|
|
2206
|
+
checkSlug(input.slug);
|
|
2207
|
+
if (containsKnownSecret(input, allSecrets())) fail("invalid-input", "Configuration contains a stored credential");
|
|
2208
|
+
if (input.transport === "stdio") input = {
|
|
2209
|
+
...input,
|
|
2210
|
+
config: await resolveStdioConfig(input.config, deps.management.commands)
|
|
2211
|
+
};
|
|
2212
|
+
if (store.serverBySlug(input.slug)) fail("conflict", "MCP server slug is already used");
|
|
2213
|
+
const id = `create-${createHash("sha256").update(JSON.stringify(input)).digest("hex")}`;
|
|
2214
|
+
if (ctx.answer && !ctx.answer.answers.some((answer) => answer.questionId === deps.approval.questionId(id))) fail("conflict", "Approved input has changed");
|
|
2215
|
+
const decision = deps.approval.decide(ctx, {
|
|
2216
|
+
id,
|
|
2217
|
+
subject: `Create MCP server ${input.name}`,
|
|
2218
|
+
reason: JSON.stringify(input),
|
|
2219
|
+
warning: input.transport === "stdio" ? "The command runs outside a sandbox." : "This server may receive tool inputs.",
|
|
2220
|
+
accepts: [
|
|
2221
|
+
"allowed-once",
|
|
2222
|
+
"allowed-session",
|
|
2223
|
+
"allowed-always",
|
|
2224
|
+
"rejected"
|
|
2225
|
+
],
|
|
2226
|
+
remember: {
|
|
2227
|
+
key: "mcp-server-create",
|
|
2228
|
+
label: "Create MCP servers"
|
|
2229
|
+
}
|
|
2230
|
+
});
|
|
2231
|
+
if (decision.kind === "ask") return decision.result;
|
|
2232
|
+
if (!decision.result.kind.startsWith("allowed-")) return {
|
|
2233
|
+
content: "MCP creation was not approved.",
|
|
2234
|
+
isError: true
|
|
2235
|
+
};
|
|
2236
|
+
const record = await saveServer(deps.management, {
|
|
2237
|
+
...input,
|
|
2238
|
+
acknowledge: true
|
|
2239
|
+
}, {
|
|
2240
|
+
agentId,
|
|
2241
|
+
selected: input.select
|
|
2242
|
+
}, ctx);
|
|
2243
|
+
return readResult({
|
|
2244
|
+
serverId: record.id,
|
|
2245
|
+
selected: input.select,
|
|
2246
|
+
summary: "Configuration saved; connection status is reported separately."
|
|
2247
|
+
});
|
|
2248
|
+
}
|
|
2249
|
+
});
|
|
2250
|
+
deps.register({
|
|
2251
|
+
name: "mcp_server_update",
|
|
2252
|
+
preload: false,
|
|
2253
|
+
description: "Update a selected shared MCP server after approval.",
|
|
2254
|
+
inputSchema: Update,
|
|
2255
|
+
outputSchema: toolOutputSchema(MutationOutput, Update, "mcp_server_update"),
|
|
2256
|
+
deliveryKind: "receipt",
|
|
2257
|
+
async execute(input, ctx) {
|
|
2258
|
+
const agentId = deps.definitions.read(ctx).agentId;
|
|
2259
|
+
const previous = requireSelected(input.serverId, agentId);
|
|
2260
|
+
const revision = revisionOf(previous);
|
|
2261
|
+
if (input.expectedRevision && input.expectedRevision !== revision) fail("conflict", "MCP server changed");
|
|
2262
|
+
let config = previous.transport === "stdio" ? StdioConfigSchema.parse(input.config ?? previous.config) : HttpConfigSchema.parse(input.config ?? previous.config);
|
|
2263
|
+
if (containsKnownSecret(input, allSecrets())) fail("invalid-input", "Configuration contains a stored credential");
|
|
2264
|
+
if (previous.transport === "stdio") config = await resolveStdioConfig(StdioConfigSchema.parse(config), deps.management.commands);
|
|
2265
|
+
const next = {
|
|
2266
|
+
...previous,
|
|
2267
|
+
name: input.name ?? previous.name,
|
|
2268
|
+
config
|
|
2269
|
+
};
|
|
2270
|
+
if (credentialRebind(previous, next)) fail("credential-rebind-required", "Stored credentials require a person to rebind this server");
|
|
2271
|
+
if (JSON.stringify(next) === JSON.stringify(previous)) return readResult({ summary: "Configuration is unchanged." });
|
|
2272
|
+
const id = `update-${createHash("sha256").update(JSON.stringify([
|
|
2273
|
+
revision,
|
|
2274
|
+
input,
|
|
2275
|
+
store.agentsOf(previous.id)
|
|
2276
|
+
])).digest("hex")}`;
|
|
2277
|
+
if (ctx.answer && !ctx.answer.answers.some((answer) => answer.questionId === deps.approval.questionId(id))) fail("conflict", "MCP configuration changed since approval");
|
|
2278
|
+
const decision = deps.approval.decide(ctx, {
|
|
2279
|
+
id,
|
|
2280
|
+
subject: `Update MCP server ${redact(previous.name, allSecrets())}`,
|
|
2281
|
+
reason: JSON.stringify({
|
|
2282
|
+
before: safeConfig(previous),
|
|
2283
|
+
after: safeConfig(next),
|
|
2284
|
+
agents: store.agentsOf(previous.id)
|
|
2285
|
+
}),
|
|
2286
|
+
accepts: [
|
|
2287
|
+
"allowed-once",
|
|
2288
|
+
"allowed-session",
|
|
2289
|
+
"allowed-always",
|
|
2290
|
+
"rejected"
|
|
2291
|
+
],
|
|
2292
|
+
remember: {
|
|
2293
|
+
key: "mcp-server-update",
|
|
2294
|
+
label: "Update selected MCP servers"
|
|
2295
|
+
}
|
|
2296
|
+
});
|
|
2297
|
+
if (decision.kind === "ask") return decision.result;
|
|
2298
|
+
if (!decision.result.kind.startsWith("allowed-")) return {
|
|
2299
|
+
content: "MCP update was not approved.",
|
|
2300
|
+
isError: true
|
|
2301
|
+
};
|
|
2302
|
+
const record = await saveServer(deps.management, {
|
|
2303
|
+
id: previous.id,
|
|
2304
|
+
slug: previous.slug,
|
|
2305
|
+
name: next.name,
|
|
2306
|
+
transport: previous.transport,
|
|
2307
|
+
config,
|
|
2308
|
+
acknowledge: true
|
|
2309
|
+
});
|
|
2310
|
+
return readResult({
|
|
2311
|
+
serverId: record.id,
|
|
2312
|
+
revision: revisionOf(record),
|
|
2313
|
+
summary: "Configuration saved; connection status is reported separately."
|
|
2314
|
+
});
|
|
2315
|
+
}
|
|
2316
|
+
});
|
|
2317
|
+
deps.register({
|
|
2318
|
+
name: "mcp_server_set_selected",
|
|
2319
|
+
preload: false,
|
|
2320
|
+
description: "Apply one complete Agent MCP selection intent atomically after one approval binds its original revision/hash and every change.",
|
|
2321
|
+
inputSchema: SelectInput,
|
|
2322
|
+
outputSchema: toolOutputSchema(MutationOutput, SelectInput, "mcp_server_set_selected"),
|
|
2323
|
+
deliveryKind: "receipt",
|
|
2324
|
+
async execute(input, ctx) {
|
|
2325
|
+
const agentId = deps.definitions.read(ctx).agentId;
|
|
2326
|
+
const intent = {
|
|
2327
|
+
scope: `agent:${agentId}`,
|
|
2328
|
+
method: "mcp_server_set_selected",
|
|
2329
|
+
operationId: input.operationId,
|
|
2330
|
+
params: input
|
|
2331
|
+
};
|
|
2332
|
+
const replay = deps.management.operations.lookup(intent);
|
|
2333
|
+
if (replay) return readResult(replay);
|
|
2334
|
+
const changes = /* @__PURE__ */ new Map();
|
|
2335
|
+
for (const change of input.changes) {
|
|
2336
|
+
requireServer(change.serverId);
|
|
2337
|
+
if (changes.has(change.serverId) && changes.get(change.serverId) !== change.selected) throw new Error("conflicting selection changes");
|
|
2338
|
+
changes.set(change.serverId, change.selected);
|
|
2339
|
+
}
|
|
2340
|
+
const state = deps.management.agentConfig.state(agentId);
|
|
2341
|
+
const before = store.agentServers(agentId);
|
|
2342
|
+
const final = new Set(before);
|
|
2343
|
+
for (const [id, selected] of changes) if (selected) final.add(id);
|
|
2344
|
+
else final.delete(id);
|
|
2345
|
+
const serverIds = [...final].sort();
|
|
2346
|
+
if (JSON.stringify(before) !== JSON.stringify(serverIds)) {
|
|
2347
|
+
const key = `select-${createHash("sha256").update(JSON.stringify({
|
|
2348
|
+
state,
|
|
2349
|
+
changes: input.changes,
|
|
2350
|
+
servers: [...changes.keys()].map((id) => revisionOf(requireServer(id)))
|
|
2351
|
+
})).digest("hex")}`;
|
|
2352
|
+
if (ctx.answer && !ctx.answer.answers.some((answer) => answer.questionId === deps.approval.questionId(key))) fail("conflict", "MCP selection changed since approval");
|
|
2353
|
+
const decision = deps.approval.decide(ctx, {
|
|
2354
|
+
id: key,
|
|
2355
|
+
subject: `Change ${changes.size} MCP selections`,
|
|
2356
|
+
reason: "Apply this complete Agent selection for subsequent steps.",
|
|
2357
|
+
accepts: [
|
|
2358
|
+
"allowed-once",
|
|
2359
|
+
"allowed-session",
|
|
2360
|
+
"allowed-always",
|
|
2361
|
+
"rejected"
|
|
2362
|
+
],
|
|
2363
|
+
remember: {
|
|
2364
|
+
key,
|
|
2365
|
+
label: "Select MCP servers"
|
|
2366
|
+
}
|
|
2367
|
+
});
|
|
2368
|
+
if (decision.kind === "ask") return decision.result;
|
|
2369
|
+
if (!decision.result.kind.startsWith("allowed-")) return {
|
|
2370
|
+
content: "MCP selection was not approved.",
|
|
2371
|
+
isError: true
|
|
2372
|
+
};
|
|
2373
|
+
}
|
|
2374
|
+
deps.management.agentConfig.check(agentId, state.revision, state.contentHash);
|
|
2375
|
+
const changed = JSON.stringify(before) !== JSON.stringify(serverIds);
|
|
2376
|
+
const prepared = changed ? deps.management.agentConfig.prepare(agentId, { extensionData: { "@eum-agent/integration-mcp": { mcpServerIds: serverIds } } }, ctx) : void 0;
|
|
2377
|
+
let committed = false;
|
|
2378
|
+
try {
|
|
2379
|
+
const receipt = deps.management.operations.atomic(intent, (scope) => {
|
|
2380
|
+
if (prepared) {
|
|
2381
|
+
if (prepared.connectionIdentity !== scope.connectionIdentity) throw new Error("foreign Agent transaction participant");
|
|
2382
|
+
prepared.assertCurrent();
|
|
2383
|
+
scope.afterRollback(() => prepared.abort());
|
|
2384
|
+
scope.afterCommit(() => prepared.settle());
|
|
2385
|
+
prepared.apply();
|
|
2386
|
+
}
|
|
2387
|
+
return {
|
|
2388
|
+
serverIds: store.agentServers(agentId),
|
|
2389
|
+
...deps.management.agentConfig.state(agentId)
|
|
2390
|
+
};
|
|
2391
|
+
});
|
|
2392
|
+
committed = receipt.operationState !== "admitted";
|
|
2393
|
+
if (changed) deps.management.announce();
|
|
2394
|
+
return readResult(receipt);
|
|
2395
|
+
} catch (error) {
|
|
2396
|
+
if (!committed) prepared?.abort();
|
|
2397
|
+
throw error;
|
|
2398
|
+
}
|
|
2399
|
+
}
|
|
2400
|
+
});
|
|
2401
|
+
}
|
|
2402
|
+
//#endregion
|
|
2403
|
+
//#region src/command-paste.ts
|
|
2404
|
+
/** Executable-field paste rules follow the resident physical host. */
|
|
2405
|
+
/** Preserves raw absolute executable-field pastes; other input uses direct host argv grammar. */
|
|
2406
|
+
function parseCommandPaste(text, commands) {
|
|
2407
|
+
if (!text || /[\0\r\n]/.test(text)) throw new Error("invalid-command-text");
|
|
2408
|
+
const windows = commands.platform === "win32";
|
|
2409
|
+
return (windows ? win32.isAbsolute(text) && /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(text) : posix.isAbsolute(text)) ? {
|
|
2410
|
+
file: text,
|
|
2411
|
+
args: [],
|
|
2412
|
+
syntax: windows ? "windows-argv" : "posix-argv"
|
|
2413
|
+
} : commands.parseCommand(text);
|
|
2414
|
+
}
|
|
2415
|
+
//#endregion
|
|
2416
|
+
//#region src/command-text.ts
|
|
2417
|
+
/** Shared command-paste input bounds for the owner RPC and browser editor. */
|
|
2418
|
+
const COMMAND_TEXT_LIMIT = 65536;
|
|
2419
|
+
/** Checks the UTF-8 byte limit before command text crosses the authenticated connection. */
|
|
2420
|
+
function commandTextFits(text) {
|
|
2421
|
+
return new TextEncoder().encode(text).length <= COMMAND_TEXT_LIMIT;
|
|
2422
|
+
}
|
|
2423
|
+
//#endregion
|
|
2424
|
+
//#region src/methods.ts
|
|
2425
|
+
const StatusSchema = z.object({
|
|
2426
|
+
state: z.enum([
|
|
2427
|
+
"disabled",
|
|
2428
|
+
"connecting",
|
|
2429
|
+
"connected",
|
|
2430
|
+
"needs-auth",
|
|
2431
|
+
"reconnecting",
|
|
2432
|
+
"failed"
|
|
2433
|
+
]),
|
|
2434
|
+
reason: z.string().optional()
|
|
2435
|
+
}).strict();
|
|
2436
|
+
/** Credential-free catalogue row used by owner frames and complete mutation receipts. */
|
|
2437
|
+
const ServerSummarySchema = z.object({
|
|
2438
|
+
id: z.string(),
|
|
2439
|
+
slug: z.string(),
|
|
2440
|
+
name: z.string(),
|
|
2441
|
+
transport: z.enum(["stdio", "http"]),
|
|
2442
|
+
enabled: z.boolean(),
|
|
2443
|
+
status: StatusSchema,
|
|
2444
|
+
agentIds: z.array(z.string())
|
|
2445
|
+
}).strict();
|
|
2446
|
+
/** One named input of a tool or a prompt, as a settings page lists it. */
|
|
2447
|
+
const ParameterSchema = z.object({
|
|
2448
|
+
name: z.string(),
|
|
2449
|
+
type: z.string().optional(),
|
|
2450
|
+
required: z.boolean(),
|
|
2451
|
+
description: z.string().optional()
|
|
2452
|
+
}).strict();
|
|
2453
|
+
const CatalogEntrySchema = z.object({
|
|
2454
|
+
name: z.string(),
|
|
2455
|
+
uri: z.string().optional(),
|
|
2456
|
+
description: z.string().optional(),
|
|
2457
|
+
mimeType: z.string().optional(),
|
|
2458
|
+
parameters: z.array(ParameterSchema).optional(),
|
|
2459
|
+
refused: z.string().optional()
|
|
2460
|
+
}).strict();
|
|
2461
|
+
const ServerDetailSchema = ServerSummarySchema.extend({
|
|
2462
|
+
description: z.string().optional(),
|
|
2463
|
+
config: z.union([StdioConfigSchema, HttpConfigSchema]),
|
|
2464
|
+
acknowledged: z.boolean(),
|
|
2465
|
+
catalog: z.object({
|
|
2466
|
+
tools: z.array(z.object({
|
|
2467
|
+
name: z.string(),
|
|
2468
|
+
mappedName: z.string(),
|
|
2469
|
+
description: z.string().optional(),
|
|
2470
|
+
parameters: z.array(ParameterSchema),
|
|
2471
|
+
refused: z.string().optional()
|
|
2472
|
+
}).strict()),
|
|
2473
|
+
resources: z.array(CatalogEntrySchema),
|
|
2474
|
+
prompts: z.array(CatalogEntrySchema)
|
|
2475
|
+
}).strict().nullable(),
|
|
2476
|
+
oauth: z.object({
|
|
2477
|
+
authorized: z.boolean(),
|
|
2478
|
+
expiresAt: z.number().optional()
|
|
2479
|
+
}).strict().nullable()
|
|
2480
|
+
}).strict();
|
|
2481
|
+
const Id = z.object({ id: z.string() }).strict();
|
|
2482
|
+
const Agent = z.object({ agentId: z.string().min(1) }).strict();
|
|
2483
|
+
const ServerList = z.object({ servers: z.array(ServerSummarySchema) }).strict();
|
|
2484
|
+
const Text = z.object({ text: z.string() }).strict();
|
|
2485
|
+
const Empty = z.object({}).strict();
|
|
2486
|
+
const PromptEntrySchema = z.object({
|
|
2487
|
+
serverId: z.string(),
|
|
2488
|
+
slug: z.string(),
|
|
2489
|
+
serverName: z.string(),
|
|
2490
|
+
name: z.string(),
|
|
2491
|
+
description: z.string().optional(),
|
|
2492
|
+
arguments: z.array(z.object({
|
|
2493
|
+
name: z.string(),
|
|
2494
|
+
description: z.string().optional(),
|
|
2495
|
+
required: z.boolean().optional()
|
|
2496
|
+
}).strict()).optional()
|
|
2497
|
+
}).strict();
|
|
2498
|
+
const ResourceEntrySchema = z.object({
|
|
2499
|
+
serverId: z.string(),
|
|
2500
|
+
serverName: z.string(),
|
|
2501
|
+
uri: z.string(),
|
|
2502
|
+
name: z.string().optional(),
|
|
2503
|
+
description: z.string().optional()
|
|
2504
|
+
}).strict();
|
|
2505
|
+
const TestResultSchema = z.union([z.object({
|
|
2506
|
+
ok: z.literal(true),
|
|
2507
|
+
tools: z.number(),
|
|
2508
|
+
resources: z.number(),
|
|
2509
|
+
prompts: z.number()
|
|
2510
|
+
}).strict(), z.object({
|
|
2511
|
+
ok: z.literal(false),
|
|
2512
|
+
reason: z.string()
|
|
2513
|
+
}).strict()]);
|
|
2514
|
+
const Reconciliation = z.strictObject({
|
|
2515
|
+
id: z.string(),
|
|
2516
|
+
state: z.enum([
|
|
2517
|
+
"pending",
|
|
2518
|
+
"completed",
|
|
2519
|
+
"failed"
|
|
2520
|
+
]),
|
|
2521
|
+
reason: z.string().optional()
|
|
2522
|
+
});
|
|
2523
|
+
const ReconciledServers = ServerList.extend({ reconciliation: z.array(Reconciliation) });
|
|
2524
|
+
const RemovedServers = ServerList.extend({ cleanup: z.array(Reconciliation) });
|
|
2525
|
+
z.union([operationResult(ReconciledServers), operationResult(RemovedServers)]);
|
|
2526
|
+
z.strictObject({
|
|
2527
|
+
serverIds: z.array(z.string()),
|
|
2528
|
+
revision: z.number(),
|
|
2529
|
+
contentHash: z.string()
|
|
2530
|
+
});
|
|
2531
|
+
/** The longest server-written description a page is sent. */
|
|
2532
|
+
const DESCRIPTION_LIMIT = 2048;
|
|
2533
|
+
/** The most inputs listed for one tool or prompt. */
|
|
2534
|
+
const PARAMETER_LIMIT = 64;
|
|
2535
|
+
/**
|
|
2536
|
+
* A tool's inputs read off its JSON Schema: the top-level properties, in the
|
|
2537
|
+
* order the server wrote them, each with its type, whether `required` names it
|
|
2538
|
+
* and its own description. Nothing deeper — a settings page answers what the
|
|
2539
|
+
* tool asks for, and the model is the one handed the whole schema.
|
|
2540
|
+
*/
|
|
2541
|
+
function schemaParameters(schema, shown) {
|
|
2542
|
+
const properties = schema?.properties;
|
|
2543
|
+
if (!properties || typeof properties !== "object") return [];
|
|
2544
|
+
const required = new Set(Array.isArray(schema?.required) ? schema.required.filter((name) => typeof name === "string") : []);
|
|
2545
|
+
return Object.entries(properties).slice(0, PARAMETER_LIMIT).map(([name, raw]) => {
|
|
2546
|
+
const property = raw && typeof raw === "object" ? raw : {};
|
|
2547
|
+
const kind = Array.isArray(property.type) ? property.type.filter((one) => typeof one === "string").join(" | ") : typeof property.type === "string" ? property.type : Array.isArray(property.enum) ? "enum" : void 0;
|
|
2548
|
+
const description = typeof property.description === "string" ? property.description.trim() : "";
|
|
2549
|
+
return {
|
|
2550
|
+
name,
|
|
2551
|
+
...kind ? { type: kind } : {},
|
|
2552
|
+
required: required.has(name),
|
|
2553
|
+
...description ? { description: shown(description) } : {}
|
|
2554
|
+
};
|
|
2555
|
+
});
|
|
2556
|
+
}
|
|
2557
|
+
/**
|
|
2558
|
+
* The plugin's wire methods and its two broadcast frames. Every result is
|
|
2559
|
+
* validated by the host against these schemas, and none carries a
|
|
2560
|
+
* credential value.
|
|
2561
|
+
*/
|
|
2562
|
+
function registerMethods(deps) {
|
|
2563
|
+
const { ctx, store, connections, tools, prompts, oauth } = deps;
|
|
2564
|
+
const serversChanged = ctx.client.registerFrame({
|
|
2565
|
+
name: "serversChanged",
|
|
2566
|
+
delivery: "broadcast",
|
|
2567
|
+
payload: ServerList
|
|
2568
|
+
});
|
|
2569
|
+
const selectionChanged = ctx.client.registerFrame({
|
|
2570
|
+
name: "selectionChanged",
|
|
2571
|
+
delivery: "broadcast",
|
|
2572
|
+
payload: Agent
|
|
2573
|
+
});
|
|
2574
|
+
const summary = (record) => {
|
|
2575
|
+
const status = connections.status(record.id);
|
|
2576
|
+
const secrets = status.reason ? secretValues(deps.secretsOf(record.id)) : [];
|
|
2577
|
+
return {
|
|
2578
|
+
id: record.id,
|
|
2579
|
+
slug: record.slug,
|
|
2580
|
+
name: record.name,
|
|
2581
|
+
transport: record.transport,
|
|
2582
|
+
enabled: record.enabled,
|
|
2583
|
+
status: status.reason ? {
|
|
2584
|
+
state: status.state,
|
|
2585
|
+
reason: redactReason(status.reason, secrets)
|
|
2586
|
+
} : { state: status.state },
|
|
2587
|
+
agentIds: store.agentsOf(record.id)
|
|
2588
|
+
};
|
|
2589
|
+
};
|
|
2590
|
+
const summaries = () => store.servers().map(summary);
|
|
2591
|
+
const require = (id) => {
|
|
2592
|
+
const record = store.server(id);
|
|
2593
|
+
if (!record) throw new Error("no such MCP server");
|
|
2594
|
+
return record;
|
|
2595
|
+
};
|
|
2596
|
+
const detail = (record) => {
|
|
2597
|
+
const snapshot = connections.snapshot(record.id);
|
|
2598
|
+
const secrets = secretValues(deps.secretsOf(record.id));
|
|
2599
|
+
const shown = (text) => redact(text, secrets).slice(0, DESCRIPTION_LIMIT);
|
|
2600
|
+
const described = (text) => text?.trim() ? { description: shown(text.trim()) } : {};
|
|
2601
|
+
const refusedPrompts = prompts.refusedPrompts(record.id, record.slug);
|
|
2602
|
+
let authorization = null;
|
|
2603
|
+
if (record.transport === "http" && record.config.auth === "oauth") {
|
|
2604
|
+
const { authorized, expiresAt } = oauth.status(record.id);
|
|
2605
|
+
authorization = {
|
|
2606
|
+
authorized,
|
|
2607
|
+
...expiresAt === void 0 ? {} : { expiresAt }
|
|
2608
|
+
};
|
|
2609
|
+
}
|
|
2610
|
+
return {
|
|
2611
|
+
...summary(record),
|
|
2612
|
+
...described(snapshot?.description),
|
|
2613
|
+
config: record.config,
|
|
2614
|
+
acknowledged: record.transport === "stdio" && record.acknowledgedAt !== null,
|
|
2615
|
+
catalog: snapshot ? {
|
|
2616
|
+
tools: tools.catalogTools(record.id, snapshot).map((tool, at) => {
|
|
2617
|
+
const source = snapshot.tools[at];
|
|
2618
|
+
return {
|
|
2619
|
+
...tool,
|
|
2620
|
+
...described(source?.description),
|
|
2621
|
+
parameters: schemaParameters(source?.inputSchema, shown)
|
|
2622
|
+
};
|
|
2623
|
+
}),
|
|
2624
|
+
resources: snapshot.resources.map((resource) => ({
|
|
2625
|
+
name: resource.name ?? resource.uri,
|
|
2626
|
+
uri: resource.uri,
|
|
2627
|
+
...described(resource.description),
|
|
2628
|
+
...resource.mimeType ? { mimeType: resource.mimeType } : {}
|
|
2629
|
+
})),
|
|
2630
|
+
prompts: snapshot.prompts.map((prompt) => {
|
|
2631
|
+
const reason = refusedPrompts.get(prompt.name);
|
|
2632
|
+
return {
|
|
2633
|
+
name: prompt.name,
|
|
2634
|
+
...described(prompt.description),
|
|
2635
|
+
parameters: (prompt.arguments ?? []).slice(0, PARAMETER_LIMIT).map((argument) => ({
|
|
2636
|
+
name: argument.name,
|
|
2637
|
+
required: argument.required === true,
|
|
2638
|
+
...argument.description ? { description: shown(argument.description) } : {}
|
|
2639
|
+
})),
|
|
2640
|
+
...reason ? { refused: reason } : {}
|
|
2641
|
+
};
|
|
2642
|
+
})
|
|
2643
|
+
} : null,
|
|
2644
|
+
oauth: authorization
|
|
2645
|
+
};
|
|
2646
|
+
};
|
|
2647
|
+
const announce = () => serversChanged.emit({ servers: summaries() });
|
|
2648
|
+
const management = {
|
|
2649
|
+
commands: deps.commands,
|
|
2650
|
+
agentConfig: deps.agentConfig,
|
|
2651
|
+
operations: ctx.services.get("owner-operations"),
|
|
2652
|
+
store,
|
|
2653
|
+
connections,
|
|
2654
|
+
tools,
|
|
2655
|
+
oauth,
|
|
2656
|
+
announce,
|
|
2657
|
+
selectionChanged: (agentId) => selectionChanged.emit({ agentId })
|
|
2658
|
+
};
|
|
2659
|
+
ctx.client.registerMethod({
|
|
2660
|
+
name: "commandParse",
|
|
2661
|
+
params: z.object({ text: z.string().min(1).refine(commandTextFits, "command-text-too-large") }).strict(),
|
|
2662
|
+
result: z.object({
|
|
2663
|
+
file: z.string().min(1),
|
|
2664
|
+
args: z.array(z.string()),
|
|
2665
|
+
syntax: z.enum(["posix-argv", "windows-argv"])
|
|
2666
|
+
}).strict(),
|
|
2667
|
+
handle: ({ text }) => parseCommandPaste(text, deps.commands)
|
|
2668
|
+
});
|
|
2669
|
+
ctx.client.registerMethod({
|
|
2670
|
+
name: "listServers",
|
|
2671
|
+
params: Empty,
|
|
2672
|
+
result: ServerList,
|
|
2673
|
+
handle: () => ({ servers: summaries() })
|
|
2674
|
+
});
|
|
2675
|
+
ctx.client.registerMethod({
|
|
2676
|
+
name: "getServers",
|
|
2677
|
+
params: batchInput({
|
|
2678
|
+
ids: z.array(z.string().min(1)).min(1).max(64),
|
|
2679
|
+
...queryBudgets
|
|
2680
|
+
}, "ids"),
|
|
2681
|
+
result: batchResult(ServerDetailSchema, z.string()),
|
|
2682
|
+
handle: (input) => settle(input.ids, (id) => detail(require(id)), input, (error, id) => redactReason(error instanceof Error ? error.message : "Operation failed", secretValues(deps.secretsOf(id))))
|
|
2683
|
+
});
|
|
2684
|
+
ctx.client.registerMethod({
|
|
2685
|
+
name: "saveServer",
|
|
2686
|
+
params: SaveServerSchema,
|
|
2687
|
+
result: ServerDetailSchema,
|
|
2688
|
+
async handle(input) {
|
|
2689
|
+
return detail(await saveServer(management, input));
|
|
2690
|
+
}
|
|
2691
|
+
});
|
|
2692
|
+
const identity = z.string().min(1);
|
|
2693
|
+
const ids = (max = 64) => z.array(identity).min(1).max(max);
|
|
2694
|
+
const reconciled = ReconciledServers;
|
|
2695
|
+
const removed = RemovedServers;
|
|
2696
|
+
const operation = (method, input) => ({
|
|
2697
|
+
scope: "settings",
|
|
2698
|
+
method,
|
|
2699
|
+
operationId: input.operationId,
|
|
2700
|
+
params: input
|
|
2701
|
+
});
|
|
2702
|
+
const operations = management.operations;
|
|
2703
|
+
const effects = async (intent, receipt, serverIds, remove = false) => {
|
|
2704
|
+
if (receipt.operationState === "admitted") return receipt;
|
|
2705
|
+
const cleanup = (await connections.collection(serverIds, () => settle(serverIds, async (id) => {
|
|
2706
|
+
if (remove) {
|
|
2707
|
+
oauth.invalidate(id);
|
|
2708
|
+
tools.forget(id);
|
|
2709
|
+
}
|
|
2710
|
+
await connections.reconcile(id);
|
|
2711
|
+
return await connections.cleanup(id);
|
|
2712
|
+
}), false)).results.flatMap((item) => item.ok ? item.value.state === "failed" ? [{
|
|
2713
|
+
code: item.target,
|
|
2714
|
+
message: item.value.reason ?? "cleanup-failed"
|
|
2715
|
+
}] : [] : [{
|
|
2716
|
+
code: item.target,
|
|
2717
|
+
message: item.error.message
|
|
2718
|
+
}]);
|
|
2719
|
+
announce();
|
|
2720
|
+
return cleanup.length ? operations.markCleanupPending(intent, cleanup) : receipt;
|
|
2721
|
+
};
|
|
2722
|
+
const replayCleanup = async (intent, receipt) => {
|
|
2723
|
+
if (receipt.operationState !== "cleanup-pending") return receipt;
|
|
2724
|
+
const ids = [...new Set(receipt.cleanup.map((item) => item.code))];
|
|
2725
|
+
const failed = (await connections.collection(ids, () => settle(ids, (id) => connections.cleanup(id)), false)).results.flatMap((item) => item.ok ? item.value.state === "failed" ? [{
|
|
2726
|
+
code: item.target,
|
|
2727
|
+
message: item.value.reason ?? "cleanup-failed"
|
|
2728
|
+
}] : [] : [{
|
|
2729
|
+
code: item.target,
|
|
2730
|
+
message: item.error.message
|
|
2731
|
+
}]);
|
|
2732
|
+
return failed.length ? operations.markCleanupPending(intent, failed) : operations.settleCleanup(intent);
|
|
2733
|
+
};
|
|
2734
|
+
ctx.client.registerMethod({
|
|
2735
|
+
name: "removeServers",
|
|
2736
|
+
params: batchInput({
|
|
2737
|
+
operationId: z.uuid(),
|
|
2738
|
+
ids: ids()
|
|
2739
|
+
}, "ids"),
|
|
2740
|
+
result: operationResult(removed),
|
|
2741
|
+
async handle(input) {
|
|
2742
|
+
input = {
|
|
2743
|
+
...input,
|
|
2744
|
+
ids: [...new Set(input.ids)]
|
|
2745
|
+
};
|
|
2746
|
+
const intent = operation("removeServers", input);
|
|
2747
|
+
const replay = operations.lookup(intent);
|
|
2748
|
+
if (replay) return replayCleanup(intent, replay);
|
|
2749
|
+
input.ids.forEach(require);
|
|
2750
|
+
const agents = [...new Set(input.ids.flatMap((id) => store.agentsOf(id)))];
|
|
2751
|
+
const prepared = [];
|
|
2752
|
+
let committed = false;
|
|
2753
|
+
try {
|
|
2754
|
+
for (const agent of agents) prepared.push(deps.agentConfig.prepare(agent, { extensionData: { [ctx.pluginName]: { mcpServerIds: store.agentServers(agent).filter((id) => !input.ids.includes(id)) } } }));
|
|
2755
|
+
const receipt = deps.selfWrite(() => operations.atomic(intent, (scope) => {
|
|
2756
|
+
for (const row of prepared) {
|
|
2757
|
+
if (row.connectionIdentity !== scope.connectionIdentity) throw new Error("foreign Agent transaction participant");
|
|
2758
|
+
row.assertCurrent();
|
|
2759
|
+
}
|
|
2760
|
+
scope.afterRollback(() => {
|
|
2761
|
+
for (const row of prepared.slice().reverse()) row.abort();
|
|
2762
|
+
});
|
|
2763
|
+
scope.afterCommit(() => {
|
|
2764
|
+
for (const row of prepared) row.settle();
|
|
2765
|
+
});
|
|
2766
|
+
for (const row of prepared) row.apply();
|
|
2767
|
+
for (const id of input.ids) store.removeServer(id);
|
|
2768
|
+
deps.credentials.clearMany(input.ids.map((id) => ({
|
|
2769
|
+
scope: id,
|
|
2770
|
+
mode: "all"
|
|
2771
|
+
})), scope);
|
|
2772
|
+
return {
|
|
2773
|
+
servers: summaries(),
|
|
2774
|
+
cleanup: input.ids.map((id) => ({
|
|
2775
|
+
id,
|
|
2776
|
+
state: "pending"
|
|
2777
|
+
}))
|
|
2778
|
+
};
|
|
2779
|
+
}));
|
|
2780
|
+
committed = receipt.operationState !== "admitted";
|
|
2781
|
+
return await effects(intent, receipt, input.ids, true);
|
|
2782
|
+
} catch (error) {
|
|
2783
|
+
if (!committed) for (const row of prepared.slice().reverse()) try {
|
|
2784
|
+
row.abort();
|
|
2785
|
+
} catch {}
|
|
2786
|
+
throw error;
|
|
2787
|
+
}
|
|
2788
|
+
}
|
|
2789
|
+
});
|
|
2790
|
+
ctx.client.registerMethod({
|
|
2791
|
+
name: "setServersEnabled",
|
|
2792
|
+
params: batchInput({
|
|
2793
|
+
operationId: z.uuid(),
|
|
2794
|
+
ids: ids(),
|
|
2795
|
+
enabled: z.boolean()
|
|
2796
|
+
}, "ids"),
|
|
2797
|
+
result: operationResult(reconciled),
|
|
2798
|
+
async handle(input) {
|
|
2799
|
+
input = {
|
|
2800
|
+
...input,
|
|
2801
|
+
ids: [...new Set(input.ids)]
|
|
2802
|
+
};
|
|
2803
|
+
const intent = operation("setServersEnabled", input);
|
|
2804
|
+
const replay = operations.lookup(intent);
|
|
2805
|
+
if (replay) return replayCleanup(intent, replay);
|
|
2806
|
+
const receipt = operations.atomic(intent, () => {
|
|
2807
|
+
input.ids.forEach(require);
|
|
2808
|
+
for (const id of input.ids) store.setEnabled(id, input.enabled);
|
|
2809
|
+
return {
|
|
2810
|
+
servers: summaries(),
|
|
2811
|
+
reconciliation: input.ids.map((id) => ({
|
|
2812
|
+
id,
|
|
2813
|
+
state: "pending"
|
|
2814
|
+
}))
|
|
2815
|
+
};
|
|
2816
|
+
});
|
|
2817
|
+
return effects(intent, receipt, input.ids);
|
|
2818
|
+
}
|
|
2819
|
+
});
|
|
2820
|
+
ctx.client.registerMethod({
|
|
2821
|
+
name: "retryServers",
|
|
2822
|
+
params: batchInput({ ids: ids(32) }, "ids"),
|
|
2823
|
+
result: batchResult(ServerSummarySchema, z.string()),
|
|
2824
|
+
async handle(input) {
|
|
2825
|
+
const result = await connections.collection(input.ids, () => settle(input.ids, async (id) => {
|
|
2826
|
+
require(id);
|
|
2827
|
+
await connections.reconcile(id, { keepSnapshot: true });
|
|
2828
|
+
const cleanup = await connections.cleanup(id);
|
|
2829
|
+
if (cleanup.state === "failed") throw new Error(cleanup.reason);
|
|
2830
|
+
return summary(require(id));
|
|
2831
|
+
}), false);
|
|
2832
|
+
announce();
|
|
2833
|
+
return result;
|
|
2834
|
+
}
|
|
2835
|
+
});
|
|
2836
|
+
ctx.client.registerMethod({
|
|
2837
|
+
name: "testServers",
|
|
2838
|
+
params: batchInput({
|
|
2839
|
+
ids: ids(32),
|
|
2840
|
+
...queryBudgets
|
|
2841
|
+
}, "ids"),
|
|
2842
|
+
result: batchResult(TestResultSchema, z.string()),
|
|
2843
|
+
handle: (input) => connections.collection(input.ids, () => settle(input.ids, async (id) => {
|
|
2844
|
+
require(id);
|
|
2845
|
+
return await connections.test(id);
|
|
2846
|
+
}, input), false)
|
|
2847
|
+
});
|
|
2848
|
+
ctx.client.registerMethod({
|
|
2849
|
+
name: "authorize",
|
|
2850
|
+
params: Id,
|
|
2851
|
+
result: z.object({ url: z.string() }).strict(),
|
|
2852
|
+
async handle({ id }) {
|
|
2853
|
+
const record = require(id);
|
|
2854
|
+
if (record.transport !== "http" || record.config.auth !== "oauth") throw new Error("this server does not use OAuth");
|
|
2855
|
+
return await oauth.authorize(id, record.config.url, (outcome) => {
|
|
2856
|
+
if (outcome.ok) connections.reconcile(id);
|
|
2857
|
+
else connections.needsAuth(id, outcome.reason);
|
|
2858
|
+
announce();
|
|
2859
|
+
});
|
|
2860
|
+
}
|
|
2861
|
+
});
|
|
2862
|
+
ctx.client.registerMethod({
|
|
2863
|
+
name: "cancelAuthorize",
|
|
2864
|
+
params: Id,
|
|
2865
|
+
result: Empty,
|
|
2866
|
+
handle({ id }) {
|
|
2867
|
+
oauth.cancel(id);
|
|
2868
|
+
return {};
|
|
2869
|
+
}
|
|
2870
|
+
});
|
|
2871
|
+
ctx.client.registerMethod({
|
|
2872
|
+
name: "signOutServers",
|
|
2873
|
+
params: batchInput({
|
|
2874
|
+
operationId: z.uuid(),
|
|
2875
|
+
ids: ids()
|
|
2876
|
+
}, "ids"),
|
|
2877
|
+
result: operationResult(reconciled),
|
|
2878
|
+
async handle(input) {
|
|
2879
|
+
input = {
|
|
2880
|
+
...input,
|
|
2881
|
+
ids: [...new Set(input.ids)]
|
|
2882
|
+
};
|
|
2883
|
+
const intent = operation("signOutServers", input);
|
|
2884
|
+
const replay = operations.lookup(intent);
|
|
2885
|
+
if (replay) return replayCleanup(intent, replay);
|
|
2886
|
+
const receipt = deps.selfWrite(() => operations.atomic(intent, (scope) => {
|
|
2887
|
+
input.ids.forEach(require);
|
|
2888
|
+
deps.credentials.clearMany(input.ids.map((id) => ({
|
|
2889
|
+
scope: id,
|
|
2890
|
+
mode: "names",
|
|
2891
|
+
names: ["oauth.tokens", "oauth.client"]
|
|
2892
|
+
})), scope);
|
|
2893
|
+
return {
|
|
2894
|
+
servers: summaries(),
|
|
2895
|
+
reconciliation: input.ids.map((id) => ({
|
|
2896
|
+
id,
|
|
2897
|
+
state: "pending"
|
|
2898
|
+
}))
|
|
2899
|
+
};
|
|
2900
|
+
}));
|
|
2901
|
+
for (const id of input.ids) oauth.invalidate(id);
|
|
2902
|
+
return effects(intent, receipt, input.ids);
|
|
2903
|
+
}
|
|
2904
|
+
});
|
|
2905
|
+
ctx.client.registerMethod({
|
|
2906
|
+
name: "agentServerSets",
|
|
2907
|
+
params: batchInput({
|
|
2908
|
+
agentIds: ids(),
|
|
2909
|
+
...queryBudgets
|
|
2910
|
+
}, "agentIds"),
|
|
2911
|
+
result: batchResult(z.strictObject({
|
|
2912
|
+
serverIds: z.array(z.string()),
|
|
2913
|
+
revision: z.number(),
|
|
2914
|
+
contentHash: z.string()
|
|
2915
|
+
}), z.string()),
|
|
2916
|
+
handle: (input) => settle(input.agentIds, (agentId) => ({
|
|
2917
|
+
serverIds: store.agentServers(agentId),
|
|
2918
|
+
...deps.agentConfig.state(agentId)
|
|
2919
|
+
}), input)
|
|
2920
|
+
});
|
|
2921
|
+
ctx.client.registerMethod({
|
|
2922
|
+
name: "setAgentServers",
|
|
2923
|
+
params: z.object({
|
|
2924
|
+
agentId: z.string().min(1),
|
|
2925
|
+
serverIds: z.array(z.string()),
|
|
2926
|
+
expectedRevision: z.number().int().positive(),
|
|
2927
|
+
expectedContentHash: z.string().regex(/^[a-f0-9]{64}$/)
|
|
2928
|
+
}).strict(),
|
|
2929
|
+
result: z.object({
|
|
2930
|
+
serverIds: z.array(z.string()),
|
|
2931
|
+
revision: z.number(),
|
|
2932
|
+
contentHash: z.string()
|
|
2933
|
+
}).strict(),
|
|
2934
|
+
async handle({ agentId, serverIds, expectedRevision, expectedContentHash }) {
|
|
2935
|
+
deps.agentConfig.check(agentId, expectedRevision, expectedContentHash);
|
|
2936
|
+
for (const id of serverIds) require(id);
|
|
2937
|
+
deps.agentConfig.save([agentId], () => store.setAgentServers(agentId, serverIds));
|
|
2938
|
+
selectionChanged.emit({ agentId });
|
|
2939
|
+
announce();
|
|
2940
|
+
return {
|
|
2941
|
+
serverIds: store.agentServers(agentId),
|
|
2942
|
+
...deps.agentConfig.state(agentId)
|
|
2943
|
+
};
|
|
2944
|
+
}
|
|
2945
|
+
});
|
|
2946
|
+
ctx.client.registerMethod({
|
|
2947
|
+
name: "prompts",
|
|
2948
|
+
params: Agent,
|
|
2949
|
+
result: z.object({ prompts: z.array(PromptEntrySchema) }).strict(),
|
|
2950
|
+
handle: ({ agentId }) => ({ prompts: prompts.list(agentId) })
|
|
2951
|
+
});
|
|
2952
|
+
ctx.client.registerMethod({
|
|
2953
|
+
name: "getPrompt",
|
|
2954
|
+
params: z.object({
|
|
2955
|
+
agentId: z.string().min(1),
|
|
2956
|
+
serverId: z.string(),
|
|
2957
|
+
name: z.string(),
|
|
2958
|
+
args: z.record(z.string(), z.string())
|
|
2959
|
+
}).strict(),
|
|
2960
|
+
result: Text,
|
|
2961
|
+
handle: (input, call) => prompts.get(input, call.signal)
|
|
2962
|
+
});
|
|
2963
|
+
ctx.client.registerMethod({
|
|
2964
|
+
name: "resources",
|
|
2965
|
+
params: z.object({
|
|
2966
|
+
agentId: z.string().min(1),
|
|
2967
|
+
query: z.string()
|
|
2968
|
+
}).strict(),
|
|
2969
|
+
result: z.object({ resources: z.array(ResourceEntrySchema) }).strict(),
|
|
2970
|
+
handle: ({ agentId, query }) => ({ resources: prompts.resources(agentId, query) })
|
|
2971
|
+
});
|
|
2972
|
+
const resourceMember = z.strictObject({
|
|
2973
|
+
serverId: z.string().min(1),
|
|
2974
|
+
uri: z.string().min(1),
|
|
2975
|
+
maxBytes: z.number().int().min(1).max(1048576)
|
|
2976
|
+
});
|
|
2977
|
+
ctx.client.registerMethod({
|
|
2978
|
+
name: "readResources",
|
|
2979
|
+
params: resourceInput({ agentId: z.string().min(1) }, resourceMember),
|
|
2980
|
+
result: batchResult(Text, z.strictObject({
|
|
2981
|
+
serverId: z.string(),
|
|
2982
|
+
uri: z.string()
|
|
2983
|
+
})),
|
|
2984
|
+
handle: (input, call) => settle(input.items.map((item) => ({
|
|
2985
|
+
serverId: item.serverId,
|
|
2986
|
+
uri: item.uri
|
|
2987
|
+
})), (_target, index) => prompts.read({
|
|
2988
|
+
agentId: input.agentId,
|
|
2989
|
+
...input.items[index]
|
|
2990
|
+
}, call.signal), void 0, (error, target) => redactReason(error instanceof Error ? error.message : "Operation failed", secretValues(deps.secretsOf(target.serverId))))
|
|
2991
|
+
});
|
|
2992
|
+
return {
|
|
2993
|
+
announce,
|
|
2994
|
+
management
|
|
2995
|
+
};
|
|
2996
|
+
}
|
|
2997
|
+
/** The server needs a person to authorize it (again). */
|
|
2998
|
+
var NeedsAuthorizationError = class extends Error {
|
|
2999
|
+
constructor(message = "authorization required") {
|
|
3000
|
+
super(message);
|
|
3001
|
+
this.name = "NeedsAuthorizationError";
|
|
3002
|
+
}
|
|
3003
|
+
};
|
|
3004
|
+
const CALLBACK_PATH = "/callback";
|
|
3005
|
+
function clientMetadata(redirectUrl) {
|
|
3006
|
+
return {
|
|
3007
|
+
client_name: "YaoGuang",
|
|
3008
|
+
redirect_uris: [redirectUrl],
|
|
3009
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
3010
|
+
response_types: ["code"],
|
|
3011
|
+
token_endpoint_auth_method: "none"
|
|
3012
|
+
};
|
|
3013
|
+
}
|
|
3014
|
+
function page(title, body) {
|
|
3015
|
+
return `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title></head><body style="font-family:system-ui;margin:3rem"><p>${body}</p><script>setTimeout(function(){window.close()},300)<\/script></body></html>`;
|
|
3016
|
+
}
|
|
3017
|
+
function respond(res, status, title, body) {
|
|
3018
|
+
res.writeHead(status, {
|
|
3019
|
+
"content-type": "text/html; charset=utf-8",
|
|
3020
|
+
"cache-control": "no-store"
|
|
3021
|
+
});
|
|
3022
|
+
res.end(page(title, body));
|
|
3023
|
+
}
|
|
3024
|
+
function listen(port) {
|
|
3025
|
+
return new Promise((resolve, reject) => {
|
|
3026
|
+
const server = createServer();
|
|
3027
|
+
server.once("error", reject);
|
|
3028
|
+
server.listen(port, "127.0.0.1", () => {
|
|
3029
|
+
server.off("error", reject);
|
|
3030
|
+
resolve(server);
|
|
3031
|
+
});
|
|
3032
|
+
});
|
|
3033
|
+
}
|
|
3034
|
+
function portOf(uri) {
|
|
3035
|
+
if (typeof uri !== "string") return void 0;
|
|
3036
|
+
try {
|
|
3037
|
+
const url = new URL(uri);
|
|
3038
|
+
return url.hostname === "127.0.0.1" && url.port !== "" ? Number(url.port) : void 0;
|
|
3039
|
+
} catch {
|
|
3040
|
+
return;
|
|
3041
|
+
}
|
|
3042
|
+
}
|
|
3043
|
+
/**
|
|
3044
|
+
* OAuth for remote servers: an `OAuthClientProvider` over the credential
|
|
3045
|
+
* manager (`oauth.tokens`, `oauth.client`), the one-shot loopback callback,
|
|
3046
|
+
* and a refresh made ahead of expiry, shared by concurrent requests.
|
|
3047
|
+
*
|
|
3048
|
+
* Every authorization and every refresh belongs to a generation per server;
|
|
3049
|
+
* signing out, reauthorizing, changing the endpoint and deleting bump it, and
|
|
3050
|
+
* a late result from an older generation is dropped before it writes.
|
|
3051
|
+
*/
|
|
3052
|
+
function createOAuth(deps) {
|
|
3053
|
+
const now = deps.now ?? Date.now;
|
|
3054
|
+
const timeoutMs = deps.timeoutMs ?? 3e5;
|
|
3055
|
+
const flows = /* @__PURE__ */ new Map();
|
|
3056
|
+
const refreshes = /* @__PURE__ */ new Map();
|
|
3057
|
+
const discovery = /* @__PURE__ */ new Map();
|
|
3058
|
+
const generations = /* @__PURE__ */ new Map();
|
|
3059
|
+
const gen = (serverId) => generations.get(serverId) ?? 0;
|
|
3060
|
+
const readJson = (serverId, name) => {
|
|
3061
|
+
const raw = deps.credentials.get(serverId, name);
|
|
3062
|
+
if (raw === void 0) return void 0;
|
|
3063
|
+
try {
|
|
3064
|
+
return JSON.parse(raw);
|
|
3065
|
+
} catch {
|
|
3066
|
+
return;
|
|
3067
|
+
}
|
|
3068
|
+
};
|
|
3069
|
+
const readTokens = (serverId) => readJson(serverId, OAUTH_TOKENS);
|
|
3070
|
+
/**
|
|
3071
|
+
* Token documents a refresh replaced, newest last and at most
|
|
3072
|
+
* `REPLACED_KEPT` per server. A request already sent may still carry one,
|
|
3073
|
+
* and a server may echo it after the refresh, so redaction keeps checking
|
|
3074
|
+
* them until the tokens are cleared.
|
|
3075
|
+
*/
|
|
3076
|
+
const replaced = /* @__PURE__ */ new Map();
|
|
3077
|
+
const remember = (serverId) => {
|
|
3078
|
+
let raw;
|
|
3079
|
+
try {
|
|
3080
|
+
raw = deps.credentials.get(serverId, OAUTH_TOKENS);
|
|
3081
|
+
} catch {
|
|
3082
|
+
raw = void 0;
|
|
3083
|
+
}
|
|
3084
|
+
if (raw === void 0) return;
|
|
3085
|
+
const kept = [...replaced.get(serverId) ?? [], raw].slice(-4);
|
|
3086
|
+
replaced.set(serverId, kept);
|
|
3087
|
+
};
|
|
3088
|
+
const readClient = (serverId) => readJson(serverId, OAUTH_CLIENT);
|
|
3089
|
+
const writeTokens = (serverId, generation, tokens) => {
|
|
3090
|
+
if (generation !== gen(serverId)) throw new Error("authorization was superseded");
|
|
3091
|
+
remember(serverId);
|
|
3092
|
+
const stored = {
|
|
3093
|
+
...tokens,
|
|
3094
|
+
...tokens.expires_in === void 0 ? {} : { expires_at: now() + tokens.expires_in * 1e3 }
|
|
3095
|
+
};
|
|
3096
|
+
deps.selfWrite(() => deps.credentials.setMany(serverId, [{
|
|
3097
|
+
name: OAUTH_TOKENS,
|
|
3098
|
+
value: JSON.stringify(stored)
|
|
3099
|
+
}]));
|
|
3100
|
+
return stored;
|
|
3101
|
+
};
|
|
3102
|
+
const writeClient = (serverId, generation, info) => {
|
|
3103
|
+
if (generation !== gen(serverId)) throw new Error("authorization was superseded");
|
|
3104
|
+
deps.selfWrite(() => deps.credentials.setMany(serverId, [{
|
|
3105
|
+
name: OAUTH_CLIENT,
|
|
3106
|
+
value: JSON.stringify(info)
|
|
3107
|
+
}]));
|
|
3108
|
+
};
|
|
3109
|
+
const clear = (serverId, name) => {
|
|
3110
|
+
const names = name === void 0 ? [OAUTH_TOKENS, OAUTH_CLIENT] : [name];
|
|
3111
|
+
if (names.includes("oauth.tokens")) replaced.delete(serverId);
|
|
3112
|
+
deps.selfWrite(() => deps.credentials.clearMany([{
|
|
3113
|
+
scope: serverId,
|
|
3114
|
+
mode: "names",
|
|
3115
|
+
names
|
|
3116
|
+
}]));
|
|
3117
|
+
};
|
|
3118
|
+
const invalidateScope = (serverId, scope, flow) => {
|
|
3119
|
+
if (scope === "all" || scope === "tokens") clear(serverId, OAUTH_TOKENS);
|
|
3120
|
+
if (scope === "all" || scope === "client") clear(serverId, OAUTH_CLIENT);
|
|
3121
|
+
if (scope === "all" || scope === "discovery") discovery.delete(serverId);
|
|
3122
|
+
if ((scope === "all" || scope === "verifier") && flow) flow.verifier = void 0;
|
|
3123
|
+
};
|
|
3124
|
+
const strip = ({ expires_at: _expiresAt, ...tokens }) => tokens;
|
|
3125
|
+
/** One refresh per server at a time; concurrent callers share it. */
|
|
3126
|
+
const refresh = (serverId, serverUrl, current) => {
|
|
3127
|
+
const running = refreshes.get(serverId);
|
|
3128
|
+
if (running) return running;
|
|
3129
|
+
const generation = gen(serverId);
|
|
3130
|
+
const work = (async () => {
|
|
3131
|
+
const client = readClient(serverId);
|
|
3132
|
+
if (!client || !current.refresh_token) throw new NeedsAuthorizationError();
|
|
3133
|
+
let info = discovery.get(serverId);
|
|
3134
|
+
if (!info?.authorizationServerUrl) {
|
|
3135
|
+
info = await discoverOAuthServerInfo(serverUrl, { fetchFn: deps.fetch });
|
|
3136
|
+
discovery.set(serverId, info);
|
|
3137
|
+
}
|
|
3138
|
+
const selected = await selectResourceURL(serverUrl, {}, info.resourceMetadata);
|
|
3139
|
+
const resource = selected && info.resourceMetadata ? info.resourceMetadata.resource : selected;
|
|
3140
|
+
const tokens = await refreshAuthorization(info.authorizationServerUrl, {
|
|
3141
|
+
...info.authorizationServerMetadata ? { metadata: info.authorizationServerMetadata } : {},
|
|
3142
|
+
clientInformation: client,
|
|
3143
|
+
refreshToken: current.refresh_token,
|
|
3144
|
+
...resource === void 0 ? {} : { resource },
|
|
3145
|
+
fetchFn: deps.fetch
|
|
3146
|
+
});
|
|
3147
|
+
return writeTokens(serverId, generation, tokens);
|
|
3148
|
+
})().finally(() => refreshes.delete(serverId));
|
|
3149
|
+
refreshes.set(serverId, work);
|
|
3150
|
+
return work;
|
|
3151
|
+
};
|
|
3152
|
+
const finish = (serverId, flow, outcome) => {
|
|
3153
|
+
if (flow.settled) return;
|
|
3154
|
+
flow.settled = true;
|
|
3155
|
+
if (flow.timer) clearTimeout(flow.timer);
|
|
3156
|
+
flow.server.close();
|
|
3157
|
+
flow.server.closeAllConnections?.();
|
|
3158
|
+
if (flows.get(serverId) === flow) flows.delete(serverId);
|
|
3159
|
+
if (flow.gen === gen(serverId)) flow.done(outcome);
|
|
3160
|
+
};
|
|
3161
|
+
/** Drops every authorization and refresh in progress for a server. */
|
|
3162
|
+
const invalidate = (serverId) => {
|
|
3163
|
+
generations.set(serverId, gen(serverId) + 1);
|
|
3164
|
+
discovery.delete(serverId);
|
|
3165
|
+
const flow = flows.get(serverId);
|
|
3166
|
+
if (flow) finish(serverId, flow, {
|
|
3167
|
+
ok: false,
|
|
3168
|
+
reason: "authorization was cancelled"
|
|
3169
|
+
});
|
|
3170
|
+
};
|
|
3171
|
+
return {
|
|
3172
|
+
/** The current generation; a caller compares it after an await. */
|
|
3173
|
+
generation: gen,
|
|
3174
|
+
invalidate,
|
|
3175
|
+
/** Whether tokens are stored, and when the access token expires. */
|
|
3176
|
+
status(serverId) {
|
|
3177
|
+
let tokens;
|
|
3178
|
+
try {
|
|
3179
|
+
tokens = readTokens(serverId);
|
|
3180
|
+
} catch {
|
|
3181
|
+
tokens = void 0;
|
|
3182
|
+
}
|
|
3183
|
+
return {
|
|
3184
|
+
authorized: tokens !== void 0,
|
|
3185
|
+
...tokens?.expires_at === void 0 ? {} : { expiresAt: tokens.expires_at },
|
|
3186
|
+
pending: flows.has(serverId)
|
|
3187
|
+
};
|
|
3188
|
+
},
|
|
3189
|
+
hasTokens(serverId) {
|
|
3190
|
+
return readTokens(serverId) !== void 0;
|
|
3191
|
+
},
|
|
3192
|
+
/** Clears this server's tokens and client registration. */
|
|
3193
|
+
signOut(serverId) {
|
|
3194
|
+
invalidate(serverId);
|
|
3195
|
+
clear(serverId);
|
|
3196
|
+
},
|
|
3197
|
+
/** The raw credential values a connection's requests may carry, for
|
|
3198
|
+
* redaction: the stored ones and the token documents a refresh replaced. */
|
|
3199
|
+
secrets(serverId) {
|
|
3200
|
+
const read = (name) => {
|
|
3201
|
+
try {
|
|
3202
|
+
return deps.credentials.get(serverId, name);
|
|
3203
|
+
} catch {
|
|
3204
|
+
return;
|
|
3205
|
+
}
|
|
3206
|
+
};
|
|
3207
|
+
return [
|
|
3208
|
+
read(OAUTH_TOKENS),
|
|
3209
|
+
read(OAUTH_CLIENT),
|
|
3210
|
+
...replaced.get(serverId) ?? []
|
|
3211
|
+
];
|
|
3212
|
+
},
|
|
3213
|
+
/**
|
|
3214
|
+
* The provider a connection uses. It never opens an authorization: when the
|
|
3215
|
+
* endpoint asks for one, the SDK's request fails and the server reads as
|
|
3216
|
+
* needing authorization. Its `tokens()` refreshes a token expiring within
|
|
3217
|
+
* a minute before handing it out.
|
|
3218
|
+
*/
|
|
3219
|
+
connectionProvider(serverId, serverUrl) {
|
|
3220
|
+
const generation = gen(serverId);
|
|
3221
|
+
const recorded = () => readClient(serverId)?.redirect_uris?.[0] ?? "http://127.0.0.1/callback";
|
|
3222
|
+
return {
|
|
3223
|
+
get redirectUrl() {
|
|
3224
|
+
return recorded();
|
|
3225
|
+
},
|
|
3226
|
+
get clientMetadata() {
|
|
3227
|
+
return clientMetadata(recorded());
|
|
3228
|
+
},
|
|
3229
|
+
clientInformation: () => readClient(serverId),
|
|
3230
|
+
saveClientInformation() {
|
|
3231
|
+
throw new NeedsAuthorizationError();
|
|
3232
|
+
},
|
|
3233
|
+
async tokens() {
|
|
3234
|
+
const stored = readTokens(serverId);
|
|
3235
|
+
if (!stored) return void 0;
|
|
3236
|
+
if (stored.expires_at === void 0 || !stored.refresh_token || stored.expires_at - now() > 6e4) return strip(stored);
|
|
3237
|
+
try {
|
|
3238
|
+
return strip(await refresh(serverId, serverUrl, stored));
|
|
3239
|
+
} catch (error) {
|
|
3240
|
+
if (error instanceof NeedsAuthorizationError) throw error;
|
|
3241
|
+
if (error instanceof OAuthError && !(error instanceof ServerError)) throw new NeedsAuthorizationError(`token refresh was refused: ${error.errorCode}`);
|
|
3242
|
+
deps.log.emit({
|
|
3243
|
+
level: "warn",
|
|
3244
|
+
event: "plugin.event",
|
|
3245
|
+
fields: { localCode: "TOKEN_REFRESH_FOR_SERVER" }
|
|
3246
|
+
});
|
|
3247
|
+
return strip(stored);
|
|
3248
|
+
}
|
|
3249
|
+
},
|
|
3250
|
+
saveTokens(tokens) {
|
|
3251
|
+
writeTokens(serverId, generation, tokens);
|
|
3252
|
+
},
|
|
3253
|
+
redirectToAuthorization() {},
|
|
3254
|
+
saveCodeVerifier() {},
|
|
3255
|
+
codeVerifier() {
|
|
3256
|
+
throw new NeedsAuthorizationError();
|
|
3257
|
+
},
|
|
3258
|
+
invalidateCredentials(scope) {
|
|
3259
|
+
if (generation === gen(serverId)) invalidateScope(serverId, scope);
|
|
3260
|
+
},
|
|
3261
|
+
saveDiscoveryState(state) {
|
|
3262
|
+
discovery.set(serverId, state);
|
|
3263
|
+
},
|
|
3264
|
+
discoveryState: () => discovery.get(serverId)
|
|
3265
|
+
};
|
|
3266
|
+
},
|
|
3267
|
+
/**
|
|
3268
|
+
* Starts an authorization: listens once on a loopback port, registers a
|
|
3269
|
+
* client when needed (again when the recorded redirect port cannot be
|
|
3270
|
+
* bound), and returns the authorization URL a page opens. `done` is called
|
|
3271
|
+
* once, unless a newer generation replaced this one.
|
|
3272
|
+
*/
|
|
3273
|
+
async authorize(serverId, serverUrl, done) {
|
|
3274
|
+
invalidate(serverId);
|
|
3275
|
+
const generation = gen(serverId);
|
|
3276
|
+
const recorded = readClient(serverId);
|
|
3277
|
+
const recordedPort = portOf(recorded?.redirect_uris?.[0]);
|
|
3278
|
+
let server;
|
|
3279
|
+
try {
|
|
3280
|
+
server = await listen(recordedPort ?? 0);
|
|
3281
|
+
} catch {
|
|
3282
|
+
server = await listen(0);
|
|
3283
|
+
}
|
|
3284
|
+
const address = server.address();
|
|
3285
|
+
const redirectUrl = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}${CALLBACK_PATH}`;
|
|
3286
|
+
if (recorded && recorded.redirect_uris?.[0] !== redirectUrl) clear(serverId, OAUTH_CLIENT);
|
|
3287
|
+
const flow = {
|
|
3288
|
+
gen: generation,
|
|
3289
|
+
server,
|
|
3290
|
+
state: randomBytes(24).toString("base64url"),
|
|
3291
|
+
done,
|
|
3292
|
+
exchanging: false,
|
|
3293
|
+
settled: false
|
|
3294
|
+
};
|
|
3295
|
+
const provider = {
|
|
3296
|
+
redirectUrl,
|
|
3297
|
+
clientMetadata: clientMetadata(redirectUrl),
|
|
3298
|
+
state: () => flow.state,
|
|
3299
|
+
clientInformation: () => readClient(serverId),
|
|
3300
|
+
saveClientInformation: (info) => writeClient(serverId, generation, info),
|
|
3301
|
+
tokens: () => void 0,
|
|
3302
|
+
saveTokens(tokens) {
|
|
3303
|
+
writeTokens(serverId, generation, tokens);
|
|
3304
|
+
},
|
|
3305
|
+
redirectToAuthorization(url) {
|
|
3306
|
+
flow.authorizationUrl = url;
|
|
3307
|
+
},
|
|
3308
|
+
saveCodeVerifier(verifier) {
|
|
3309
|
+
flow.verifier = verifier;
|
|
3310
|
+
},
|
|
3311
|
+
codeVerifier() {
|
|
3312
|
+
if (flow.verifier === void 0) throw new Error("no authorization in progress");
|
|
3313
|
+
return flow.verifier;
|
|
3314
|
+
},
|
|
3315
|
+
invalidateCredentials(scope) {
|
|
3316
|
+
if (generation === gen(serverId)) invalidateScope(serverId, scope, flow);
|
|
3317
|
+
},
|
|
3318
|
+
saveDiscoveryState(state) {
|
|
3319
|
+
discovery.set(serverId, state);
|
|
3320
|
+
},
|
|
3321
|
+
discoveryState: () => discovery.get(serverId)
|
|
3322
|
+
};
|
|
3323
|
+
try {
|
|
3324
|
+
const result = await auth(provider, {
|
|
3325
|
+
serverUrl,
|
|
3326
|
+
fetchFn: deps.fetch
|
|
3327
|
+
});
|
|
3328
|
+
if (generation !== gen(serverId)) throw new Error("authorization was superseded");
|
|
3329
|
+
if (result !== "REDIRECT" || !flow.authorizationUrl) throw new Error("the authorization server did not ask for a browser authorization");
|
|
3330
|
+
} catch (error) {
|
|
3331
|
+
server.close();
|
|
3332
|
+
throw error;
|
|
3333
|
+
}
|
|
3334
|
+
server.on("request", (req, res) => {
|
|
3335
|
+
handle(req, res);
|
|
3336
|
+
});
|
|
3337
|
+
const handle = async (req, res) => {
|
|
3338
|
+
const url = new URL(req.url ?? "/", redirectUrl);
|
|
3339
|
+
if (req.method !== "GET" || url.pathname !== CALLBACK_PATH) {
|
|
3340
|
+
res.writeHead(404).end();
|
|
3341
|
+
return;
|
|
3342
|
+
}
|
|
3343
|
+
if (url.searchParams.get("state") !== flow.state || flow.settled || flow.exchanging) {
|
|
3344
|
+
respond(res, 400, "YaoGuang", "This authorization link is not valid. 授权链接无效。");
|
|
3345
|
+
return;
|
|
3346
|
+
}
|
|
3347
|
+
const error = url.searchParams.get("error");
|
|
3348
|
+
if (error !== null) {
|
|
3349
|
+
const code = /^[a-z_]{1,64}$/.test(error) ? error : "error";
|
|
3350
|
+
respond(res, 200, "YaoGuang", "Authorization was not completed. 授权未完成,可以关闭此页。");
|
|
3351
|
+
finish(serverId, flow, {
|
|
3352
|
+
ok: false,
|
|
3353
|
+
reason: `authorization was declined (${code})`
|
|
3354
|
+
});
|
|
3355
|
+
return;
|
|
3356
|
+
}
|
|
3357
|
+
const code = url.searchParams.get("code");
|
|
3358
|
+
if (!code) {
|
|
3359
|
+
respond(res, 400, "YaoGuang", "The authorization code is missing. 缺少授权码。");
|
|
3360
|
+
return;
|
|
3361
|
+
}
|
|
3362
|
+
flow.exchanging = true;
|
|
3363
|
+
try {
|
|
3364
|
+
await auth(provider, {
|
|
3365
|
+
serverUrl,
|
|
3366
|
+
authorizationCode: code,
|
|
3367
|
+
fetchFn: deps.fetch
|
|
3368
|
+
});
|
|
3369
|
+
respond(res, 200, "YaoGuang", "Authorization complete. You can close this page. 授权完成,可以关闭此页。");
|
|
3370
|
+
finish(serverId, flow, { ok: true });
|
|
3371
|
+
} catch (failure) {
|
|
3372
|
+
respond(res, 200, "YaoGuang", "Authorization failed. 授权失败,可以关闭此页。");
|
|
3373
|
+
finish(serverId, flow, {
|
|
3374
|
+
ok: false,
|
|
3375
|
+
reason: `token exchange failed: ${failure instanceof Error ? failure.message : String(failure)}`
|
|
3376
|
+
});
|
|
3377
|
+
}
|
|
3378
|
+
};
|
|
3379
|
+
flow.timer = setTimeout(() => finish(serverId, flow, {
|
|
3380
|
+
ok: false,
|
|
3381
|
+
reason: "authorization timed out after 5 minutes"
|
|
3382
|
+
}), timeoutMs);
|
|
3383
|
+
flow.timer.unref?.();
|
|
3384
|
+
flows.set(serverId, flow);
|
|
3385
|
+
return { url: flow.authorizationUrl.href };
|
|
3386
|
+
},
|
|
3387
|
+
/** Cancels owned callbacks and invalidates late writes without reading revoked credentials. */
|
|
3388
|
+
shutdown() {
|
|
3389
|
+
const owned = /* @__PURE__ */ new Set([
|
|
3390
|
+
...flows.keys(),
|
|
3391
|
+
...generations.keys(),
|
|
3392
|
+
...refreshes.keys(),
|
|
3393
|
+
...discovery.keys()
|
|
3394
|
+
]);
|
|
3395
|
+
for (const serverId of owned) invalidate(serverId);
|
|
3396
|
+
},
|
|
3397
|
+
/** Abandons the authorization in progress, if any. */
|
|
3398
|
+
cancel(serverId) {
|
|
3399
|
+
const flow = flows.get(serverId);
|
|
3400
|
+
if (flow) finish(serverId, flow, {
|
|
3401
|
+
ok: false,
|
|
3402
|
+
reason: "authorization was cancelled"
|
|
3403
|
+
});
|
|
3404
|
+
}
|
|
3405
|
+
};
|
|
3406
|
+
}
|
|
3407
|
+
//#endregion
|
|
3408
|
+
//#region src/content.ts
|
|
3409
|
+
const notice = (omitted) => `\n\n[… ${omitted} bytes omitted …]\n\n`;
|
|
3410
|
+
/**
|
|
3411
|
+
* `text` when it fits in `limit` UTF-8 bytes; otherwise its head and tail
|
|
3412
|
+
* split 3:1 around a line saying how much was left out. The notice's bytes
|
|
3413
|
+
* are reserved first, so the result never exceeds `limit`, and neither cut
|
|
3414
|
+
* splits a character.
|
|
3415
|
+
*/
|
|
3416
|
+
function truncate(text, limit) {
|
|
3417
|
+
const bytes = Buffer.from(text, "utf8");
|
|
3418
|
+
if (bytes.length <= limit) return text;
|
|
3419
|
+
const budget = limit - Buffer.byteLength(notice(bytes.length));
|
|
3420
|
+
let head = Math.floor(budget * 3 / 4);
|
|
3421
|
+
let tail = bytes.length - (budget - head);
|
|
3422
|
+
while (head > 0 && ((bytes[head] ?? 0) & 192) === 128) head -= 1;
|
|
3423
|
+
while (tail < bytes.length && ((bytes[tail] ?? 0) & 192) === 128) tail += 1;
|
|
3424
|
+
return bytes.subarray(0, head).toString("utf8") + notice(tail - head) + bytes.subarray(tail).toString("utf8");
|
|
3425
|
+
}
|
|
3426
|
+
/** Bytes a base64 blob decodes to. */
|
|
3427
|
+
function blobBytes(blob) {
|
|
3428
|
+
const padding = blob.endsWith("==") ? 2 : blob.endsWith("=") ? 1 : 0;
|
|
3429
|
+
return Math.max(0, Math.floor(blob.length * 3 / 4) - padding);
|
|
3430
|
+
}
|
|
3431
|
+
/** One embedded resource: its text, or a line naming what it was. */
|
|
3432
|
+
function resourceText(resource) {
|
|
3433
|
+
if (typeof resource.text === "string") return resource.text;
|
|
3434
|
+
return `[二进制资源:${typeof resource.mimeType === "string" ? resource.mimeType : "application/octet-stream"},${typeof resource.blob === "string" ? blobBytes(resource.blob) : 0} 字节]`;
|
|
3435
|
+
}
|
|
3436
|
+
/** One content block as text; `undefined` for a block with no text form. */
|
|
3437
|
+
function blockText(block) {
|
|
3438
|
+
switch (block.type) {
|
|
3439
|
+
case "text": return typeof block.text === "string" ? block.text : "";
|
|
3440
|
+
case "image": return `[图片:${String(block.mimeType ?? "image")}]`;
|
|
3441
|
+
case "audio": return `[音频:${String(block.mimeType ?? "audio")}]`;
|
|
3442
|
+
case "resource": return resourceText(block.resource ?? {});
|
|
3443
|
+
case "resource_link": return `[资源:${String(block.uri ?? "")}]`;
|
|
3444
|
+
default: return `[${block.type}]`;
|
|
3445
|
+
}
|
|
3446
|
+
}
|
|
3447
|
+
const isImageType = (mime) => typeof mime === "string" && mime.startsWith("image/");
|
|
3448
|
+
/** The last path segment of `uri`, query and fragment removed and percent
|
|
3449
|
+
* escapes decoded; `undefined` when that leaves nothing to name a file by. */
|
|
3450
|
+
function uriBasename(uri) {
|
|
3451
|
+
if (typeof uri !== "string") return void 0;
|
|
3452
|
+
const path = uri.replace(/[?#].*$/, "").replace(/\/+$/, "");
|
|
3453
|
+
const slash = path.lastIndexOf("/");
|
|
3454
|
+
if (slash === -1 || path[slash - 1] === ":") return void 0;
|
|
3455
|
+
const segment = path.slice(slash + 1);
|
|
3456
|
+
try {
|
|
3457
|
+
return decodeURIComponent(segment) || void 0;
|
|
3458
|
+
} catch {
|
|
3459
|
+
return segment || void 0;
|
|
3460
|
+
}
|
|
3461
|
+
}
|
|
3462
|
+
/** The bytes one block hands back as an image, with the name it goes by, or
|
|
3463
|
+
* `undefined` for a block that stays text: an `image` block or an embedded
|
|
3464
|
+
* resource `blob`, either with base64 data and an `image/*` type. Whether the
|
|
3465
|
+
* host can take the format is the host's judgement, not this one's. */
|
|
3466
|
+
function blockImage(block, ordinal) {
|
|
3467
|
+
const fallback = `image-${ordinal}`;
|
|
3468
|
+
if (block.type === "image") {
|
|
3469
|
+
if (typeof block.data !== "string" || !isImageType(block.mimeType)) return void 0;
|
|
3470
|
+
const data = Buffer.from(block.data, "base64");
|
|
3471
|
+
return data.length === 0 ? void 0 : {
|
|
3472
|
+
data: new Uint8Array(data),
|
|
3473
|
+
name: fallback
|
|
3474
|
+
};
|
|
3475
|
+
}
|
|
3476
|
+
if (block.type === "resource") {
|
|
3477
|
+
const resource = block.resource ?? {};
|
|
3478
|
+
if (typeof resource.text === "string") return void 0;
|
|
3479
|
+
if (typeof resource.blob !== "string" || !isImageType(resource.mimeType)) return void 0;
|
|
3480
|
+
const data = Buffer.from(resource.blob, "base64");
|
|
3481
|
+
if (data.length === 0) return void 0;
|
|
3482
|
+
return {
|
|
3483
|
+
data: new Uint8Array(data),
|
|
3484
|
+
name: uriBasename(resource.uri) ?? fallback
|
|
3485
|
+
};
|
|
3486
|
+
}
|
|
3487
|
+
}
|
|
3488
|
+
/**
|
|
3489
|
+
* A `tools/call` result as the model reads it: text blocks in order, image
|
|
3490
|
+
* blocks and embedded image resources as files, other blocks as placeholders,
|
|
3491
|
+
* and `structuredContent` as JSON when no text block carried anything. An
|
|
3492
|
+
* image's ordinal counts every image this result hands back, in block order.
|
|
3493
|
+
*/
|
|
3494
|
+
function toolResultContent(result) {
|
|
3495
|
+
const blocks = Array.isArray(result.content) ? result.content : [];
|
|
3496
|
+
const hasText = blocks.some((block) => block.type === "text");
|
|
3497
|
+
const files = [];
|
|
3498
|
+
const parts = [];
|
|
3499
|
+
for (const block of blocks) {
|
|
3500
|
+
const image = blockImage(block, files.length + 1);
|
|
3501
|
+
if (image) files.push(image);
|
|
3502
|
+
else parts.push(blockText(block));
|
|
3503
|
+
}
|
|
3504
|
+
if (!hasText && result.structuredContent !== void 0) parts.unshift(JSON.stringify(result.structuredContent));
|
|
3505
|
+
if (!blocks.length && result.structuredContent === void 0 && result.toolResult !== void 0) parts.push(JSON.stringify(result.toolResult));
|
|
3506
|
+
return {
|
|
3507
|
+
text: parts.join("\n"),
|
|
3508
|
+
files
|
|
3509
|
+
};
|
|
3510
|
+
}
|
|
3511
|
+
/**
|
|
3512
|
+
* A `prompts/get` result as the text a person's message carries: messages in
|
|
3513
|
+
* order, an assistant message introduced by a line saying so.
|
|
3514
|
+
*/
|
|
3515
|
+
function promptText(result) {
|
|
3516
|
+
return result.messages.map((message) => {
|
|
3517
|
+
const text = blockText(message.content);
|
|
3518
|
+
return message.role === "assistant" ? `[以下为 prompt 中的 assistant 消息]\n${text}` : text;
|
|
3519
|
+
}).join("\n\n");
|
|
3520
|
+
}
|
|
3521
|
+
/** A `resources/read` result as text, contents in order. */
|
|
3522
|
+
function readResultText(result) {
|
|
3523
|
+
return result.contents.map((content) => resourceText(content)).join("\n\n");
|
|
3524
|
+
}
|
|
3525
|
+
/** Counts original resource contents without allocating decoded binary blobs or a combined body. */
|
|
3526
|
+
function assertResourceBytes(result, maxBytes) {
|
|
3527
|
+
let bytes = 0;
|
|
3528
|
+
for (const item of result.contents) {
|
|
3529
|
+
bytes += typeof item.text === "string" ? Buffer.byteLength(item.text) : typeof item.blob === "string" ? blobBytes(item.blob) : 0;
|
|
3530
|
+
if (bytes > maxBytes) throw Object.assign(/* @__PURE__ */ new Error("MCP resource exceeds declared budget"), { code: "read-limit" });
|
|
3531
|
+
}
|
|
3532
|
+
}
|
|
3533
|
+
/** A host composer command argument name. */
|
|
3534
|
+
const ARGUMENT_NAME = /^[A-Za-z0-9_][A-Za-z0-9_-]{0,63}$/;
|
|
3535
|
+
/** The first twelve hex characters of `sha256(slug + "\0" + name)`. */
|
|
3536
|
+
function digest(slug, name) {
|
|
3537
|
+
return createHash("sha256").update(`${slug}\0${name}`).digest("hex").slice(0, 12);
|
|
3538
|
+
}
|
|
3539
|
+
/**
|
|
3540
|
+
* Maps a candidate to a legal name: characters outside `allowed` become `_`;
|
|
3541
|
+
* when any was replaced or the result exceeds `max`, it is cut to
|
|
3542
|
+
* `max - 13` characters and `_<hash>` appended, so the result is unique per
|
|
3543
|
+
* `(slug, name)` and independent of listing order.
|
|
3544
|
+
*/
|
|
3545
|
+
function legal(prefix, name, slug, allowed, max) {
|
|
3546
|
+
const body = name.replace(allowed, "_");
|
|
3547
|
+
const full = `${prefix}${body}`;
|
|
3548
|
+
if (body === name && full.length <= max) return full;
|
|
3549
|
+
return `${full.slice(0, max - 13)}_${digest(slug, name)}`;
|
|
3550
|
+
}
|
|
3551
|
+
/** `mcp_<slug>_<tool>`, at most 64 characters of `[A-Za-z0-9_-]`. */
|
|
3552
|
+
function toolName(slug, tool) {
|
|
3553
|
+
return legal(`mcp_${slug}_`, tool, slug, /[^A-Za-z0-9_-]/g, 64);
|
|
3554
|
+
}
|
|
3555
|
+
/** `<slug>.<prompt>`, a legal composer command name. */
|
|
3556
|
+
function commandName(slug, prompt) {
|
|
3557
|
+
return legal(`${slug}.`, prompt, slug, /[^A-Za-z0-9._-]/g, 200);
|
|
3558
|
+
}
|
|
3559
|
+
/** A legal composer argument name for an MCP prompt argument. */
|
|
3560
|
+
function argumentName(slug, argument) {
|
|
3561
|
+
const mapped = legal("", argument, slug, /[^A-Za-z0-9_-]/g, 64);
|
|
3562
|
+
return ARGUMENT_NAME.test(mapped) ? mapped : `_${mapped.slice(0, 63)}`;
|
|
3563
|
+
}
|
|
3564
|
+
/** Groups items by a mapped name and reports every name more than one item mapped to. */
|
|
3565
|
+
function collisions(items, name) {
|
|
3566
|
+
const seen = /* @__PURE__ */ new Map();
|
|
3567
|
+
for (const item of items) seen.set(name(item), (seen.get(name(item)) ?? 0) + 1);
|
|
3568
|
+
return new Set([...seen].filter(([, count]) => count > 1).map(([key]) => key));
|
|
3569
|
+
}
|
|
3570
|
+
const REFUSED_PROMPT = "maps to the same command name as another prompt of this server";
|
|
3571
|
+
/** Runs a server request; a failure's text is checked against the credentials first. */
|
|
3572
|
+
async function guarded(secrets, request) {
|
|
3573
|
+
try {
|
|
3574
|
+
return await request();
|
|
3575
|
+
} catch (error) {
|
|
3576
|
+
const safe = new Error(redact(error instanceof Error ? error.message : String(error), secrets));
|
|
3577
|
+
if (error instanceof Error && "code" in error && error.code === "read-limit") Object.assign(safe, { code: "read-limit" });
|
|
3578
|
+
throw safe;
|
|
3579
|
+
}
|
|
3580
|
+
}
|
|
3581
|
+
/**
|
|
3582
|
+
* The composer's MCP content: prompts as commands and resources as
|
|
3583
|
+
* attachments, for the servers an agent selects. Names a server gives are
|
|
3584
|
+
* mapped to what the host's command grammar accepts, and mapped back before
|
|
3585
|
+
* the server is asked; a prompt whose name or arguments collide is left out.
|
|
3586
|
+
*/
|
|
3587
|
+
function createPrompts(deps) {
|
|
3588
|
+
const { store } = deps;
|
|
3589
|
+
const mappedPrompts = (serverId, slug) => {
|
|
3590
|
+
const prompts = deps.connections().snapshot(serverId)?.prompts ?? [];
|
|
3591
|
+
const nameOf = (prompt) => commandName(slug, prompt.name).slice(slug.length + 1);
|
|
3592
|
+
const clashes = collisions(prompts, nameOf);
|
|
3593
|
+
const kept = [];
|
|
3594
|
+
const refused = /* @__PURE__ */ new Map();
|
|
3595
|
+
for (const prompt of prompts) {
|
|
3596
|
+
const name = nameOf(prompt);
|
|
3597
|
+
const argNames = (prompt.arguments ?? []).map((arg) => argumentName(slug, arg.name));
|
|
3598
|
+
if (clashes.has(name) || new Set(argNames).size !== argNames.length) {
|
|
3599
|
+
refused.set(prompt.name, REFUSED_PROMPT);
|
|
3600
|
+
continue;
|
|
3601
|
+
}
|
|
3602
|
+
const args = /* @__PURE__ */ new Map();
|
|
3603
|
+
for (const [index, arg] of (prompt.arguments ?? []).entries()) args.set(argNames[index], arg.name);
|
|
3604
|
+
kept.push({
|
|
3605
|
+
prompt,
|
|
3606
|
+
name,
|
|
3607
|
+
args
|
|
3608
|
+
});
|
|
3609
|
+
}
|
|
3610
|
+
return {
|
|
3611
|
+
kept,
|
|
3612
|
+
refused
|
|
3613
|
+
};
|
|
3614
|
+
};
|
|
3615
|
+
/** The server, when `agentId` selects it; otherwise the refusal. */
|
|
3616
|
+
const selected = (agentId, serverId) => {
|
|
3617
|
+
const record = store.server(serverId);
|
|
3618
|
+
if (!record) throw new Error("no such MCP server");
|
|
3619
|
+
if (!store.isSelected(agentId, serverId)) throw new Error(`server "${record.slug}" is not selected by this agent`);
|
|
3620
|
+
const live = deps.connections().live(serverId);
|
|
3621
|
+
if (!live) {
|
|
3622
|
+
const status = deps.connections().status(serverId);
|
|
3623
|
+
throw new Error(`MCP server ${record.name} 当前未连接:${status.reason ?? status.state}`);
|
|
3624
|
+
}
|
|
3625
|
+
return {
|
|
3626
|
+
record,
|
|
3627
|
+
live
|
|
3628
|
+
};
|
|
3629
|
+
};
|
|
3630
|
+
return {
|
|
3631
|
+
refusedPrompts(serverId, slug) {
|
|
3632
|
+
return mappedPrompts(serverId, slug).refused;
|
|
3633
|
+
},
|
|
3634
|
+
list(agentId) {
|
|
3635
|
+
const entries = [];
|
|
3636
|
+
for (const id of store.agentServers(agentId)) {
|
|
3637
|
+
const record = store.server(id);
|
|
3638
|
+
if (!record || !deps.connections().live(id)) continue;
|
|
3639
|
+
for (const { prompt, name, args } of mappedPrompts(id, record.slug).kept) {
|
|
3640
|
+
const back = new Map([...args].map(([mapped, own]) => [own, mapped]));
|
|
3641
|
+
entries.push({
|
|
3642
|
+
serverId: id,
|
|
3643
|
+
slug: record.slug,
|
|
3644
|
+
serverName: record.name,
|
|
3645
|
+
name,
|
|
3646
|
+
...prompt.description ? { description: prompt.description } : {},
|
|
3647
|
+
arguments: (prompt.arguments ?? []).map((arg) => ({
|
|
3648
|
+
name: back.get(arg.name),
|
|
3649
|
+
...arg.description ? { description: arg.description } : {},
|
|
3650
|
+
...arg.required ? { required: true } : {}
|
|
3651
|
+
}))
|
|
3652
|
+
});
|
|
3653
|
+
}
|
|
3654
|
+
}
|
|
3655
|
+
return entries;
|
|
3656
|
+
},
|
|
3657
|
+
async get(input, signal) {
|
|
3658
|
+
const { record, live } = selected(input.agentId, input.serverId);
|
|
3659
|
+
const found = mappedPrompts(record.id, record.slug).kept.find((one) => one.name === input.name);
|
|
3660
|
+
if (!found) throw new Error(`no prompt "${input.name}" on MCP server ${record.name}`);
|
|
3661
|
+
const args = {};
|
|
3662
|
+
for (const [mapped, own] of found.args) {
|
|
3663
|
+
const value = input.args[mapped];
|
|
3664
|
+
if (value !== void 0) args[own] = value;
|
|
3665
|
+
}
|
|
3666
|
+
for (const arg of found.prompt.arguments ?? []) if (arg.required && args[arg.name] === void 0) {
|
|
3667
|
+
const mapped = [...found.args].find(([, own]) => own === arg.name)?.[0] ?? arg.name;
|
|
3668
|
+
throw new Error(`missing argument "${mapped}"`);
|
|
3669
|
+
}
|
|
3670
|
+
return { text: redact(promptText(await guarded(live.secrets, () => live.client.getPrompt({
|
|
3671
|
+
name: found.prompt.name,
|
|
3672
|
+
arguments: args
|
|
3673
|
+
}, signal ? { signal } : void 0))), live.secrets) };
|
|
3674
|
+
},
|
|
3675
|
+
resources(agentId, query) {
|
|
3676
|
+
const needle = query.trim().toLowerCase();
|
|
3677
|
+
const entries = [];
|
|
3678
|
+
for (const id of store.agentServers(agentId)) {
|
|
3679
|
+
const record = store.server(id);
|
|
3680
|
+
if (!record || !deps.connections().live(id)) continue;
|
|
3681
|
+
for (const resource of deps.connections().snapshot(id)?.resources ?? []) {
|
|
3682
|
+
const haystack = [
|
|
3683
|
+
resource.name,
|
|
3684
|
+
resource.uri,
|
|
3685
|
+
resource.description
|
|
3686
|
+
].filter(Boolean).join("\n").toLowerCase();
|
|
3687
|
+
if (needle && !haystack.includes(needle)) continue;
|
|
3688
|
+
entries.push({
|
|
3689
|
+
serverId: id,
|
|
3690
|
+
serverName: record.name,
|
|
3691
|
+
uri: resource.uri,
|
|
3692
|
+
...resource.name ? { name: resource.name } : {},
|
|
3693
|
+
...resource.description ? { description: resource.description } : {}
|
|
3694
|
+
});
|
|
3695
|
+
if (entries.length >= 200) return entries;
|
|
3696
|
+
}
|
|
3697
|
+
}
|
|
3698
|
+
return entries;
|
|
3699
|
+
},
|
|
3700
|
+
async read(input, signal) {
|
|
3701
|
+
const { live } = selected(input.agentId, input.serverId);
|
|
3702
|
+
const result = await guarded(live.secrets, () => withResourceBudget(input.maxBytes, () => live.client.readResource({ uri: input.uri }, signal ? { signal } : void 0)));
|
|
3703
|
+
assertResourceBytes(result, input.maxBytes);
|
|
3704
|
+
const text = redact(readResultText(result), live.secrets);
|
|
3705
|
+
if (Buffer.byteLength(text) > input.maxBytes) throw Object.assign(/* @__PURE__ */ new Error("MCP resource exceeds declared budget"), { code: "read-limit" });
|
|
3706
|
+
return { text };
|
|
3707
|
+
}
|
|
3708
|
+
};
|
|
3709
|
+
}
|
|
3710
|
+
//#endregion
|
|
3711
|
+
//#region src/store.ts
|
|
3712
|
+
/** The plugin's three tables, always under the host-issued prefix. */
|
|
3713
|
+
function createMcpStore(storage) {
|
|
3714
|
+
const { db, tableName } = storage;
|
|
3715
|
+
const servers = tableName("server");
|
|
3716
|
+
const selections = tableName("agent_server");
|
|
3717
|
+
db.exec(`CREATE TABLE IF NOT EXISTS ${servers} (
|
|
3718
|
+
id TEXT NOT NULL PRIMARY KEY,
|
|
3719
|
+
slug TEXT NOT NULL UNIQUE,
|
|
3720
|
+
name TEXT NOT NULL,
|
|
3721
|
+
transport TEXT NOT NULL,
|
|
3722
|
+
config TEXT NOT NULL,
|
|
3723
|
+
enabled INTEGER NOT NULL,
|
|
3724
|
+
acknowledged_at INTEGER,
|
|
3725
|
+
created_at INTEGER NOT NULL
|
|
3726
|
+
) STRICT;
|
|
3727
|
+
CREATE TABLE IF NOT EXISTS ${selections} (
|
|
3728
|
+
agent_id TEXT NOT NULL,
|
|
3729
|
+
server_id TEXT NOT NULL,
|
|
3730
|
+
PRIMARY KEY (agent_id, server_id)
|
|
3731
|
+
) STRICT;
|
|
3732
|
+
CREATE INDEX IF NOT EXISTS ${tableName("agent_server_by_server")} ON ${selections} (server_id);`);
|
|
3733
|
+
const selected = db.prepare(`SELECT 1 FROM ${selections} WHERE agent_id = ? AND server_id = ?`);
|
|
3734
|
+
const parse = (row) => {
|
|
3735
|
+
const base = {
|
|
3736
|
+
id: String(row.id),
|
|
3737
|
+
slug: String(row.slug),
|
|
3738
|
+
name: String(row.name),
|
|
3739
|
+
enabled: Number(row.enabled) === 1,
|
|
3740
|
+
createdAt: Number(row.created_at)
|
|
3741
|
+
};
|
|
3742
|
+
const config = JSON.parse(String(row.config));
|
|
3743
|
+
return row.transport === "stdio" ? {
|
|
3744
|
+
...base,
|
|
3745
|
+
transport: "stdio",
|
|
3746
|
+
config: StdioConfigSchema.parse(config),
|
|
3747
|
+
acknowledgedAt: row.acknowledged_at === null ? null : Number(row.acknowledged_at)
|
|
3748
|
+
} : {
|
|
3749
|
+
...base,
|
|
3750
|
+
transport: "http",
|
|
3751
|
+
config: HttpConfigSchema.parse(config),
|
|
3752
|
+
acknowledgedAt: null
|
|
3753
|
+
};
|
|
3754
|
+
};
|
|
3755
|
+
const transaction = (write) => {
|
|
3756
|
+
if (db.isTransaction) return write();
|
|
3757
|
+
db.exec("BEGIN IMMEDIATE");
|
|
3758
|
+
try {
|
|
3759
|
+
const result = write();
|
|
3760
|
+
db.exec("COMMIT");
|
|
3761
|
+
return result;
|
|
3762
|
+
} catch (error) {
|
|
3763
|
+
db.exec("ROLLBACK");
|
|
3764
|
+
throw error;
|
|
3765
|
+
}
|
|
3766
|
+
};
|
|
3767
|
+
let directoryVersion = 0;
|
|
3768
|
+
const saveServer = (record) => {
|
|
3769
|
+
directoryVersion++;
|
|
3770
|
+
db.prepare(`INSERT INTO ${servers} (id, slug, name, transport, config, enabled, acknowledged_at, created_at)
|
|
3771
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
3772
|
+
ON CONFLICT(id) DO UPDATE SET slug = excluded.slug, name = excluded.name,
|
|
3773
|
+
transport = excluded.transport, config = excluded.config, enabled = excluded.enabled,
|
|
3774
|
+
acknowledged_at = excluded.acknowledged_at`).run(record.id, record.slug, record.name, record.transport, JSON.stringify(record.config), record.enabled ? 1 : 0, record.acknowledgedAt, record.createdAt);
|
|
3775
|
+
};
|
|
3776
|
+
const setServerSelected = (agentId, serverId, selected) => {
|
|
3777
|
+
directoryVersion++;
|
|
3778
|
+
if (selected) db.prepare(`INSERT OR IGNORE INTO ${selections} (agent_id, server_id) VALUES (?, ?)`).run(agentId, serverId);
|
|
3779
|
+
else db.prepare(`DELETE FROM ${selections} WHERE agent_id = ? AND server_id = ?`).run(agentId, serverId);
|
|
3780
|
+
};
|
|
3781
|
+
return {
|
|
3782
|
+
transaction,
|
|
3783
|
+
/** Header-only keyset query; selected-id filtering precedes LIMIT and never parses config. */
|
|
3784
|
+
headerPage(agentId, after, limit, ids) {
|
|
3785
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new Error("invalid header page limit");
|
|
3786
|
+
const filter = ids ? `AND s.id IN (${ids.map(() => "?").join(",")}) AND EXISTS (SELECT 1 FROM ${selections} a WHERE a.agent_id=? AND a.server_id=s.id)` : "";
|
|
3787
|
+
const rows = db.prepare(`SELECT s.id,s.slug,s.name,s.transport,s.enabled,
|
|
3788
|
+
EXISTS(SELECT 1 FROM ${selections} a WHERE a.agent_id=? AND a.server_id=s.id) AS selected
|
|
3789
|
+
FROM ${servers} s WHERE s.id>? ${filter} ORDER BY s.id LIMIT ?`).all(agentId, after ?? "", ...ids ? [...ids, agentId] : [], limit + 1);
|
|
3790
|
+
return {
|
|
3791
|
+
items: rows.slice(0, limit).map((row) => ({
|
|
3792
|
+
id: String(row.id),
|
|
3793
|
+
slug: String(row.slug),
|
|
3794
|
+
name: String(row.name),
|
|
3795
|
+
transport: row.transport,
|
|
3796
|
+
enabled: Number(row.enabled) === 1,
|
|
3797
|
+
selected: Number(row.selected) === 1
|
|
3798
|
+
})),
|
|
3799
|
+
complete: rows.length <= limit,
|
|
3800
|
+
queryVersion: directoryVersion
|
|
3801
|
+
};
|
|
3802
|
+
},
|
|
3803
|
+
/** Advances for every owner catalogue mutation; process restart invalidates owner cursor state. */
|
|
3804
|
+
directoryVersion: () => directoryVersion,
|
|
3805
|
+
servers() {
|
|
3806
|
+
return db.prepare(`SELECT * FROM ${servers} ORDER BY created_at, id`).all().map((row) => parse(row));
|
|
3807
|
+
},
|
|
3808
|
+
server(id) {
|
|
3809
|
+
const row = db.prepare(`SELECT * FROM ${servers} WHERE id = ?`).get(id);
|
|
3810
|
+
return row ? parse(row) : void 0;
|
|
3811
|
+
},
|
|
3812
|
+
serverBySlug(slug) {
|
|
3813
|
+
const row = db.prepare(`SELECT * FROM ${servers} WHERE slug = ?`).get(slug);
|
|
3814
|
+
return row ? parse(row) : void 0;
|
|
3815
|
+
},
|
|
3816
|
+
/** Inserts or replaces one server row. */
|
|
3817
|
+
saveServer,
|
|
3818
|
+
/** Creates a server and its initial agent selection atomically. */
|
|
3819
|
+
createSelectedServer(record, agentId, selected) {
|
|
3820
|
+
transaction(() => {
|
|
3821
|
+
saveServer(record);
|
|
3822
|
+
if (selected) setServerSelected(agentId, record.id, true);
|
|
3823
|
+
});
|
|
3824
|
+
},
|
|
3825
|
+
/** Adds or removes one agent's selection without replacing other selections. */
|
|
3826
|
+
setServerSelected,
|
|
3827
|
+
setEnabled(id, enabled) {
|
|
3828
|
+
directoryVersion++;
|
|
3829
|
+
db.prepare(`UPDATE ${servers} SET enabled = ? WHERE id = ?`).run(enabled ? 1 : 0, id);
|
|
3830
|
+
},
|
|
3831
|
+
/** Deletes a server with its selections, in one transaction. Its tools'
|
|
3832
|
+
* remembered approvals are the host's grants, keyed by this server's id,
|
|
3833
|
+
* and a person revokes them in the access list. */
|
|
3834
|
+
removeServer(id) {
|
|
3835
|
+
directoryVersion++;
|
|
3836
|
+
transaction(() => {
|
|
3837
|
+
db.prepare(`DELETE FROM ${servers} WHERE id = ?`).run(id);
|
|
3838
|
+
db.prepare(`DELETE FROM ${selections} WHERE server_id = ?`).run(id);
|
|
3839
|
+
});
|
|
3840
|
+
},
|
|
3841
|
+
isSelected(agentId, serverId) {
|
|
3842
|
+
return selected.get(agentId, serverId) !== void 0;
|
|
3843
|
+
},
|
|
3844
|
+
agentServers(agentId) {
|
|
3845
|
+
return db.prepare(`SELECT server_id FROM ${selections} WHERE agent_id = ? ORDER BY server_id`).all(agentId).map((row) => String(row.server_id));
|
|
3846
|
+
},
|
|
3847
|
+
agentsOf(serverId) {
|
|
3848
|
+
return db.prepare(`SELECT agent_id FROM ${selections} WHERE server_id = ? ORDER BY agent_id`).all(serverId).map((row) => String(row.agent_id));
|
|
3849
|
+
},
|
|
3850
|
+
/** Replaces an agent's selection whole. */
|
|
3851
|
+
setAgentServers(agentId, serverIds) {
|
|
3852
|
+
directoryVersion++;
|
|
3853
|
+
transaction(() => {
|
|
3854
|
+
db.prepare(`DELETE FROM ${selections} WHERE agent_id = ?`).run(agentId);
|
|
3855
|
+
const insert = db.prepare(`INSERT INTO ${selections} (agent_id, server_id) VALUES (?, ?)`);
|
|
3856
|
+
for (const id of new Set(serverIds)) insert.run(agentId, id);
|
|
3857
|
+
});
|
|
3858
|
+
}
|
|
3859
|
+
};
|
|
3860
|
+
}
|
|
3861
|
+
//#endregion
|
|
3862
|
+
//#region src/input-schema.ts
|
|
3863
|
+
/** Compiles a remote input contract before a tool becomes callable. */
|
|
3864
|
+
/** Enforces complete remote schemas locally; absent dialect declarations use MCP's 2020-12 default. */
|
|
3865
|
+
function inputValidator(schema) {
|
|
3866
|
+
const version = schema.$schema;
|
|
3867
|
+
const options = {
|
|
3868
|
+
strict: false,
|
|
3869
|
+
strictSchema: true,
|
|
3870
|
+
strictNumbers: true,
|
|
3871
|
+
validateSchema: true,
|
|
3872
|
+
allErrors: false,
|
|
3873
|
+
validateFormats: true
|
|
3874
|
+
};
|
|
3875
|
+
const compiler = version === void 0 || version === "https://json-schema.org/draft/2020-12/schema" ? new Ajv2020(options) : version === "https://json-schema.org/draft/2019-09/schema" ? new Ajv2019(options) : version === "http://json-schema.org/draft-07/schema#" || version === "http://json-schema.org/draft-07/schema" ? new Ajv(options) : void 0;
|
|
3876
|
+
if (!compiler) throw new Error("unsupported_tool_schema: unsupported JSON Schema dialect");
|
|
3877
|
+
addFormats.default(compiler);
|
|
3878
|
+
const validate = compiler.compile(schema);
|
|
3879
|
+
if ("$async" in validate && validate.$async) throw new Error("unsupported_tool_schema: asynchronous validation is unsupported");
|
|
3880
|
+
return z.record(z.string(), z.unknown()).superRefine((input, ctx) => {
|
|
3881
|
+
if (!validate(input)) ctx.addIssue({
|
|
3882
|
+
code: "custom",
|
|
3883
|
+
message: compiler.errorsText(validate.errors).slice(0, 512)
|
|
3884
|
+
});
|
|
3885
|
+
});
|
|
3886
|
+
}
|
|
3887
|
+
const RESOURCE_TOOL = "mcp_resource_read";
|
|
3888
|
+
const REFUSED_TAKEN = "name already taken";
|
|
3889
|
+
const REFUSED_COLLISION = "maps to the same name as another tool of this server";
|
|
3890
|
+
const RESERVED_TOOL_NAMES = /* @__PURE__ */ new Set([RESOURCE_TOOL, ...TOOL_NAMES]);
|
|
3891
|
+
/** Host-owned MCP tool names that a remote server cannot register, even if disabled. */
|
|
3892
|
+
function reservedToolName(name) {
|
|
3893
|
+
return RESERVED_TOOL_NAMES.has(name);
|
|
3894
|
+
}
|
|
3895
|
+
const ResourceInput = z.object({
|
|
3896
|
+
server: z.string().min(1).max(200).describe("The slug of an MCP server this agent selects."),
|
|
3897
|
+
uri: z.string().min(1).max(8192).describe("The resource URI the server listed.")
|
|
3898
|
+
}).strict();
|
|
3899
|
+
const messageOf = (error) => error instanceof Error ? error.message : String(error);
|
|
3900
|
+
const isTimeout = (error) => error?.code === -32001;
|
|
3901
|
+
const isUnauthorized = (error) => error?.name === "UnauthorizedError" || error?.constructor?.name === "UnauthorizedError";
|
|
3902
|
+
/**
|
|
3903
|
+
* The model-visible side: one registration per server tool, visible to the
|
|
3904
|
+
* agents that select its server, replaced whole and synchronously when a new
|
|
3905
|
+
* snapshot arrives; the `mcp_resource_read` tool; approval per call.
|
|
3906
|
+
*/
|
|
3907
|
+
function createTools(deps) {
|
|
3908
|
+
const { ctx, store } = deps;
|
|
3909
|
+
const callTimeout = deps.callTimeoutMs ?? 3e5;
|
|
3910
|
+
const registered = /* @__PURE__ */ new Map();
|
|
3911
|
+
const refused = /* @__PURE__ */ new Map();
|
|
3912
|
+
const mapped = /* @__PURE__ */ new Map();
|
|
3913
|
+
const scoped = /* @__PURE__ */ new Map();
|
|
3914
|
+
const handleFor = (serverId) => {
|
|
3915
|
+
let handle = scoped.get(serverId);
|
|
3916
|
+
if (!handle) {
|
|
3917
|
+
handle = ctx.forAgents((agentId) => store.isSelected(agentId, serverId));
|
|
3918
|
+
scoped.set(serverId, handle);
|
|
3919
|
+
}
|
|
3920
|
+
return handle;
|
|
3921
|
+
};
|
|
3922
|
+
const notConnected = (serverId, name) => {
|
|
3923
|
+
const status = deps.connections().status(serverId);
|
|
3924
|
+
if (status.state === "connected") return void 0;
|
|
3925
|
+
if (status.state === "needs-auth") return {
|
|
3926
|
+
content: `MCP server ${name} 需要重新授权`,
|
|
3927
|
+
isError: true
|
|
3928
|
+
};
|
|
3929
|
+
return {
|
|
3930
|
+
content: `MCP server ${name} 当前未连接:${status.reason ?? status.state}`,
|
|
3931
|
+
isError: true
|
|
3932
|
+
};
|
|
3933
|
+
};
|
|
3934
|
+
async function approve(serverId, server, tool, input, exec) {
|
|
3935
|
+
const decision = deps.approval.decide(exec, {
|
|
3936
|
+
id: `mcp:${server.slug}:${tool}`,
|
|
3937
|
+
subject: `call ${tool} on MCP server ${server.name}`,
|
|
3938
|
+
reason: truncate(JSON.stringify(input ?? {}), 2e3),
|
|
3939
|
+
accepts: [
|
|
3940
|
+
"allowed-once",
|
|
3941
|
+
"allowed-session",
|
|
3942
|
+
"allowed-always",
|
|
3943
|
+
"rejected"
|
|
3944
|
+
],
|
|
3945
|
+
remember: {
|
|
3946
|
+
key: `mcp:${serverId}:${tool}`,
|
|
3947
|
+
label: `调用 MCP 服务器「${server.name}」的 ${tool}`
|
|
3948
|
+
}
|
|
3949
|
+
});
|
|
3950
|
+
if (decision.kind === "ask") return decision.result;
|
|
3951
|
+
const result = decision.result;
|
|
3952
|
+
switch (result.kind) {
|
|
3953
|
+
case "allowed-once":
|
|
3954
|
+
case "allowed-session":
|
|
3955
|
+
case "allowed-always": return;
|
|
3956
|
+
case "record-failed": return {
|
|
3957
|
+
content: `could not remember the approval, so the call was not made: ${result.message}`,
|
|
3958
|
+
isError: true
|
|
3959
|
+
};
|
|
3960
|
+
case "rejected": {
|
|
3961
|
+
const reason = result.reason?.trim() ?? "";
|
|
3962
|
+
return {
|
|
3963
|
+
content: reason ? `permission refused by the person: ${reason}` : "permission refused by the person.",
|
|
3964
|
+
isError: true
|
|
3965
|
+
};
|
|
3966
|
+
}
|
|
3967
|
+
case "unavailable": return {
|
|
3968
|
+
content: "approval prompts are disabled; this MCP tool cannot be called",
|
|
3969
|
+
isError: true
|
|
3970
|
+
};
|
|
3971
|
+
}
|
|
3972
|
+
}
|
|
3973
|
+
async function call(serverId, tool, input, exec) {
|
|
3974
|
+
const record = store.server(serverId);
|
|
3975
|
+
if (!record || !store.isSelected(exec.address.agentId, serverId)) return {
|
|
3976
|
+
content: "this MCP server is not selected by this agent",
|
|
3977
|
+
isError: true
|
|
3978
|
+
};
|
|
3979
|
+
const current = deps.connections().snapshot(serverId)?.tools.find((candidate) => candidate.name === tool.name);
|
|
3980
|
+
if (!current || definitionKey(record.name, current) !== definitionKey(record.name, tool)) return {
|
|
3981
|
+
content: "MCP tool definition changed; search for the current definition again.",
|
|
3982
|
+
isError: true
|
|
3983
|
+
};
|
|
3984
|
+
const down = notConnected(serverId, record.name);
|
|
3985
|
+
if (down) return down;
|
|
3986
|
+
const gate = await approve(serverId, record, tool.name, input, exec);
|
|
3987
|
+
if (gate) return gate;
|
|
3988
|
+
const live = deps.connections().live(serverId);
|
|
3989
|
+
if (!live) return notConnected(serverId, record.name) ?? {
|
|
3990
|
+
content: "not connected",
|
|
3991
|
+
isError: true
|
|
3992
|
+
};
|
|
3993
|
+
try {
|
|
3994
|
+
const result = await live.client.callTool({
|
|
3995
|
+
name: tool.name,
|
|
3996
|
+
arguments: input
|
|
3997
|
+
}, void 0, {
|
|
3998
|
+
signal: exec.signal,
|
|
3999
|
+
timeout: callTimeout
|
|
4000
|
+
});
|
|
4001
|
+
const { text: raw, files } = toolResultContent(result);
|
|
4002
|
+
const text = redact(raw, live.secrets);
|
|
4003
|
+
return {
|
|
4004
|
+
content: JSON.stringify({
|
|
4005
|
+
text,
|
|
4006
|
+
sourceComplete: true
|
|
4007
|
+
}),
|
|
4008
|
+
...result.isError === true ? { isError: true } : {},
|
|
4009
|
+
...files.length === 0 ? {} : { files }
|
|
4010
|
+
};
|
|
4011
|
+
} catch (error) {
|
|
4012
|
+
if (isTimeout(error)) return {
|
|
4013
|
+
content: `调用超时(${Math.round(callTimeout / 6e4)} 分钟)`,
|
|
4014
|
+
isError: true
|
|
4015
|
+
};
|
|
4016
|
+
if (exec.signal.aborted) return {
|
|
4017
|
+
content: "the call was cancelled",
|
|
4018
|
+
isError: true
|
|
4019
|
+
};
|
|
4020
|
+
if (isUnauthorized(error)) {
|
|
4021
|
+
deps.connections().needsAuth(serverId, "the server refused the stored authorization");
|
|
4022
|
+
return {
|
|
4023
|
+
content: `MCP server ${record.name} 需要重新授权`,
|
|
4024
|
+
isError: true
|
|
4025
|
+
};
|
|
4026
|
+
}
|
|
4027
|
+
return {
|
|
4028
|
+
content: `MCP server ${record.name} 调用失败:${redact(messageOf(error), live.secrets)}`,
|
|
4029
|
+
isError: true
|
|
4030
|
+
};
|
|
4031
|
+
}
|
|
4032
|
+
}
|
|
4033
|
+
const definitionKey = (serverName, tool) => createHash("sha256").update(JSON.stringify([
|
|
4034
|
+
serverName,
|
|
4035
|
+
tool.name,
|
|
4036
|
+
tool.description ?? "",
|
|
4037
|
+
tool.inputSchema
|
|
4038
|
+
])).digest("hex");
|
|
4039
|
+
/**
|
|
4040
|
+
* Replaces a server's registrations with what `snapshot` lists, in one
|
|
4041
|
+
* synchronous pass: withdraws what disappeared, registers what is new and
|
|
4042
|
+
* re-registers what changed. `undefined` withdraws everything.
|
|
4043
|
+
*/
|
|
4044
|
+
function apply(serverId, snapshot) {
|
|
4045
|
+
const current = registered.get(serverId) ?? /* @__PURE__ */ new Map();
|
|
4046
|
+
const record = store.server(serverId);
|
|
4047
|
+
const nextRefused = /* @__PURE__ */ new Map();
|
|
4048
|
+
const nextMapped = /* @__PURE__ */ new Map();
|
|
4049
|
+
const wanted = /* @__PURE__ */ new Map();
|
|
4050
|
+
if (snapshot && record) {
|
|
4051
|
+
const clashes = collisions(snapshot.tools, (tool) => toolName(record.slug, tool.name));
|
|
4052
|
+
for (const tool of snapshot.tools) {
|
|
4053
|
+
const name = toolName(record.slug, tool.name);
|
|
4054
|
+
nextMapped.set(tool.name, name);
|
|
4055
|
+
if (reservedToolName(name)) nextRefused.set(tool.name, REFUSED_TAKEN);
|
|
4056
|
+
else if (clashes.has(name)) nextRefused.set(tool.name, REFUSED_COLLISION);
|
|
4057
|
+
else try {
|
|
4058
|
+
wanted.set(name, {
|
|
4059
|
+
tool,
|
|
4060
|
+
key: definitionKey(record.name, tool),
|
|
4061
|
+
input: inputValidator(tool.inputSchema)
|
|
4062
|
+
});
|
|
4063
|
+
} catch {
|
|
4064
|
+
nextRefused.set(tool.name, "unsupported_tool_schema");
|
|
4065
|
+
}
|
|
4066
|
+
}
|
|
4067
|
+
}
|
|
4068
|
+
for (const [name, entry] of current) {
|
|
4069
|
+
if (wanted.get(name)?.key === entry.key) continue;
|
|
4070
|
+
entry.dispose();
|
|
4071
|
+
current.delete(name);
|
|
4072
|
+
}
|
|
4073
|
+
for (const [name, { tool, key, input }] of wanted) {
|
|
4074
|
+
if (current.has(name) || !record) continue;
|
|
4075
|
+
const description = `[MCP · ${record.name}] ${tool.description ?? ""}`;
|
|
4076
|
+
try {
|
|
4077
|
+
const dispose = handleFor(serverId).tools.register({
|
|
4078
|
+
name,
|
|
4079
|
+
description,
|
|
4080
|
+
inputSchema: input,
|
|
4081
|
+
preload: false,
|
|
4082
|
+
catalogKind: "dynamic",
|
|
4083
|
+
deliveryKind: "preview",
|
|
4084
|
+
outputSchema: z.union([z.strictObject({
|
|
4085
|
+
text: z.string(),
|
|
4086
|
+
sourceComplete: z.boolean()
|
|
4087
|
+
}), z.string().max(1024)]),
|
|
4088
|
+
available: () => deps.connections().status(serverId).state === "connected",
|
|
4089
|
+
jsonSchema: tool.inputSchema,
|
|
4090
|
+
execute: (input, exec) => call(serverId, tool, input, exec)
|
|
4091
|
+
});
|
|
4092
|
+
current.set(name, {
|
|
4093
|
+
dispose,
|
|
4094
|
+
key
|
|
4095
|
+
});
|
|
4096
|
+
} catch (error) {
|
|
4097
|
+
nextRefused.set(tool.name, REFUSED_TAKEN);
|
|
4098
|
+
deps.log.emit({
|
|
4099
|
+
level: "warn",
|
|
4100
|
+
event: "plugin.event",
|
|
4101
|
+
fields: { localCode: "MCP_TOOL" }
|
|
4102
|
+
});
|
|
4103
|
+
}
|
|
4104
|
+
}
|
|
4105
|
+
registered.set(serverId, current);
|
|
4106
|
+
refused.set(serverId, nextRefused);
|
|
4107
|
+
mapped.set(serverId, nextMapped);
|
|
4108
|
+
if (!snapshot) {
|
|
4109
|
+
registered.delete(serverId);
|
|
4110
|
+
refused.delete(serverId);
|
|
4111
|
+
mapped.delete(serverId);
|
|
4112
|
+
}
|
|
4113
|
+
}
|
|
4114
|
+
/** Forgets a removed server's registrations. */
|
|
4115
|
+
function forget(serverId) {
|
|
4116
|
+
apply(serverId, void 0);
|
|
4117
|
+
scoped.delete(serverId);
|
|
4118
|
+
}
|
|
4119
|
+
async function readResource(input, exec, maxBytes) {
|
|
4120
|
+
const record = store.serverBySlug(input.server);
|
|
4121
|
+
if (!record || !store.isSelected(exec.address.agentId, record.id)) return {
|
|
4122
|
+
content: `server "${input.server}" is not selected by this agent`,
|
|
4123
|
+
isError: true
|
|
4124
|
+
};
|
|
4125
|
+
const down = notConnected(record.id, record.name);
|
|
4126
|
+
if (down) return down;
|
|
4127
|
+
const live = deps.connections().live(record.id);
|
|
4128
|
+
if (!live) return {
|
|
4129
|
+
content: `MCP server ${record.name} 当前未连接`,
|
|
4130
|
+
isError: true
|
|
4131
|
+
};
|
|
4132
|
+
try {
|
|
4133
|
+
const result = await withResourceBudget(maxBytes, () => live.client.readResource({ uri: input.uri }, {
|
|
4134
|
+
signal: exec.signal,
|
|
4135
|
+
timeout: callTimeout
|
|
4136
|
+
}));
|
|
4137
|
+
assertResourceBytes(result, maxBytes);
|
|
4138
|
+
const content = redact(readResultText(result), live.secrets);
|
|
4139
|
+
if (Buffer.byteLength(content) > maxBytes) throw Object.assign(/* @__PURE__ */ new Error("MCP resource exceeds declared budget"), { code: "read-limit" });
|
|
4140
|
+
return { content };
|
|
4141
|
+
} catch (error) {
|
|
4142
|
+
if (error instanceof Error && "code" in error && error.code === "read-limit") throw error;
|
|
4143
|
+
if (isTimeout(error)) return {
|
|
4144
|
+
content: `调用超时(${Math.round(callTimeout / 6e4)} 分钟)`,
|
|
4145
|
+
isError: true
|
|
4146
|
+
};
|
|
4147
|
+
return {
|
|
4148
|
+
content: `reading ${input.uri} from MCP server ${record.name} failed: ${redact(messageOf(error), live.secrets)}`,
|
|
4149
|
+
isError: true
|
|
4150
|
+
};
|
|
4151
|
+
}
|
|
4152
|
+
}
|
|
4153
|
+
/** Registers `mcp_resource_read`, visible to an agent that selects a server
|
|
4154
|
+
* offering resources. */
|
|
4155
|
+
function registerResourceTool() {
|
|
4156
|
+
return ctx.forAgents((agentId) => store.agentServers(agentId).some((id) => (deps.connections().snapshot(id)?.resources.length ?? 0) > 0)).tools.register({
|
|
4157
|
+
name: RESOURCE_TOOL,
|
|
4158
|
+
preload: false,
|
|
4159
|
+
description: "Read a resource from an MCP server this agent selects, by the server slug and the resource URI.",
|
|
4160
|
+
inputSchema: z.strictObject({
|
|
4161
|
+
items: z.array(ResourceInput).min(1).max(32).describe("Ordered selected-server resources, maximum 32; physical source limits are managed internally."),
|
|
4162
|
+
outputTokens: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional().describe("Desired model delivery tokens. Accepted originals are retained before bounded previews.")
|
|
4163
|
+
}),
|
|
4164
|
+
outputSchema: batchResult(z.strictObject({ content: z.string() }), z.strictObject({
|
|
4165
|
+
server: z.string(),
|
|
4166
|
+
uri: z.string()
|
|
4167
|
+
})),
|
|
4168
|
+
deliveryKind: "preview",
|
|
4169
|
+
async execute(input, exec) {
|
|
4170
|
+
const batch = await settle(input.items.map((item) => ({
|
|
4171
|
+
server: item.server,
|
|
4172
|
+
uri: item.uri
|
|
4173
|
+
})), async (_target, index) => {
|
|
4174
|
+
const result = await readResource(input.items[index], exec, Math.min(1048576, Math.floor(4194304 / input.items.length)));
|
|
4175
|
+
if (result.isError) throw new Error(result.content);
|
|
4176
|
+
return result;
|
|
4177
|
+
});
|
|
4178
|
+
return { content: JSON.stringify(batch) };
|
|
4179
|
+
}
|
|
4180
|
+
});
|
|
4181
|
+
}
|
|
4182
|
+
return {
|
|
4183
|
+
apply,
|
|
4184
|
+
forget,
|
|
4185
|
+
registerResourceTool,
|
|
4186
|
+
/** The catalog `getServer` shows: every listed tool, its mapped name and
|
|
4187
|
+
* why it was refused, if it was. */
|
|
4188
|
+
catalogTools(serverId, snapshot) {
|
|
4189
|
+
const names = mapped.get(serverId);
|
|
4190
|
+
const refusals = refused.get(serverId);
|
|
4191
|
+
return (snapshot?.tools ?? []).map((tool) => {
|
|
4192
|
+
const reason = refusals?.get(tool.name);
|
|
4193
|
+
return {
|
|
4194
|
+
name: tool.name,
|
|
4195
|
+
mappedName: names?.get(tool.name) ?? tool.name,
|
|
4196
|
+
...reason ? { refused: reason } : {}
|
|
4197
|
+
};
|
|
4198
|
+
});
|
|
4199
|
+
}
|
|
4200
|
+
};
|
|
4201
|
+
}
|
|
4202
|
+
//#endregion
|
|
4203
|
+
//#region src/index.ts
|
|
4204
|
+
/** The plugin, with its connection timing replaced where a test asks. */
|
|
4205
|
+
function createMcpPlugin(options = {}) {
|
|
4206
|
+
return {
|
|
4207
|
+
name: "@eum-agent/integration-mcp",
|
|
4208
|
+
configSchema: McpConfig,
|
|
4209
|
+
requires: [
|
|
4210
|
+
"query-resources",
|
|
4211
|
+
"credentials",
|
|
4212
|
+
"owner-operations",
|
|
4213
|
+
"host-commands",
|
|
4214
|
+
"protocol-processes",
|
|
4215
|
+
"network",
|
|
4216
|
+
"approval",
|
|
4217
|
+
"work-lifecycle",
|
|
4218
|
+
"agent-definition",
|
|
4219
|
+
"agent-definition-management",
|
|
4220
|
+
"agent-configuration-store"
|
|
4221
|
+
],
|
|
4222
|
+
apply(ctx, config) {
|
|
4223
|
+
const store = createMcpStore(ctx.storage.open());
|
|
4224
|
+
const commands = ctx.services.get("host-commands");
|
|
4225
|
+
const credentials = ctx.services.get("credentials");
|
|
4226
|
+
const network = ctx.services.get("network");
|
|
4227
|
+
const processes = ctx.services.get("protocol-processes");
|
|
4228
|
+
const approval = ctx.services.get("approval");
|
|
4229
|
+
const definitions = ctx.services.get("agent-definition");
|
|
4230
|
+
const management = ctx.services.get("agent-definition-management");
|
|
4231
|
+
const configuration = ctx.services.get("agent-configuration-store");
|
|
4232
|
+
const agentConfig = {
|
|
4233
|
+
state: management.state,
|
|
4234
|
+
check: management.check,
|
|
4235
|
+
prepare: management.prepare,
|
|
4236
|
+
save(ids, write, execution) {
|
|
4237
|
+
return management.save(ids, () => {
|
|
4238
|
+
ctx.signal.throwIfAborted();
|
|
4239
|
+
const result = write();
|
|
4240
|
+
for (const id of ids) configuration.write(ctx.pluginName, id, { mcpServerIds: store.agentServers(id) });
|
|
4241
|
+
return result;
|
|
4242
|
+
}, execution);
|
|
4243
|
+
}
|
|
4244
|
+
};
|
|
4245
|
+
let selfWriting = 0;
|
|
4246
|
+
const selfWrite = (write) => {
|
|
4247
|
+
selfWriting += 1;
|
|
4248
|
+
try {
|
|
4249
|
+
return write();
|
|
4250
|
+
} finally {
|
|
4251
|
+
selfWriting -= 1;
|
|
4252
|
+
}
|
|
4253
|
+
};
|
|
4254
|
+
const oauth = createOAuth({
|
|
4255
|
+
credentials,
|
|
4256
|
+
fetch: network.fetch,
|
|
4257
|
+
selfWrite,
|
|
4258
|
+
log: ctx.log,
|
|
4259
|
+
...options.authorizationTimeoutMs === void 0 ? {} : { timeoutMs: options.authorizationTimeoutMs }
|
|
4260
|
+
});
|
|
4261
|
+
let connections;
|
|
4262
|
+
const tools = createTools({
|
|
4263
|
+
ctx,
|
|
4264
|
+
store,
|
|
4265
|
+
connections: () => connections,
|
|
4266
|
+
approval,
|
|
4267
|
+
log: ctx.log,
|
|
4268
|
+
...options.callTimeoutMs === void 0 ? {} : { callTimeoutMs: options.callTimeoutMs }
|
|
4269
|
+
});
|
|
4270
|
+
let announce = () => {};
|
|
4271
|
+
connections = createConnections({
|
|
4272
|
+
commands,
|
|
4273
|
+
owner: ctx.pluginName,
|
|
4274
|
+
store,
|
|
4275
|
+
processes,
|
|
4276
|
+
network,
|
|
4277
|
+
credentials,
|
|
4278
|
+
oauth,
|
|
4279
|
+
log: ctx.log,
|
|
4280
|
+
onSnapshot: (serverId, snapshot) => {
|
|
4281
|
+
if (!ctx.signal.aborted) tools.apply(serverId, snapshot);
|
|
4282
|
+
},
|
|
4283
|
+
onChanged: () => {
|
|
4284
|
+
if (!ctx.signal.aborted) announce();
|
|
4285
|
+
},
|
|
4286
|
+
...options.timing ? { timing: options.timing } : {},
|
|
4287
|
+
...options.inherited ? { inherited: options.inherited } : {}
|
|
4288
|
+
});
|
|
4289
|
+
const prompts = createPrompts({
|
|
4290
|
+
store,
|
|
4291
|
+
connections: () => connections
|
|
4292
|
+
});
|
|
4293
|
+
const secretsOf = (serverId) => {
|
|
4294
|
+
const record = store.server(serverId);
|
|
4295
|
+
if (!record) return [];
|
|
4296
|
+
const read = (name) => {
|
|
4297
|
+
try {
|
|
4298
|
+
return credentials.get(serverId, name);
|
|
4299
|
+
} catch {
|
|
4300
|
+
return;
|
|
4301
|
+
}
|
|
4302
|
+
};
|
|
4303
|
+
return [...credentialNames(record).map(read), ...oauth.secrets(serverId)];
|
|
4304
|
+
};
|
|
4305
|
+
const methods = registerMethods({
|
|
4306
|
+
commands,
|
|
4307
|
+
ctx,
|
|
4308
|
+
store,
|
|
4309
|
+
connections,
|
|
4310
|
+
tools,
|
|
4311
|
+
prompts,
|
|
4312
|
+
oauth,
|
|
4313
|
+
credentials,
|
|
4314
|
+
selfWrite,
|
|
4315
|
+
secretsOf,
|
|
4316
|
+
agentConfig
|
|
4317
|
+
});
|
|
4318
|
+
ctx.agentConfiguration.register({
|
|
4319
|
+
schema: z.strictObject({ mcpServerIds: z.array(z.string().min(1)).default([]) }).default({ mcpServerIds: [] }),
|
|
4320
|
+
read: (id) => ({ mcpServerIds: store.agentServers(id) }),
|
|
4321
|
+
remove(id) {
|
|
4322
|
+
return {
|
|
4323
|
+
apply: () => store.setAgentServers(id, []),
|
|
4324
|
+
abort() {},
|
|
4325
|
+
settle() {}
|
|
4326
|
+
};
|
|
4327
|
+
},
|
|
4328
|
+
prepare(id, value) {
|
|
4329
|
+
for (const server of value.mcpServerIds) if (!store.server(server)) throw new Error(`Missing MCP server ${server}`);
|
|
4330
|
+
return {
|
|
4331
|
+
apply() {
|
|
4332
|
+
store.setAgentServers(id, value.mcpServerIds);
|
|
4333
|
+
configuration.write(ctx.pluginName, id, value);
|
|
4334
|
+
},
|
|
4335
|
+
abort() {},
|
|
4336
|
+
settle() {
|
|
4337
|
+
methods.management.selectionChanged(id);
|
|
4338
|
+
}
|
|
4339
|
+
};
|
|
4340
|
+
}
|
|
4341
|
+
});
|
|
4342
|
+
announce = methods.announce;
|
|
4343
|
+
const disabled = new Set(config.disabled);
|
|
4344
|
+
registerMcpManagementTools({
|
|
4345
|
+
resources: ctx.services.get("query-resources"),
|
|
4346
|
+
definitions,
|
|
4347
|
+
approval,
|
|
4348
|
+
store,
|
|
4349
|
+
connections,
|
|
4350
|
+
credentials,
|
|
4351
|
+
oauth,
|
|
4352
|
+
management: methods.management,
|
|
4353
|
+
register: (tool) => {
|
|
4354
|
+
if (!disabled.has(tool.name)) ctx.tools.register(tool);
|
|
4355
|
+
},
|
|
4356
|
+
onDispose: (dispose) => ctx.onDispose(dispose)
|
|
4357
|
+
});
|
|
4358
|
+
ctx.tools.guide({
|
|
4359
|
+
title: "MCP servers",
|
|
4360
|
+
entries: [
|
|
4361
|
+
{
|
|
4362
|
+
tools: ["mcp_server_list"],
|
|
4363
|
+
text: "`mcp_server_list` lists configured servers and whether this agent selects them; with `serverId` it reads one selected server’s safe configuration and credential status."
|
|
4364
|
+
},
|
|
4365
|
+
{
|
|
4366
|
+
tools: ["mcp_server_create"],
|
|
4367
|
+
text: "`mcp_server_create` proposes a new server and normally selects it for this agent."
|
|
4368
|
+
},
|
|
4369
|
+
{
|
|
4370
|
+
tools: ["mcp_server_update"],
|
|
4371
|
+
text: "`mcp_server_update` proposes changes to a server this agent selects; shared changes affect every selecting agent."
|
|
4372
|
+
},
|
|
4373
|
+
{
|
|
4374
|
+
tools: ["mcp_server_set_selected"],
|
|
4375
|
+
text: "`mcp_server_set_selected` changes only this agent’s selection."
|
|
4376
|
+
}
|
|
4377
|
+
]
|
|
4378
|
+
});
|
|
4379
|
+
tools.registerResourceTool();
|
|
4380
|
+
const offCredentials = credentials.onChanged((scopes) => {
|
|
4381
|
+
if (ctx.signal.aborted || selfWriting > 0) return;
|
|
4382
|
+
for (const scope of scopes) if (store.server(scope)) connections.reconcile(scope, { keepSnapshot: true });
|
|
4383
|
+
});
|
|
4384
|
+
let withdrawn = false;
|
|
4385
|
+
let unbind = () => {};
|
|
4386
|
+
let drained;
|
|
4387
|
+
const drain = () => {
|
|
4388
|
+
drained ??= (async () => {
|
|
4389
|
+
oauth.shutdown();
|
|
4390
|
+
const results = await Promise.allSettled([connections.shutdown()]);
|
|
4391
|
+
results.push(...await Promise.allSettled([processes.shutdown()]));
|
|
4392
|
+
const failures = results.filter((result) => result.status === "rejected");
|
|
4393
|
+
if (failures.length) throw new AggregateError(failures.map((result) => result.reason), "MCP cleanup failed");
|
|
4394
|
+
if (withdrawn) {
|
|
4395
|
+
unbind();
|
|
4396
|
+
unbind = () => {};
|
|
4397
|
+
}
|
|
4398
|
+
})().catch((error) => {
|
|
4399
|
+
drained = void 0;
|
|
4400
|
+
throw error;
|
|
4401
|
+
});
|
|
4402
|
+
return drained;
|
|
4403
|
+
};
|
|
4404
|
+
unbind = ctx.services.get("work-lifecycle").register(drain);
|
|
4405
|
+
ctx.onDispose(async () => {
|
|
4406
|
+
withdrawn = true;
|
|
4407
|
+
offCredentials();
|
|
4408
|
+
await drain();
|
|
4409
|
+
unbind();
|
|
4410
|
+
unbind = () => {};
|
|
4411
|
+
});
|
|
4412
|
+
connections.boot();
|
|
4413
|
+
const ui = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
|
|
4414
|
+
if (!options.withoutUi && existsSync(ui)) ctx.client.registerUi({ module: ui });
|
|
4415
|
+
}
|
|
4416
|
+
};
|
|
4417
|
+
}
|
|
4418
|
+
const mcpPlugin = createMcpPlugin();
|
|
4419
|
+
//#endregion
|
|
4420
|
+
export { TOOL_NAMES, createMcpPlugin, mcpPlugin as default, mcpPlugin };
|