@eum-agent/integration-mcp 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/dist/index.js +3201 -0
  2. package/package.json +51 -3
  3. package/ui/ui.js +2690 -0
  4. package/README.md +0 -3
package/dist/index.js ADDED
@@ -0,0 +1,3201 @@
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 { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";
9
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
10
+ import { isDeepStrictEqual } from "node:util";
11
+ import { createServer } from "node:http";
12
+ import { auth, discoverOAuthServerInfo, refreshAuthorization, selectResourceURL } from "@modelcontextprotocol/sdk/client/auth.js";
13
+ import { OAuthError, ServerError } from "@modelcontextprotocol/sdk/server/auth/errors.js";
14
+ //#region src/names.ts
15
+ /**
16
+ * The name rules both halves apply: the gateway's zod in `config.ts` and the
17
+ * settings form in `ui/draft.ts`. Imports nothing, so the browser program can
18
+ * take it without Node types.
19
+ */
20
+ /** A server's short name: part of every tool and command name it contributes. */
21
+ const SLUG = /^[a-z0-9][a-z0-9-]{0,23}$/;
22
+ /** An environment variable a person configures: a portable shell identifier. */
23
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
24
+ /** An HTTP header name (RFC 9110 token) that is also a valid credential name. */
25
+ const HEADER_NAME = /^[A-Za-z0-9_][A-Za-z0-9_-]{0,99}$/;
26
+ //#endregion
27
+ //#region src/config.ts
28
+ const EnvEntrySchema = z.object({
29
+ 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"),
30
+ /** A credential: its value lives in the credential manager as `env.<name>`. */
31
+ secret: z.boolean(),
32
+ /** The plain value; absent for a credential. */
33
+ value: z.string().max(32768).refine((value) => !value.includes("\0"), "invalid environment value").optional()
34
+ }).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");
35
+ /** A local command. `command` is an absolute path or a bare name looked up on PATH. */
36
+ const StdioConfigSchema = z.object({
37
+ 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"),
38
+ args: z.array(z.string().max(32768).refine((value) => !value.includes("\0"), "invalid argument")).max(256).default([]),
39
+ cwd: z.string().refine((cwd) => !cwd.includes("\0") && (isAbsolute(cwd) || /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(cwd)), "cwd must be an absolute path").optional(),
40
+ env: z.array(EnvEntrySchema).max(256).default([])
41
+ }).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");
42
+ /** A remote Streamable HTTP endpoint. Header values are credentials (`header.<name>`). */
43
+ const HttpConfigSchema = z.object({
44
+ url: z.string().trim().refine((url) => {
45
+ try {
46
+ const parsed = new URL(url);
47
+ return (parsed.protocol === "http:" || parsed.protocol === "https:") && parsed.username === "" && parsed.password === "";
48
+ } catch {
49
+ return false;
50
+ }
51
+ }, "url must be an http(s) URL"),
52
+ auth: z.enum([
53
+ "none",
54
+ "headers",
55
+ "oauth"
56
+ ]),
57
+ headers: z.array(z.string().regex(HEADER_NAME, "invalid header name")).max(64).default([])
58
+ }).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\"");
59
+ /** What a person saves; `id` absent creates a server. */
60
+ const SaveServerSchema = z.discriminatedUnion("transport", [z.object({
61
+ id: z.string().uuid().optional(),
62
+ slug: z.string(),
63
+ name: z.string().trim().min(1).max(80),
64
+ transport: z.literal("stdio"),
65
+ config: StdioConfigSchema,
66
+ acknowledge: z.boolean().optional()
67
+ }).strict(), z.object({
68
+ id: z.string().uuid().optional(),
69
+ slug: z.string(),
70
+ name: z.string().trim().min(1).max(80),
71
+ transport: z.literal("http"),
72
+ config: HttpConfigSchema,
73
+ acknowledge: z.boolean().optional()
74
+ }).strict()]);
75
+ /** Refuses a slug that is malformed; uniqueness is the store's. */
76
+ function checkSlug(slug) {
77
+ if (!SLUG.test(slug)) throw new Error(`slug must match ${SLUG.source}`);
78
+ }
79
+ /** What a person acknowledges for a stdio server: the command line, where it
80
+ * runs and which variables it is given. A value change is not in it. */
81
+ function acknowledgementKey(config, platform = process.platform) {
82
+ return JSON.stringify([
83
+ config.command,
84
+ config.args,
85
+ config.cwd ?? null,
86
+ [...new Set(config.env.map((entry) => platform === "win32" ? entry.name.toUpperCase() : entry.name))].sort()
87
+ ]);
88
+ }
89
+ /** The credential name that holds a secret environment variable's value. */
90
+ const envCredential = (name) => `env.${name}`;
91
+ /** The credential name that holds a header's value. */
92
+ const headerCredential = (name) => `header.${name}`;
93
+ const OAUTH_TOKENS = "oauth.tokens";
94
+ const OAUTH_CLIENT = "oauth.client";
95
+ /** Every credential name a configuration refers to (OAuth excluded). */
96
+ function credentialNames(record) {
97
+ 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) : [];
98
+ }
99
+ /** Resolves bare executables and the real cwd before their launch is acknowledged. */
100
+ async function resolveStdioConfig(config, commands) {
101
+ const plain = Object.fromEntries(config.env.filter((entry) => !entry.secret).map((entry) => [entry.name, entry.value]));
102
+ const env = commands.environment([commands.childEnvironment(commands.env, "protocol"), plain]);
103
+ const inspected = await commands.inspect(config.command, env);
104
+ if (inspected.status !== "found" || !inspected.path) throw new Error(`command-unavailable: ${inspected.reason}`);
105
+ for (const entry of config.env) {
106
+ if ((commands.platform === "win32" ? entry.name.toUpperCase() : entry.name).startsWith("YAOGUANG_")) throw new Error("configured environment variable is reserved");
107
+ if (/^(?:https?|all|ftp|no)_proxy$/i.test(entry.name)) throw new Error("proxy-environment-managed-by-gateway");
108
+ }
109
+ return {
110
+ ...config,
111
+ command: inspected.path,
112
+ cwd: await commands.directory(config.cwd ?? commands.homedir())
113
+ };
114
+ }
115
+ //#endregion
116
+ //#region src/env.ts
117
+ /**
118
+ * Filters inherited credentials, preserves explicit credentials and refuses reserved names.
119
+ * Each source is validated before layer overrides. The gateway controls proxies; configured
120
+ * proxy names are refused. Values are preserved exactly and never included in errors.
121
+ */
122
+ function childEnvironment(input) {
123
+ const { commands } = input;
124
+ const configuredSources = [];
125
+ for (const entry of input.config.env) {
126
+ const name = commands.platform === "win32" ? entry.name.toUpperCase() : entry.name;
127
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(entry.name)) throw new Error("invalid-environment-input");
128
+ if (name.startsWith("YAOGUANG_")) throw new Error("configured environment variable is reserved");
129
+ if (/^(?:https?|all|ftp|no)_proxy$/i.test(name)) throw new Error("proxy-environment-managed-by-gateway");
130
+ const value = entry.secret ? input.secret(entry.name) : entry.value ?? "";
131
+ if (value === void 0) throw new MissingCredentialError(entry.name);
132
+ configuredSources.push({ [entry.name]: value });
133
+ }
134
+ const configured = {};
135
+ for (const source of configuredSources) for (const [name, value] of Object.entries(source)) {
136
+ const key = commands.platform === "win32" ? name.toUpperCase() : name;
137
+ if (Object.hasOwn(configured, key) && configured[key] !== value) throw new Error(`environment-name-conflict: ${key}`);
138
+ configured[key] = value;
139
+ }
140
+ return {
141
+ env: commands.environment([commands.childEnvironment(input.inherited, "protocol"), input.proxy]),
142
+ configuredEnv: commands.environment([configured])
143
+ };
144
+ }
145
+ /** A configured credential variable has no stored value. */
146
+ var MissingCredentialError = class extends Error {
147
+ /** Variable name whose credential must be supplied. */
148
+ variable;
149
+ /** Reports the missing variable without revealing a credential value. */
150
+ constructor(variable) {
151
+ super(`credential for ${variable} is not set`);
152
+ this.name = "MissingCredentialError";
153
+ this.variable = variable;
154
+ }
155
+ };
156
+ //#endregion
157
+ //#region src/redact.ts
158
+ /** What replaces a credential found in outward text. */
159
+ const REDACTED = "[已隐去]";
160
+ /** The text a status reason becomes when it contains a credential. */
161
+ const REDACTED_REASON = "原因中含有凭据,已整段隐去";
162
+ /** Fields of an OAuth JSON credential whose values are secrets in their own right. */
163
+ const JSON_SECRETS = [
164
+ "access_token",
165
+ "refresh_token",
166
+ "id_token",
167
+ "client_secret"
168
+ ];
169
+ /**
170
+ * The values to compare outward text against, from the credentials a request
171
+ * actually used. A JSON credential (`oauth.tokens`, `oauth.client`) is split
172
+ * into its secret fields as well, because a server echoes a token, never the
173
+ * JSON document holding it. Values shorter than four characters are left out:
174
+ * replacing every occurrence of one would destroy the text without protecting
175
+ * anything a hint (the last four characters) does not already show.
176
+ */
177
+ function secretValues(raw) {
178
+ const values = /* @__PURE__ */ new Set();
179
+ for (const value of raw) {
180
+ if (value === void 0) continue;
181
+ values.add(value);
182
+ if (!value.startsWith("{")) continue;
183
+ try {
184
+ const parsed = JSON.parse(value);
185
+ for (const key of JSON_SECRETS) {
186
+ const field = parsed[key];
187
+ if (typeof field === "string") values.add(field);
188
+ }
189
+ } catch {}
190
+ }
191
+ return [...values].filter((value) => value.length >= 4).sort((a, b) => b.length - a.length);
192
+ }
193
+ /** Whether `text` contains any of `secrets`. */
194
+ function containsSecret(text, secrets) {
195
+ return secrets.some((secret) => text.includes(secret));
196
+ }
197
+ /** `text` with every occurrence of every secret replaced by `[已隐去]`. */
198
+ function redact(text, secrets) {
199
+ let out = text;
200
+ for (const secret of secrets) if (out.includes(secret)) out = out.split(secret).join(REDACTED);
201
+ return out;
202
+ }
203
+ /** A status reason as it may be shown: hidden whole when it contains a secret. */
204
+ function redactReason(text, secrets) {
205
+ return containsSecret(text, secrets) ? REDACTED_REASON : text;
206
+ }
207
+ //#endregion
208
+ //#region src/transport/http.ts
209
+ /**
210
+ * A Streamable HTTP transport whose every request goes through the gateway's
211
+ * network service: the endpoint is one a person configured, so it takes the
212
+ * gateway's route and never passes through the allowed-host list. `headers`
213
+ * carries the static header credentials; `authProvider` the OAuth tokens.
214
+ */
215
+ function httpTransport(input) {
216
+ return new StreamableHTTPClientTransport(new URL(input.url), {
217
+ fetch: input.fetch,
218
+ requestInit: { headers: { ...input.headers } },
219
+ ...input.authProvider ? { authProvider: input.authProvider } : {}
220
+ });
221
+ }
222
+ //#endregion
223
+ //#region src/transport/output-schema.ts
224
+ function record(value) {
225
+ return typeof value === "object" && value !== null && !Array.isArray(value);
226
+ }
227
+ function objectOnly(schema) {
228
+ let remaining = 256;
229
+ const ancestors = /* @__PURE__ */ new Set();
230
+ const resolve = (ref) => {
231
+ if (typeof ref !== "string" || !ref.startsWith("#/")) return void 0;
232
+ let pointer;
233
+ try {
234
+ pointer = decodeURIComponent(ref.slice(1));
235
+ } catch {
236
+ return;
237
+ }
238
+ let target = schema;
239
+ for (const part of pointer.slice(1).split("/")) {
240
+ if (--remaining < 0 || /~(?:[^01]|$)/.test(part)) return void 0;
241
+ const key = part.replaceAll("~1", "/").replaceAll("~0", "~");
242
+ if (!record(target) || "$id" in target || !Object.hasOwn(target, key)) return void 0;
243
+ target = target[key];
244
+ }
245
+ return target;
246
+ };
247
+ const visit = (node, depth) => {
248
+ if (--remaining < 0 || depth > 64 || !record(node) || ancestors.has(node)) return false;
249
+ if ("$id" in node || "$dynamicRef" in node || "$recursiveRef" in node || "allOf" in node) return false;
250
+ ancestors.add(node);
251
+ try {
252
+ let proven = false;
253
+ if ("type" in node) {
254
+ if (node.type !== "object") return false;
255
+ proven = true;
256
+ }
257
+ if ("$ref" in node) {
258
+ if (!visit(resolve(node.$ref), depth + 1)) return false;
259
+ proven = true;
260
+ }
261
+ for (const key of ["oneOf", "anyOf"]) {
262
+ if (!(key in node)) continue;
263
+ const branches = node[key];
264
+ if (!Array.isArray(branches) || branches.length === 0 || !branches.every((branch) => visit(branch, depth + 1))) return false;
265
+ proven = true;
266
+ }
267
+ return proven;
268
+ } finally {
269
+ ancestors.delete(node);
270
+ }
271
+ };
272
+ return visit(schema, 0);
273
+ }
274
+ function normalizeResult(result) {
275
+ if (!Array.isArray(result.tools)) return result;
276
+ let changed = false;
277
+ const tools = result.tools.map((tool) => {
278
+ if (!record(tool) || !record(tool.outputSchema)) return tool;
279
+ const schema = tool.outputSchema;
280
+ if ("type" in schema || !objectOnly(schema)) return tool;
281
+ changed = true;
282
+ return {
283
+ ...tool,
284
+ outputSchema: {
285
+ ...schema,
286
+ type: "object"
287
+ }
288
+ };
289
+ });
290
+ return changed ? {
291
+ ...result,
292
+ tools
293
+ } : result;
294
+ }
295
+ /**
296
+ * Adds a missing root object type only to provably object-only tool output schemas.
297
+ * Only replies to tracked tools/list requests are normalized; the SDK still parses
298
+ * the complete reply, caches output validators and validates subsequent tool results.
299
+ * Delegates transport ownership, session metadata and protocol negotiation unchanged.
300
+ */
301
+ function objectOutputSchemas(transport) {
302
+ const pending = /* @__PURE__ */ new Set();
303
+ const wrapped = {
304
+ start() {
305
+ transport.onclose = () => {
306
+ pending.clear();
307
+ wrapped.onclose?.();
308
+ };
309
+ transport.onerror = (error) => wrapped.onerror?.(error);
310
+ transport.onmessage = (message, extra) => {
311
+ if (("result" in message || "error" in message) && message.id !== void 0 && pending.delete(message.id)) {
312
+ if ("result" in message) {
313
+ const result = normalizeResult(message.result);
314
+ if (result !== message.result) {
315
+ wrapped.onmessage?.({
316
+ ...message,
317
+ result
318
+ }, extra);
319
+ return;
320
+ }
321
+ }
322
+ }
323
+ wrapped.onmessage?.(message, extra);
324
+ };
325
+ return transport.start();
326
+ },
327
+ async send(message, options) {
328
+ const id = "id" in message ? message.id : void 0;
329
+ if ("method" in message && message.method === "tools/list" && id !== void 0) pending.add(id);
330
+ if ("method" in message && message.method === "notifications/cancelled") {
331
+ const requestId = message.params?.requestId;
332
+ if (typeof requestId === "string" || typeof requestId === "number") pending.delete(requestId);
333
+ }
334
+ try {
335
+ await transport.send(message, options);
336
+ } catch (error) {
337
+ if (id !== void 0) pending.delete(id);
338
+ throw error;
339
+ }
340
+ },
341
+ close: () => transport.close(),
342
+ get sessionId() {
343
+ return transport.sessionId;
344
+ },
345
+ setProtocolVersion: (version) => transport.setProtocolVersion?.(version)
346
+ };
347
+ return wrapped;
348
+ }
349
+ //#endregion
350
+ //#region src/transport/stdio.ts
351
+ /**
352
+ * An MCP transport over a host-owned protocol process: newline-delimited
353
+ * JSON-RPC on its stdin and stdout. The host spawned the process and alone
354
+ * signals it; `close()` asks the host to stop the group and settles once it
355
+ * has, rejecting when the host reports the cleanup failed.
356
+ */
357
+ var ProcessTransport = class {
358
+ onclose;
359
+ onerror;
360
+ onmessage;
361
+ process;
362
+ buffer = new ReadBuffer();
363
+ closed = false;
364
+ stopping;
365
+ constructor(process) {
366
+ this.process = process;
367
+ }
368
+ async start() {
369
+ const { stdout, stdin } = this.process;
370
+ stdout.on("data", (chunk) => {
371
+ try {
372
+ this.buffer.append(chunk);
373
+ } catch (error) {
374
+ this.onerror?.(error);
375
+ return;
376
+ }
377
+ while (true) {
378
+ let message;
379
+ try {
380
+ message = this.buffer.readMessage();
381
+ } catch (error) {
382
+ this.onerror?.(error);
383
+ continue;
384
+ }
385
+ if (message === null) break;
386
+ this.onmessage?.(message);
387
+ }
388
+ });
389
+ stdout.on("error", (error) => this.onerror?.(error));
390
+ stdin.on("error", (error) => this.onerror?.(error));
391
+ this.process.exited.then(() => this.finish(), () => this.finish());
392
+ }
393
+ send(message) {
394
+ if (this.closed) return Promise.reject(/* @__PURE__ */ new Error("server process is not running"));
395
+ return new Promise((resolve, reject) => {
396
+ const { stdin } = this.process;
397
+ const done = (error) => error ? reject(error) : void 0;
398
+ if (stdin.write(serializeMessage(message), done)) resolve();
399
+ else stdin.once("drain", () => resolve());
400
+ });
401
+ }
402
+ close() {
403
+ this.stopping ??= Promise.resolve().then(() => this.process.stop()).then(() => this.finish()).catch((error) => {
404
+ this.stopping = void 0;
405
+ try {
406
+ this.finish();
407
+ } catch (notification) {
408
+ throw new AggregateError([error, notification], "transport stop and close notification failed", { cause: error });
409
+ }
410
+ throw error;
411
+ });
412
+ return this.stopping;
413
+ }
414
+ /** Whether `close()` was asked for, as opposed to the process ending on its own. */
415
+ get stopRequested() {
416
+ return this.stopping !== void 0;
417
+ }
418
+ /** The promise of the stop in progress, if any. */
419
+ get stopped() {
420
+ return this.stopping;
421
+ }
422
+ finish() {
423
+ if (this.closed) return;
424
+ this.closed = true;
425
+ this.buffer.clear();
426
+ this.onclose?.();
427
+ }
428
+ };
429
+ //#endregion
430
+ //#region src/connections.ts
431
+ const TIMING = {
432
+ handshakeMs: 3e4,
433
+ backoffMs: 1e3,
434
+ maxBackoffMs: 3e4,
435
+ maxAttempts: 10,
436
+ stableMs: 3e4,
437
+ concurrency: 4,
438
+ stderrSettleMs: 50
439
+ };
440
+ const UNACKNOWLEDGED = "尚未确认以用户权限运行";
441
+ const CREDENTIAL_UNAVAILABLE = "凭据无法读取,请重新填写";
442
+ const CLIENT_INFO = {
443
+ name: "yaoguang",
444
+ version: "1.0.0"
445
+ };
446
+ var Superseded = class extends Error {};
447
+ function isNeedsAuth(error) {
448
+ const name = error?.name;
449
+ return name === "UnauthorizedError" || name === "NeedsAuthorizationError" || error?.constructor?.name === "UnauthorizedError";
450
+ }
451
+ const messageOf$1 = (error) => error instanceof Error ? error.message : String(error);
452
+ /**
453
+ * One connection per enabled server: the state machine, generations, the
454
+ * start queue, handshake deadline, paged listing, serial snapshot updates,
455
+ * reconnection with backoff, and closing.
456
+ *
457
+ * Every change of configuration, enablement, authorization or credentials
458
+ * bumps the server's generation first; anything that resolves afterwards
459
+ * compares its generation before it writes, registers or changes a status.
460
+ */
461
+ function createConnections(deps) {
462
+ const timing = {
463
+ ...TIMING,
464
+ ...deps.timing
465
+ };
466
+ const connections = /* @__PURE__ */ new Map();
467
+ let closed = false;
468
+ let active = 0;
469
+ /** Attempts and test connections under way; shutdown waits for each. */
470
+ const running = /* @__PURE__ */ new Set();
471
+ /** Transports of attempts and tests not yet live; shutdown closes them so
472
+ * a handshake in progress ends at once rather than at its deadline. */
473
+ const starting = /* @__PURE__ */ new Set();
474
+ const receipts = /* @__PURE__ */ new Set();
475
+ const pendingStops = /* @__PURE__ */ new Map();
476
+ let shuttingDown;
477
+ const track = (work) => {
478
+ running.add(work);
479
+ work.finally(() => running.delete(work)).catch(() => {});
480
+ return work;
481
+ };
482
+ const waiting = [];
483
+ const acquire = async () => {
484
+ if (active < timing.concurrency) {
485
+ active += 1;
486
+ return;
487
+ }
488
+ await new Promise((resolve) => waiting.push(resolve));
489
+ active += 1;
490
+ };
491
+ const release = () => {
492
+ active -= 1;
493
+ waiting.shift()?.();
494
+ };
495
+ const connection = (id) => {
496
+ let found = connections.get(id);
497
+ if (!found) {
498
+ found = {
499
+ id,
500
+ gen: 0,
501
+ status: { state: "disabled" },
502
+ attempts: 0,
503
+ lastStop: Promise.resolve(),
504
+ queue: Promise.resolve(),
505
+ connected: false
506
+ };
507
+ connections.set(id, found);
508
+ }
509
+ return found;
510
+ };
511
+ const setStatus = (conn, status) => {
512
+ conn.status = status;
513
+ deps.onChanged();
514
+ };
515
+ const clearTimers = (conn) => {
516
+ if (conn.retry) clearTimeout(conn.retry);
517
+ if (conn.stable) clearTimeout(conn.stable);
518
+ conn.retry = void 0;
519
+ conn.stable = void 0;
520
+ };
521
+ const stopTransport = (transport, conn) => {
522
+ pendingStops.set(transport, conn);
523
+ const task = Promise.resolve().then(() => transport.close()).then(() => {
524
+ pendingStops.delete(transport);
525
+ });
526
+ conn.lastStop = task;
527
+ task.catch(() => {});
528
+ return task;
529
+ };
530
+ /** Closes the live transport, retaining failed cleanup for the next drain. */
531
+ const drop = (conn) => {
532
+ const live = conn.live;
533
+ conn.live = void 0;
534
+ if (live) stopTransport(live.transport, conn);
535
+ };
536
+ const withdraw = (conn) => {
537
+ if (conn.snapshot === void 0) return;
538
+ conn.snapshot = void 0;
539
+ deps.onSnapshot(conn.id, void 0);
540
+ };
541
+ const publish = (conn, snapshot) => {
542
+ conn.snapshot = snapshot;
543
+ deps.onSnapshot(conn.id, snapshot);
544
+ };
545
+ /** The credential values and transport one attempt uses. Throws a reason.
546
+ * `secrets` answers the values current at the moment it is called. */
547
+ const prepare = async (record, conn, gen) => {
548
+ const current = () => {
549
+ if (closed || conn.gen !== gen) throw new Superseded();
550
+ };
551
+ const read = (name) => deps.credentials.get(record.id, name);
552
+ if (record.transport === "stdio") {
553
+ const used = [];
554
+ const proxy = (await deps.network.environment()).env;
555
+ const env = childEnvironment({
556
+ commands: deps.commands,
557
+ inherited: deps.inherited?.() ?? deps.commands.env,
558
+ proxy,
559
+ config: record.config,
560
+ secret: (name) => {
561
+ const value = read(envCredential(name));
562
+ used.push(value);
563
+ return value;
564
+ }
565
+ });
566
+ const effective = await deps.commands.inspect(record.config.command, deps.commands.environment([env.env, env.configuredEnv]));
567
+ if (effective.status !== "found" || effective.path !== record.config.command) throw new Error(`command-unavailable: ${effective.reason ?? "command-resolution-changed"}`);
568
+ const cwd = await deps.commands.directory(record.config.cwd ?? deps.commands.homedir());
569
+ if (record.config.cwd !== cwd) throw new Error("cwd-changed: acknowledge the resolved directory again");
570
+ current();
571
+ const attempt = deps.processes.start({
572
+ owner: deps.owner,
573
+ argv: [record.config.command, ...record.config.args],
574
+ cwd,
575
+ env: env.env,
576
+ configuredEnv: env.configuredEnv,
577
+ beforeSpawn: current
578
+ });
579
+ receipts.add(attempt);
580
+ conn.lastReceipt = attempt;
581
+ let cleaned = false;
582
+ attempt.cleaned.then(() => {
583
+ cleaned = true;
584
+ receipts.delete(attempt);
585
+ if (conn.failedStart === attempt) conn.failedStart = void 0;
586
+ if (conn.lastReceipt === attempt) conn.lastStop = Promise.resolve();
587
+ });
588
+ let process_;
589
+ let handedOff = false;
590
+ try {
591
+ process_ = await attempt.ready;
592
+ handedOff = true;
593
+ current();
594
+ } catch (primary) {
595
+ let failure = primary;
596
+ if (handedOff) try {
597
+ await attempt.stop();
598
+ } catch (cleanup) {
599
+ failure = new AggregateError([primary, cleanup], "MCP startup cleanup failed", { cause: primary });
600
+ }
601
+ if (!cleaned) {
602
+ conn.failedStart = attempt;
603
+ conn.lastStop = Promise.reject(failure);
604
+ conn.lastStop.catch(() => {});
605
+ }
606
+ throw failure;
607
+ }
608
+ const fixed = secretValues(used);
609
+ return {
610
+ transport: new ProcessTransport(process_),
611
+ secrets: () => fixed,
612
+ process: process_
613
+ };
614
+ }
615
+ const headers = {};
616
+ const used = [];
617
+ if (record.config.auth === "headers") for (const name of record.config.headers) {
618
+ const value = read(headerCredential(name));
619
+ if (value === void 0) throw new MissingCredentialError(`header ${name}`);
620
+ headers[name] = value;
621
+ used.push(value);
622
+ }
623
+ const oauth = record.config.auth === "oauth";
624
+ return {
625
+ transport: httpTransport({
626
+ url: record.config.url,
627
+ fetch: deps.network.fetch,
628
+ headers,
629
+ ...record.config.auth === "oauth" ? { authProvider: deps.oauth.connectionProvider(record.id, record.config.url) } : {}
630
+ }),
631
+ secrets: () => secretValues(oauth ? [...used, ...deps.oauth.secrets(record.id)] : used)
632
+ };
633
+ };
634
+ /** Lists everything the server declared, page by page, in full. */
635
+ const list = async (client, capabilities, options, only, previous) => {
636
+ const pages = async (fetchPage) => {
637
+ const items = [];
638
+ const seen = /* @__PURE__ */ new Set();
639
+ let cursor;
640
+ do {
641
+ const page = await fetchPage(cursor);
642
+ items.push(...page.items);
643
+ cursor = page.nextCursor;
644
+ if (cursor !== void 0) {
645
+ if (seen.has(cursor)) throw new Error("the server repeated a list cursor");
646
+ seen.add(cursor);
647
+ }
648
+ } while (cursor !== void 0);
649
+ return items;
650
+ };
651
+ /** A kind outside `only` keeps what `previous` had; an undeclared one is empty. */
652
+ const read = async (kind, fetchPage) => {
653
+ if (only !== void 0 && only !== kind) return void 0;
654
+ return capabilities[kind] === void 0 ? [] : await pages(fetchPage);
655
+ };
656
+ const next = (cursor) => cursor ? { cursor } : {};
657
+ const tools = await read("tools", async (cursor) => {
658
+ const page = await client.listTools(next(cursor), options);
659
+ return {
660
+ items: page.tools,
661
+ ...page.nextCursor ? { nextCursor: page.nextCursor } : {}
662
+ };
663
+ });
664
+ const resources = await read("resources", async (cursor) => {
665
+ const page = await client.listResources(next(cursor), options);
666
+ return {
667
+ items: page.resources,
668
+ ...page.nextCursor ? { nextCursor: page.nextCursor } : {}
669
+ };
670
+ });
671
+ const prompts = await read("prompts", async (cursor) => {
672
+ const page = await client.listPrompts(next(cursor), options);
673
+ return {
674
+ items: page.prompts,
675
+ ...page.nextCursor ? { nextCursor: page.nextCursor } : {}
676
+ };
677
+ });
678
+ const description = client.getServerVersion()?.description?.trim();
679
+ return {
680
+ ...description ? { description } : {},
681
+ tools: (tools ?? previous?.tools ?? []).map((tool) => ({
682
+ name: tool.name,
683
+ ...tool.description ? { description: tool.description } : {},
684
+ inputSchema: tool.inputSchema
685
+ })),
686
+ resources: (resources ?? previous?.resources ?? []).map((resource) => ({
687
+ uri: resource.uri,
688
+ ...resource.name ? { name: resource.name } : {},
689
+ ...resource.description ? { description: resource.description } : {},
690
+ ...resource.mimeType ? { mimeType: resource.mimeType } : {}
691
+ })),
692
+ prompts: (prompts ?? previous?.prompts ?? []).map((prompt) => ({
693
+ name: prompt.name,
694
+ ...prompt.description ? { description: prompt.description } : {},
695
+ ...prompt.arguments ? { arguments: prompt.arguments } : {}
696
+ }))
697
+ };
698
+ };
699
+ /** Initialize plus the first full listing, inside the handshake deadline. */
700
+ const handshake = async (transport) => {
701
+ const client = new Client(CLIENT_INFO, { capabilities: {} });
702
+ const deadline = new AbortController();
703
+ const timer = setTimeout(() => deadline.abort(), timing.handshakeMs);
704
+ const options = {
705
+ signal: deadline.signal,
706
+ timeout: timing.handshakeMs
707
+ };
708
+ try {
709
+ await client.connect(objectOutputSchemas(transport), options);
710
+ const capabilities = client.getServerCapabilities() ?? {};
711
+ return {
712
+ client,
713
+ capabilities,
714
+ snapshot: await list(client, capabilities, options)
715
+ };
716
+ } catch (error) {
717
+ await client.close().catch(() => {});
718
+ if (deadline.signal.aborted) throw new Error(`handshake timed out after ${Math.round(timing.handshakeMs / 1e3)} s`);
719
+ throw error;
720
+ } finally {
721
+ clearTimeout(timer);
722
+ }
723
+ };
724
+ const stderrReason = async (process_, base) => {
725
+ if (!process_) return base;
726
+ await new Promise((resolve) => setTimeout(resolve, timing.stderrSettleMs));
727
+ const tail = process_.stderrTail().trim();
728
+ return tail ? `${base}: ${tail.slice(-2e3)}` : base;
729
+ };
730
+ const scheduleRetry = (conn, gen, reason) => {
731
+ if (closed || conn.gen !== gen) return;
732
+ conn.attempts += 1;
733
+ if (conn.attempts > timing.maxAttempts) {
734
+ withdraw(conn);
735
+ setStatus(conn, {
736
+ state: "failed",
737
+ reason
738
+ });
739
+ return;
740
+ }
741
+ const delay = Math.min(timing.backoffMs * 2 ** (conn.attempts - 1), timing.maxBackoffMs);
742
+ setStatus(conn, {
743
+ state: "reconnecting",
744
+ reason
745
+ });
746
+ conn.retry = setTimeout(() => {
747
+ conn.retry = void 0;
748
+ attempt(conn, gen);
749
+ }, delay);
750
+ conn.retry.unref?.();
751
+ };
752
+ /** Watches one live connection for an end it did not ask for. */
753
+ const watch = (conn, gen, client, process_, secrets) => {
754
+ client.onclose = () => {
755
+ if (conn.live?.client !== client || conn.gen !== gen || closed) return;
756
+ clearTimers(conn);
757
+ drop(conn);
758
+ stderrReason(process_, process_ ? "server process exited" : "connection closed").then((reason) => {
759
+ if (closed || conn.gen !== gen) return;
760
+ scheduleRetry(conn, gen, redactReason(reason, secrets()));
761
+ });
762
+ };
763
+ const refresh = (kind) => () => {
764
+ conn.queue = conn.queue.then(async () => {
765
+ const live = conn.live;
766
+ if (!live || live.client !== client || conn.gen !== gen) return;
767
+ try {
768
+ const next = await list(client, live.capabilities, { timeout: timing.handshakeMs }, kind, conn.snapshot);
769
+ if (conn.live?.client !== client || conn.gen !== gen) return;
770
+ publish(conn, next);
771
+ deps.onChanged();
772
+ } catch (error) {
773
+ if (closed || conn.gen !== gen) return;
774
+ deps.log.warn(`refreshing ${kind} of MCP server ${conn.id} failed: ${redact(messageOf$1(error), secrets())}`);
775
+ }
776
+ });
777
+ };
778
+ client.setNotificationHandler(ToolListChangedNotificationSchema, refresh("tools"));
779
+ client.setNotificationHandler(ResourceListChangedNotificationSchema, refresh("resources"));
780
+ client.setNotificationHandler(PromptListChangedNotificationSchema, refresh("prompts"));
781
+ };
782
+ /** One connection attempt within generation `gen`, tracked for shutdown. */
783
+ const attempt = (conn, gen) => track(attemptOnce(conn, gen));
784
+ const attemptOnce = async (conn, gen) => {
785
+ if (closed || conn.gen !== gen) return;
786
+ const record = deps.store.server(conn.id);
787
+ if (!record) return;
788
+ await acquire();
789
+ let prepared;
790
+ try {
791
+ try {
792
+ await conn.lastStop;
793
+ } catch {
794
+ if (conn.gen !== gen) return;
795
+ withdraw(conn);
796
+ setStatus(conn, {
797
+ state: "failed",
798
+ reason: "the previous server process could not be stopped"
799
+ });
800
+ return;
801
+ }
802
+ if (conn.gen !== gen || closed) return;
803
+ prepared = await prepare(record, conn, gen);
804
+ starting.add(prepared.transport);
805
+ if (conn.gen !== gen || closed) throw new Superseded();
806
+ const { client, capabilities, snapshot } = await handshake(prepared.transport);
807
+ if (conn.gen !== gen || closed) {
808
+ await client.close().catch(() => {});
809
+ throw new Superseded();
810
+ }
811
+ const secretsOf = prepared.secrets;
812
+ conn.live = {
813
+ client,
814
+ transport: prepared.transport,
815
+ capabilities,
816
+ get secrets() {
817
+ return secretsOf();
818
+ }
819
+ };
820
+ conn.connected = true;
821
+ watch(conn, gen, client, prepared.process, prepared.secrets);
822
+ publish(conn, snapshot);
823
+ setStatus(conn, { state: "connected" });
824
+ conn.stable = setTimeout(() => {
825
+ conn.stable = void 0;
826
+ if (conn.gen === gen) conn.attempts = 0;
827
+ }, timing.stableMs);
828
+ conn.stable.unref?.();
829
+ } catch (error) {
830
+ if (prepared && conn.live?.transport !== prepared.transport) stopTransport(prepared.transport, conn);
831
+ if (error instanceof Superseded || conn.gen !== gen || closed) return;
832
+ const secrets = prepared?.secrets() ?? [];
833
+ if (isNeedsAuth(error)) {
834
+ withdraw(conn);
835
+ setStatus(conn, {
836
+ state: "needs-auth",
837
+ reason: redactReason(messageOf$1(error), secrets)
838
+ });
839
+ return;
840
+ }
841
+ if (error?.name === "CredentialUnavailableError") {
842
+ withdraw(conn);
843
+ setStatus(conn, {
844
+ state: "failed",
845
+ reason: CREDENTIAL_UNAVAILABLE
846
+ });
847
+ return;
848
+ }
849
+ const reason = redactReason(await stderrReason(prepared?.process, messageOf$1(error)), secrets);
850
+ if (conn.gen !== gen || closed) return;
851
+ if (conn.connected && !(error instanceof MissingCredentialError)) {
852
+ scheduleRetry(conn, gen, reason);
853
+ return;
854
+ }
855
+ withdraw(conn);
856
+ setStatus(conn, {
857
+ state: "failed",
858
+ reason
859
+ });
860
+ } finally {
861
+ if (prepared) starting.delete(prepared.transport);
862
+ release();
863
+ }
864
+ };
865
+ /** Brings one server's connection in line with its stored record.
866
+ * Returns the initial attempt when an enabled server can connect. */
867
+ const reconcile = (id, options = {}) => {
868
+ if (closed) return;
869
+ const conn = connection(id);
870
+ conn.gen += 1;
871
+ conn.attempts = 0;
872
+ conn.connected = false;
873
+ clearTimers(conn);
874
+ drop(conn);
875
+ const record = deps.store.server(id);
876
+ if (!record) {
877
+ withdraw(conn);
878
+ connections.delete(id);
879
+ deps.onChanged();
880
+ return;
881
+ }
882
+ if (!record.enabled) {
883
+ withdraw(conn);
884
+ setStatus(conn, { state: "disabled" });
885
+ return;
886
+ }
887
+ if (record.transport === "stdio" && record.acknowledgedAt === null) {
888
+ withdraw(conn);
889
+ setStatus(conn, {
890
+ state: "failed",
891
+ reason: UNACKNOWLEDGED
892
+ });
893
+ return;
894
+ }
895
+ if (record.transport === "http" && record.config.auth === "oauth") {
896
+ let authorized;
897
+ try {
898
+ authorized = deps.oauth.hasTokens(id);
899
+ } catch {
900
+ withdraw(conn);
901
+ setStatus(conn, {
902
+ state: "failed",
903
+ reason: CREDENTIAL_UNAVAILABLE
904
+ });
905
+ return;
906
+ }
907
+ if (!authorized) {
908
+ withdraw(conn);
909
+ setStatus(conn, { state: "needs-auth" });
910
+ return;
911
+ }
912
+ }
913
+ if (!options.keepSnapshot) withdraw(conn);
914
+ setStatus(conn, { state: "connecting" });
915
+ return attempt(conn, conn.gen);
916
+ };
917
+ /** The work of `test`, untracked. */
918
+ const testOnce = async (id) => {
919
+ if (closed) return {
920
+ ok: false,
921
+ reason: "the plugin is stopping"
922
+ };
923
+ const record = deps.store.server(id);
924
+ if (!record) return {
925
+ ok: false,
926
+ reason: "no such server"
927
+ };
928
+ if (record.transport === "stdio" && record.acknowledgedAt === null) return {
929
+ ok: false,
930
+ reason: UNACKNOWLEDGED
931
+ };
932
+ const conn = connection(id);
933
+ const gen = conn.gen;
934
+ const count = (snapshot) => ({
935
+ ok: true,
936
+ tools: snapshot.tools.length,
937
+ resources: snapshot.resources.length,
938
+ prompts: snapshot.prompts.length
939
+ });
940
+ if (conn?.live && conn.status.state === "connected") {
941
+ const live = conn.live;
942
+ try {
943
+ const snapshot = await list(live.client, live.capabilities, { timeout: timing.handshakeMs });
944
+ if (closed || conn.gen !== gen || conn.live !== live) return {
945
+ ok: false,
946
+ reason: "the connection changed during testing"
947
+ };
948
+ publish(conn, snapshot);
949
+ deps.onChanged();
950
+ return count(snapshot);
951
+ } catch (error) {
952
+ const reason = redactReason(messageOf$1(error), live.secrets);
953
+ if (!closed && conn.gen === gen && conn.live === live) {
954
+ conn.gen += 1;
955
+ clearTimers(conn);
956
+ drop(conn);
957
+ withdraw(conn);
958
+ setStatus(conn, {
959
+ state: isNeedsAuth(error) ? "needs-auth" : "failed",
960
+ reason
961
+ });
962
+ }
963
+ return {
964
+ ok: false,
965
+ reason
966
+ };
967
+ }
968
+ }
969
+ if (record.enabled) {
970
+ const attempt = reconcile(id, { keepSnapshot: true });
971
+ const testingGen = conn.gen;
972
+ await attempt;
973
+ if (closed) return {
974
+ ok: false,
975
+ reason: "the plugin is stopping"
976
+ };
977
+ if (conn.gen !== testingGen) return {
978
+ ok: false,
979
+ reason: "the connection changed during testing"
980
+ };
981
+ if (conn.status.state === "connected" && conn.live && conn.snapshot) return count(conn.snapshot);
982
+ return {
983
+ ok: false,
984
+ reason: conn.status.reason ?? "the server is not connected"
985
+ };
986
+ }
987
+ let prepared;
988
+ try {
989
+ if (closed) return {
990
+ ok: false,
991
+ reason: "the plugin is stopping"
992
+ };
993
+ await conn.lastStop;
994
+ prepared = await prepare(record, conn, gen);
995
+ starting.add(prepared.transport);
996
+ if (closed) throw new Error("the plugin is stopping");
997
+ const { client, snapshot } = await handshake(prepared.transport);
998
+ await client.close().catch(() => {});
999
+ return count(snapshot);
1000
+ } catch (error) {
1001
+ if (error?.name === "CredentialUnavailableError") return {
1002
+ ok: false,
1003
+ reason: CREDENTIAL_UNAVAILABLE
1004
+ };
1005
+ const reason = await stderrReason(prepared?.process, messageOf$1(error));
1006
+ if (closed) return {
1007
+ ok: false,
1008
+ reason: "the plugin is stopping"
1009
+ };
1010
+ return {
1011
+ ok: false,
1012
+ reason: redact(reason, prepared?.secrets() ?? [])
1013
+ };
1014
+ } finally {
1015
+ if (prepared) starting.delete(prepared.transport);
1016
+ if (prepared) await stopTransport(prepared.transport, conn).catch(() => {});
1017
+ }
1018
+ };
1019
+ return {
1020
+ /** Starts every stored server in the background; returns at once. */
1021
+ boot() {
1022
+ for (const record of deps.store.servers()) reconcile(record.id);
1023
+ },
1024
+ reconcile,
1025
+ status(id) {
1026
+ return connections.get(id)?.status ?? { state: "disabled" };
1027
+ },
1028
+ snapshot(id) {
1029
+ return connections.get(id)?.snapshot;
1030
+ },
1031
+ /** The live connection, or `undefined` while not connected. */
1032
+ live(id) {
1033
+ const conn = connections.get(id);
1034
+ return conn?.status.state === "connected" ? conn.live : void 0;
1035
+ },
1036
+ /** A call learned the server wants authorization again. */
1037
+ needsAuth(id, reason) {
1038
+ const conn = connections.get(id);
1039
+ if (!conn || closed) return;
1040
+ conn.gen += 1;
1041
+ clearTimers(conn);
1042
+ drop(conn);
1043
+ withdraw(conn);
1044
+ setStatus(conn, {
1045
+ state: "needs-auth",
1046
+ ...reason ? { reason } : {}
1047
+ });
1048
+ },
1049
+ /**
1050
+ * Lists capabilities: through the live connection when there is one,
1051
+ * otherwise restores the enabled server's resident connection and status.
1052
+ * Disabled servers use a temporary connection closed before this returns.
1053
+ */
1054
+ test(id) {
1055
+ return track(testOnce(id));
1056
+ },
1057
+ /** Closes every connection and stops reconnecting; settles once every
1058
+ * process group this plugin started has been stopped, including those of
1059
+ * handshakes and test connections still under way. */
1060
+ shutdown() {
1061
+ closed = true;
1062
+ shuttingDown ??= Promise.resolve().then(async () => {
1063
+ const stops = [];
1064
+ const stopped = /* @__PURE__ */ new Set();
1065
+ for (const conn of connections.values()) {
1066
+ conn.gen += 1;
1067
+ clearTimers(conn);
1068
+ drop(conn);
1069
+ }
1070
+ for (const [transport, conn] of pendingStops) stops.push(stopTransport(transport, conn));
1071
+ for (const transport of starting) stops.push(transport.close());
1072
+ for (const receipt of receipts) {
1073
+ stopped.add(receipt);
1074
+ stops.push(receipt.stop());
1075
+ }
1076
+ const initialStops = Promise.allSettled(stops);
1077
+ await Promise.allSettled([...running]);
1078
+ const lateStops = [];
1079
+ for (const receipt of receipts) if (!stopped.has(receipt)) lateStops.push(receipt.stop());
1080
+ const results = (await Promise.all([initialStops, Promise.allSettled(lateStops)])).flat();
1081
+ results.push(...await Promise.allSettled([...connections.values()].map((conn) => conn.lastStop)));
1082
+ const failures = results.filter((result) => result.status === "rejected");
1083
+ if (failures.length) throw new AggregateError(failures.map((result) => result.reason), "cleanup-failed");
1084
+ }).catch((error) => {
1085
+ shuttingDown = void 0;
1086
+ throw error;
1087
+ });
1088
+ return shuttingDown;
1089
+ },
1090
+ /** Whether the stored stdio configuration carries a confirmation that
1091
+ * still matches it. */
1092
+ acknowledged(record, previous) {
1093
+ if (record.transport !== "stdio" || !previous || previous.transport !== "stdio") return false;
1094
+ return previous.acknowledgedAt !== null && acknowledgementKey(previous.config, deps.commands.platform) === acknowledgementKey(record.config, deps.commands.platform);
1095
+ }
1096
+ };
1097
+ }
1098
+ //#endregion
1099
+ //#region src/management.ts
1100
+ /**
1101
+ * Validates and saves one server, optionally selecting a new one for an agent.
1102
+ * Rejects edits whose captured server changed during asynchronous command resolution.
1103
+ */
1104
+ async function saveServer(deps, input, selectFor, ctx) {
1105
+ const { store, connections, tools, oauth } = deps;
1106
+ checkSlug(input.slug);
1107
+ const previous = input.id === void 0 ? void 0 : store.server(input.id);
1108
+ if (input.id && !previous) throw new Error("no such MCP server");
1109
+ if (previous && previous.slug !== input.slug) throw new Error("a slug cannot be changed");
1110
+ const taken = store.serverBySlug(input.slug);
1111
+ if (taken && taken.id !== previous?.id) throw new Error(`slug "${input.slug}" is already used`);
1112
+ const id = previous?.id ?? randomUUID();
1113
+ const base = {
1114
+ id,
1115
+ slug: input.slug,
1116
+ name: input.name,
1117
+ enabled: previous?.enabled ?? true,
1118
+ createdAt: previous?.createdAt ?? Date.now()
1119
+ };
1120
+ let record;
1121
+ if (input.transport === "stdio") {
1122
+ const draft = {
1123
+ ...base,
1124
+ transport: "stdio",
1125
+ config: await resolveStdioConfig(input.config, deps.commands),
1126
+ acknowledgedAt: null
1127
+ };
1128
+ const kept = connections.acknowledged(draft, previous);
1129
+ if (!kept && input.acknowledge !== true) throw new Error("stdio servers must be acknowledged before saving");
1130
+ record = {
1131
+ ...draft,
1132
+ acknowledgedAt: kept && previous?.transport === "stdio" ? previous.acknowledgedAt : Date.now()
1133
+ };
1134
+ } else record = {
1135
+ ...base,
1136
+ transport: "http",
1137
+ config: input.config,
1138
+ acknowledgedAt: null
1139
+ };
1140
+ if (previous && !isDeepStrictEqual(previous, store.server(previous.id))) throw new Error("MCP server changed while saving; reload before retrying");
1141
+ if (selectFor && previous) throw new Error("initial selection requires a new server");
1142
+ if (selectFor) deps.agentConfig.save([selectFor.agentId], () => store.createSelectedServer(record, selectFor.agentId, selectFor.selected), ctx);
1143
+ else store.saveServer(record);
1144
+ 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);
1145
+ if (!previous || previous.transport !== record.transport || JSON.stringify(previous.config) !== JSON.stringify(record.config) || previous.acknowledgedAt !== record.acknowledgedAt) connections.reconcile(id);
1146
+ else if (previous.name !== record.name) tools.apply(id, connections.snapshot(id));
1147
+ deps.announce();
1148
+ if (selectFor?.selected) deps.selectionChanged(selectFor.agentId);
1149
+ return record;
1150
+ }
1151
+ /** Changes one agent's selection while leaving the global server state intact. */
1152
+ function selectServer(deps, agentId, serverId, selected, ctx) {
1153
+ if (!deps.store.server(serverId)) throw new Error("no such MCP server");
1154
+ deps.agentConfig.save([agentId], () => deps.store.setServerSelected(agentId, serverId, selected), ctx);
1155
+ deps.selectionChanged(agentId);
1156
+ deps.announce();
1157
+ }
1158
+ //#endregion
1159
+ //#region src/tool-names.ts
1160
+ /** Canonical names shared by tool registration and browser presentation. */
1161
+ const TOOL_NAMES = [
1162
+ "mcp_server_list",
1163
+ "mcp_server_create",
1164
+ "mcp_server_update",
1165
+ "mcp_server_set_selected"
1166
+ ];
1167
+ //#endregion
1168
+ //#region src/management-tools.ts
1169
+ /** Strict plugin configuration for individually disabling management tools. */
1170
+ const McpConfig = z.object({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).strict().default({ disabled: [] });
1171
+ const ListInput = z.object({ serverId: z.string().uuid().optional() }).strict();
1172
+ /** One server's creation, `transport` paired with its own `config`. */
1173
+ const CreatePaired = z.discriminatedUnion("transport", [z.object({
1174
+ slug: z.string(),
1175
+ name: z.string().trim().min(1).max(80),
1176
+ transport: z.literal("stdio"),
1177
+ config: StdioConfigSchema,
1178
+ select: z.boolean().default(true)
1179
+ }).strict(), z.object({
1180
+ slug: z.string(),
1181
+ name: z.string().trim().min(1).max(80),
1182
+ transport: z.literal("http"),
1183
+ config: HttpConfigSchema,
1184
+ select: z.boolean().default(true)
1185
+ }).strict()]);
1186
+ /** The parameters as the model sees them: one object, because an
1187
+ * OpenAI-compatible endpoint refuses a tool whose top level is not
1188
+ * `type: "object"`. The pairing `CreatePaired` states is checked here. */
1189
+ const Create = z.object({
1190
+ slug: z.string(),
1191
+ name: z.string().trim().min(1).max(80),
1192
+ transport: z.enum(["stdio", "http"]),
1193
+ config: z.union([StdioConfigSchema, HttpConfigSchema]),
1194
+ select: z.boolean().default(true)
1195
+ }).strict().superRefine((value, ctx) => {
1196
+ if (!CreatePaired.safeParse(value).success) ctx.addIssue({
1197
+ code: "custom",
1198
+ path: ["config"],
1199
+ message: `config does not match transport ${value.transport}`
1200
+ });
1201
+ });
1202
+ const Update = z.object({
1203
+ serverId: z.string().uuid(),
1204
+ name: z.string().trim().min(1).max(80).optional(),
1205
+ config: z.union([StdioConfigSchema, HttpConfigSchema]).optional(),
1206
+ expectedRevision: z.string().optional()
1207
+ }).strict().refine((value) => value.name !== void 0 || value.config !== void 0, "a change is required");
1208
+ const Select = z.object({
1209
+ serverId: z.string().uuid(),
1210
+ selected: z.boolean()
1211
+ }).strict();
1212
+ const revisionOf = (record) => createHash("sha256").update(JSON.stringify(record)).digest("hex");
1213
+ const fail = (code, message) => {
1214
+ throw Object.assign(new Error(message), { code });
1215
+ };
1216
+ /** Registers the five model-facing management tools. */
1217
+ function registerMcpManagementTools(deps) {
1218
+ const { store, connections, credentials, oauth } = deps;
1219
+ const requireServer = (serverId) => {
1220
+ const record = store.server(serverId);
1221
+ if (!record) throw new Error("no such MCP server");
1222
+ return record;
1223
+ };
1224
+ const requireSelected = (serverId, agentId) => {
1225
+ const record = requireServer(serverId);
1226
+ if (!store.isSelected(agentId, serverId)) throw new Error("this server is not selected by this agent");
1227
+ return record;
1228
+ };
1229
+ const secretsOf = (serverId) => {
1230
+ return secretValues([...credentials.list(serverId).filter((status) => status.set).map((status) => credentials.get(serverId, status.name)), ...oauth.secrets(serverId)]);
1231
+ };
1232
+ const allSecrets = () => secretValues(store.servers().flatMap((record) => secretsOf(record.id)));
1233
+ const sanitize = (value, secrets) => {
1234
+ if (typeof value === "string") return redact(value, secrets);
1235
+ if (Array.isArray(value)) return value.map((item) => sanitize(item, secrets));
1236
+ if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sanitize(item, secrets)]));
1237
+ return value;
1238
+ };
1239
+ const safeConfig = (record) => sanitize(record.config, allSecrets());
1240
+ const changedExecutionParty = (before, after) => {
1241
+ if (before.transport !== after.transport) return true;
1242
+ return before.transport === "stdio" && after.transport === "stdio" ? JSON.stringify([
1243
+ before.config.command,
1244
+ before.config.args,
1245
+ before.config.cwd
1246
+ ]) !== JSON.stringify([
1247
+ after.config.command,
1248
+ after.config.args,
1249
+ after.config.cwd
1250
+ ]) : before.transport === "http" && after.transport === "http" && JSON.stringify([before.config.url, before.config.auth]) !== JSON.stringify([after.config.url, after.config.auth]);
1251
+ };
1252
+ 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);
1253
+ const containsKnownSecret = (value, secrets) => {
1254
+ if (typeof value === "string") return secrets.some((secret) => value.includes(secret));
1255
+ if (Array.isArray(value)) return value.some((item) => containsKnownSecret(item, secrets));
1256
+ return value !== null && typeof value === "object" && Object.values(value).some((item) => containsKnownSecret(item, secrets));
1257
+ };
1258
+ const readResult = (data) => ({ content: JSON.stringify({
1259
+ status: "ok",
1260
+ data
1261
+ }) });
1262
+ const listServers = (agentId) => {
1263
+ const knownSecrets = allSecrets();
1264
+ return readResult({ servers: store.servers().map((record) => sanitize({
1265
+ id: record.id,
1266
+ slug: record.slug,
1267
+ name: record.name,
1268
+ transport: record.transport,
1269
+ enabled: record.enabled,
1270
+ selected: store.isSelected(agentId, record.id),
1271
+ connectionState: connections.status(record.id).state
1272
+ }, knownSecrets)) });
1273
+ };
1274
+ const serverDetail = (serverId, agentId) => {
1275
+ try {
1276
+ const record = requireSelected(serverId, agentId);
1277
+ return readResult(sanitize({
1278
+ id: record.id,
1279
+ slug: record.slug,
1280
+ name: record.name,
1281
+ transport: record.transport,
1282
+ enabled: record.enabled,
1283
+ config: safeConfig(record),
1284
+ revision: revisionOf(record),
1285
+ agentIds: store.agentsOf(serverId),
1286
+ credentials: credentials.list(serverId).map(({ name, set }) => ({
1287
+ name,
1288
+ set
1289
+ })),
1290
+ connectionState: connections.status(serverId).state,
1291
+ ...record.transport === "http" && record.config.auth === "oauth" ? { oauthAuthorized: oauth.status(serverId).authorized } : {}
1292
+ }, allSecrets()));
1293
+ } catch (cause) {
1294
+ return {
1295
+ content: JSON.stringify({
1296
+ status: "failed",
1297
+ code: cause?.name === "CredentialUnavailableError" ? "credential-unavailable" : "not-found",
1298
+ summary: "MCP server details are unavailable."
1299
+ }),
1300
+ isError: true
1301
+ };
1302
+ }
1303
+ };
1304
+ deps.register({
1305
+ name: "mcp_server_list",
1306
+ description: "List configured MCP servers and whether this agent selects each one. With `serverId`, read the safe configuration and credential status of one server this agent selects instead.",
1307
+ inputSchema: ListInput,
1308
+ async execute({ serverId }, ctx) {
1309
+ const agentId = deps.definitions.read(ctx).agentId;
1310
+ return serverId === void 0 ? listServers(agentId) : serverDetail(serverId, agentId);
1311
+ }
1312
+ });
1313
+ deps.register({
1314
+ name: "mcp_server_create",
1315
+ description: "Create an MCP server and optionally select it for this agent after approval.",
1316
+ inputSchema: Create,
1317
+ async execute(fields, ctx) {
1318
+ let input = CreatePaired.parse(fields);
1319
+ const agentId = deps.definitions.read(ctx).agentId;
1320
+ checkSlug(input.slug);
1321
+ if (containsKnownSecret(input, allSecrets())) fail("invalid-input", "Configuration contains a stored credential");
1322
+ if (input.transport === "stdio") input = {
1323
+ ...input,
1324
+ config: await resolveStdioConfig(input.config, deps.management.commands)
1325
+ };
1326
+ if (store.serverBySlug(input.slug)) fail("conflict", "MCP server slug is already used");
1327
+ const id = `create-${createHash("sha256").update(JSON.stringify(input)).digest("hex")}`;
1328
+ if (ctx.answer && !ctx.answer.answers.some((answer) => answer.questionId === deps.approval.questionId(id))) fail("conflict", "Approved input has changed");
1329
+ const decision = deps.approval.decide(ctx, {
1330
+ id,
1331
+ subject: `Create MCP server ${input.name}`,
1332
+ reason: JSON.stringify(input),
1333
+ warning: input.transport === "stdio" ? "The command runs outside a sandbox." : "This server may receive tool inputs.",
1334
+ accepts: [
1335
+ "allowed-once",
1336
+ "allowed-session",
1337
+ "allowed-always",
1338
+ "rejected"
1339
+ ],
1340
+ remember: {
1341
+ key: "mcp-server-create",
1342
+ label: "Create MCP servers"
1343
+ }
1344
+ });
1345
+ if (decision.kind === "ask") return decision.result;
1346
+ if (!decision.result.kind.startsWith("allowed-")) return {
1347
+ content: "MCP creation was not approved.",
1348
+ isError: true
1349
+ };
1350
+ const record = await saveServer(deps.management, {
1351
+ ...input,
1352
+ acknowledge: true
1353
+ }, {
1354
+ agentId,
1355
+ selected: input.select
1356
+ }, ctx);
1357
+ return readResult({
1358
+ serverId: record.id,
1359
+ selected: input.select,
1360
+ summary: "Configuration saved; connection status is reported separately."
1361
+ });
1362
+ }
1363
+ });
1364
+ deps.register({
1365
+ name: "mcp_server_update",
1366
+ description: "Update a selected shared MCP server after approval.",
1367
+ inputSchema: Update,
1368
+ async execute(input, ctx) {
1369
+ const agentId = deps.definitions.read(ctx).agentId;
1370
+ const previous = requireSelected(input.serverId, agentId);
1371
+ const revision = revisionOf(previous);
1372
+ if (input.expectedRevision && input.expectedRevision !== revision) fail("conflict", "MCP server changed");
1373
+ let config = previous.transport === "stdio" ? StdioConfigSchema.parse(input.config ?? previous.config) : HttpConfigSchema.parse(input.config ?? previous.config);
1374
+ if (containsKnownSecret(input, allSecrets())) fail("invalid-input", "Configuration contains a stored credential");
1375
+ if (previous.transport === "stdio") config = await resolveStdioConfig(StdioConfigSchema.parse(config), deps.management.commands);
1376
+ const next = {
1377
+ ...previous,
1378
+ name: input.name ?? previous.name,
1379
+ config
1380
+ };
1381
+ if (credentialRebind(previous, next)) fail("credential-rebind-required", "Stored credentials require a person to rebind this server");
1382
+ if (JSON.stringify(next) === JSON.stringify(previous)) return readResult({ summary: "Configuration is unchanged." });
1383
+ const id = `update-${createHash("sha256").update(JSON.stringify([
1384
+ revision,
1385
+ input,
1386
+ store.agentsOf(previous.id)
1387
+ ])).digest("hex")}`;
1388
+ if (ctx.answer && !ctx.answer.answers.some((answer) => answer.questionId === deps.approval.questionId(id))) fail("conflict", "MCP configuration changed since approval");
1389
+ const decision = deps.approval.decide(ctx, {
1390
+ id,
1391
+ subject: `Update MCP server ${redact(previous.name, allSecrets())}`,
1392
+ reason: JSON.stringify({
1393
+ before: safeConfig(previous),
1394
+ after: safeConfig(next),
1395
+ agents: store.agentsOf(previous.id)
1396
+ }),
1397
+ accepts: [
1398
+ "allowed-once",
1399
+ "allowed-session",
1400
+ "allowed-always",
1401
+ "rejected"
1402
+ ],
1403
+ remember: {
1404
+ key: "mcp-server-update",
1405
+ label: "Update selected MCP servers"
1406
+ }
1407
+ });
1408
+ if (decision.kind === "ask") return decision.result;
1409
+ if (!decision.result.kind.startsWith("allowed-")) return {
1410
+ content: "MCP update was not approved.",
1411
+ isError: true
1412
+ };
1413
+ const record = await saveServer(deps.management, {
1414
+ id: previous.id,
1415
+ slug: previous.slug,
1416
+ name: next.name,
1417
+ transport: previous.transport,
1418
+ config,
1419
+ acknowledge: true
1420
+ });
1421
+ return readResult({
1422
+ serverId: record.id,
1423
+ revision: revisionOf(record),
1424
+ summary: "Configuration saved; connection status is reported separately."
1425
+ });
1426
+ }
1427
+ });
1428
+ deps.register({
1429
+ name: "mcp_server_set_selected",
1430
+ description: "Select or unselect an MCP server for this agent after approval.",
1431
+ inputSchema: Select,
1432
+ async execute(input, ctx) {
1433
+ const agentId = deps.definitions.read(ctx).agentId;
1434
+ const record = requireServer(input.serverId);
1435
+ const selected = store.isSelected(agentId, record.id);
1436
+ if (selected === input.selected) return readResult({
1437
+ serverId: record.id,
1438
+ selected
1439
+ });
1440
+ const id = `select-${createHash("sha256").update(JSON.stringify([
1441
+ revisionOf(record),
1442
+ store.agentServers(agentId),
1443
+ input
1444
+ ])).digest("hex")}`;
1445
+ if (ctx.answer && !ctx.answer.answers.some((answer) => answer.questionId === deps.approval.questionId(id))) fail("conflict", "MCP selection changed since approval");
1446
+ const decision = deps.approval.decide(ctx, {
1447
+ id,
1448
+ subject: `${input.selected ? "Select" : "Unselect"} MCP server ${redact(record.name, allSecrets())}`,
1449
+ reason: "Change this agent’s MCP tools for subsequent steps.",
1450
+ accepts: [
1451
+ "allowed-once",
1452
+ "allowed-session",
1453
+ "allowed-always",
1454
+ "rejected"
1455
+ ],
1456
+ remember: {
1457
+ key: "mcp-server-select",
1458
+ label: "Select MCP servers"
1459
+ }
1460
+ });
1461
+ if (decision.kind === "ask") return decision.result;
1462
+ if (!decision.result.kind.startsWith("allowed-")) return {
1463
+ content: "MCP selection was not approved.",
1464
+ isError: true
1465
+ };
1466
+ selectServer(deps.management, agentId, record.id, input.selected, ctx);
1467
+ return readResult({
1468
+ serverId: record.id,
1469
+ selected: input.selected,
1470
+ summary: "Selection saved; tools change at the next model step."
1471
+ });
1472
+ }
1473
+ });
1474
+ }
1475
+ //#endregion
1476
+ //#region src/command-paste.ts
1477
+ /** Executable-field paste rules follow the resident physical host. */
1478
+ /** Preserves raw absolute executable-field pastes; other input uses direct host argv grammar. */
1479
+ function parseCommandPaste(text, commands) {
1480
+ if (!text || /[\0\r\n]/.test(text)) throw new Error("invalid-command-text");
1481
+ const windows = commands.platform === "win32";
1482
+ return (windows ? win32.isAbsolute(text) && /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(text) : posix.isAbsolute(text)) ? {
1483
+ file: text,
1484
+ args: [],
1485
+ syntax: windows ? "windows-argv" : "posix-argv"
1486
+ } : commands.parseCommand(text);
1487
+ }
1488
+ //#endregion
1489
+ //#region src/command-text.ts
1490
+ /** Shared command-paste input bounds for the owner RPC and browser editor. */
1491
+ const COMMAND_TEXT_LIMIT = 65536;
1492
+ /** Checks the UTF-8 byte limit before command text crosses the authenticated connection. */
1493
+ function commandTextFits(text) {
1494
+ return new TextEncoder().encode(text).length <= COMMAND_TEXT_LIMIT;
1495
+ }
1496
+ //#endregion
1497
+ //#region src/methods.ts
1498
+ const StatusSchema = z.object({
1499
+ state: z.enum([
1500
+ "disabled",
1501
+ "connecting",
1502
+ "connected",
1503
+ "needs-auth",
1504
+ "reconnecting",
1505
+ "failed"
1506
+ ]),
1507
+ reason: z.string().optional()
1508
+ }).strict();
1509
+ const ServerSummarySchema = z.object({
1510
+ id: z.string(),
1511
+ slug: z.string(),
1512
+ name: z.string(),
1513
+ transport: z.enum(["stdio", "http"]),
1514
+ enabled: z.boolean(),
1515
+ status: StatusSchema,
1516
+ agentIds: z.array(z.string())
1517
+ }).strict();
1518
+ /** One named input of a tool or a prompt, as a settings page lists it. */
1519
+ const ParameterSchema = z.object({
1520
+ name: z.string(),
1521
+ type: z.string().optional(),
1522
+ required: z.boolean(),
1523
+ description: z.string().optional()
1524
+ }).strict();
1525
+ const CatalogEntrySchema = z.object({
1526
+ name: z.string(),
1527
+ uri: z.string().optional(),
1528
+ description: z.string().optional(),
1529
+ mimeType: z.string().optional(),
1530
+ parameters: z.array(ParameterSchema).optional(),
1531
+ refused: z.string().optional()
1532
+ }).strict();
1533
+ const ServerDetailSchema = ServerSummarySchema.extend({
1534
+ description: z.string().optional(),
1535
+ config: z.union([StdioConfigSchema, HttpConfigSchema]),
1536
+ acknowledged: z.boolean(),
1537
+ catalog: z.object({
1538
+ tools: z.array(z.object({
1539
+ name: z.string(),
1540
+ mappedName: z.string(),
1541
+ description: z.string().optional(),
1542
+ parameters: z.array(ParameterSchema),
1543
+ refused: z.string().optional()
1544
+ }).strict()),
1545
+ resources: z.array(CatalogEntrySchema),
1546
+ prompts: z.array(CatalogEntrySchema)
1547
+ }).strict().nullable(),
1548
+ oauth: z.object({
1549
+ authorized: z.boolean(),
1550
+ expiresAt: z.number().optional()
1551
+ }).strict().nullable()
1552
+ }).strict();
1553
+ const Id = z.object({ id: z.string() }).strict();
1554
+ const Agent = z.object({ agentId: z.string().min(1) }).strict();
1555
+ const ServerList = z.object({ servers: z.array(ServerSummarySchema) }).strict();
1556
+ const Text = z.object({ text: z.string() }).strict();
1557
+ const Empty = z.object({}).strict();
1558
+ const PromptEntrySchema = z.object({
1559
+ serverId: z.string(),
1560
+ slug: z.string(),
1561
+ serverName: z.string(),
1562
+ name: z.string(),
1563
+ description: z.string().optional(),
1564
+ arguments: z.array(z.object({
1565
+ name: z.string(),
1566
+ description: z.string().optional(),
1567
+ required: z.boolean().optional()
1568
+ }).strict()).optional()
1569
+ }).strict();
1570
+ const ResourceEntrySchema = z.object({
1571
+ serverId: z.string(),
1572
+ serverName: z.string(),
1573
+ uri: z.string(),
1574
+ name: z.string().optional(),
1575
+ description: z.string().optional()
1576
+ }).strict();
1577
+ const TestResultSchema = z.union([z.object({
1578
+ ok: z.literal(true),
1579
+ tools: z.number(),
1580
+ resources: z.number(),
1581
+ prompts: z.number()
1582
+ }).strict(), z.object({
1583
+ ok: z.literal(false),
1584
+ reason: z.string()
1585
+ }).strict()]);
1586
+ /** The longest server-written description a page is sent. */
1587
+ const DESCRIPTION_LIMIT = 2048;
1588
+ /** The most inputs listed for one tool or prompt. */
1589
+ const PARAMETER_LIMIT = 64;
1590
+ /**
1591
+ * A tool's inputs read off its JSON Schema: the top-level properties, in the
1592
+ * order the server wrote them, each with its type, whether `required` names it
1593
+ * and its own description. Nothing deeper — a settings page answers what the
1594
+ * tool asks for, and the model is the one handed the whole schema.
1595
+ */
1596
+ function schemaParameters(schema, shown) {
1597
+ const properties = schema?.properties;
1598
+ if (!properties || typeof properties !== "object") return [];
1599
+ const required = new Set(Array.isArray(schema?.required) ? schema.required.filter((name) => typeof name === "string") : []);
1600
+ return Object.entries(properties).slice(0, PARAMETER_LIMIT).map(([name, raw]) => {
1601
+ const property = raw && typeof raw === "object" ? raw : {};
1602
+ 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;
1603
+ const description = typeof property.description === "string" ? property.description.trim() : "";
1604
+ return {
1605
+ name,
1606
+ ...kind ? { type: kind } : {},
1607
+ required: required.has(name),
1608
+ ...description ? { description: shown(description) } : {}
1609
+ };
1610
+ });
1611
+ }
1612
+ /**
1613
+ * The plugin's wire methods and its two broadcast frames. Every result is
1614
+ * validated by the host against these schemas, and none carries a
1615
+ * credential value.
1616
+ */
1617
+ function registerMethods(deps) {
1618
+ const { ctx, store, connections, tools, prompts, oauth } = deps;
1619
+ const serversChanged = ctx.client.registerFrame({
1620
+ name: "serversChanged",
1621
+ delivery: "broadcast",
1622
+ payload: ServerList
1623
+ });
1624
+ const selectionChanged = ctx.client.registerFrame({
1625
+ name: "selectionChanged",
1626
+ delivery: "broadcast",
1627
+ payload: Agent
1628
+ });
1629
+ const summary = (record) => {
1630
+ const status = connections.status(record.id);
1631
+ const secrets = status.reason ? secretValues(deps.secretsOf(record.id)) : [];
1632
+ return {
1633
+ id: record.id,
1634
+ slug: record.slug,
1635
+ name: record.name,
1636
+ transport: record.transport,
1637
+ enabled: record.enabled,
1638
+ status: status.reason ? {
1639
+ state: status.state,
1640
+ reason: redactReason(status.reason, secrets)
1641
+ } : { state: status.state },
1642
+ agentIds: store.agentsOf(record.id)
1643
+ };
1644
+ };
1645
+ const summaries = () => store.servers().map(summary);
1646
+ const require = (id) => {
1647
+ const record = store.server(id);
1648
+ if (!record) throw new Error("no such MCP server");
1649
+ return record;
1650
+ };
1651
+ const detail = (record) => {
1652
+ const snapshot = connections.snapshot(record.id);
1653
+ const secrets = secretValues(deps.secretsOf(record.id));
1654
+ const shown = (text) => redact(text, secrets).slice(0, DESCRIPTION_LIMIT);
1655
+ const described = (text) => text?.trim() ? { description: shown(text.trim()) } : {};
1656
+ const refusedPrompts = prompts.refusedPrompts(record.id, record.slug);
1657
+ let authorization = null;
1658
+ if (record.transport === "http" && record.config.auth === "oauth") {
1659
+ const { authorized, expiresAt } = oauth.status(record.id);
1660
+ authorization = {
1661
+ authorized,
1662
+ ...expiresAt === void 0 ? {} : { expiresAt }
1663
+ };
1664
+ }
1665
+ return {
1666
+ ...summary(record),
1667
+ ...described(snapshot?.description),
1668
+ config: record.config,
1669
+ acknowledged: record.transport === "stdio" && record.acknowledgedAt !== null,
1670
+ catalog: snapshot ? {
1671
+ tools: tools.catalogTools(record.id, snapshot).map((tool, at) => {
1672
+ const source = snapshot.tools[at];
1673
+ return {
1674
+ ...tool,
1675
+ ...described(source?.description),
1676
+ parameters: schemaParameters(source?.inputSchema, shown)
1677
+ };
1678
+ }),
1679
+ resources: snapshot.resources.map((resource) => ({
1680
+ name: resource.name ?? resource.uri,
1681
+ uri: resource.uri,
1682
+ ...described(resource.description),
1683
+ ...resource.mimeType ? { mimeType: resource.mimeType } : {}
1684
+ })),
1685
+ prompts: snapshot.prompts.map((prompt) => {
1686
+ const reason = refusedPrompts.get(prompt.name);
1687
+ return {
1688
+ name: prompt.name,
1689
+ ...described(prompt.description),
1690
+ parameters: (prompt.arguments ?? []).slice(0, PARAMETER_LIMIT).map((argument) => ({
1691
+ name: argument.name,
1692
+ required: argument.required === true,
1693
+ ...argument.description ? { description: shown(argument.description) } : {}
1694
+ })),
1695
+ ...reason ? { refused: reason } : {}
1696
+ };
1697
+ })
1698
+ } : null,
1699
+ oauth: authorization
1700
+ };
1701
+ };
1702
+ const announce = () => serversChanged.emit({ servers: summaries() });
1703
+ const management = {
1704
+ commands: deps.commands,
1705
+ agentConfig: deps.agentConfig,
1706
+ store,
1707
+ connections,
1708
+ tools,
1709
+ oauth,
1710
+ announce,
1711
+ selectionChanged: (agentId) => selectionChanged.emit({ agentId })
1712
+ };
1713
+ ctx.client.registerMethod({
1714
+ name: "commandParse",
1715
+ params: z.object({ text: z.string().min(1).refine(commandTextFits, "command-text-too-large") }).strict(),
1716
+ result: z.object({
1717
+ file: z.string().min(1),
1718
+ args: z.array(z.string()),
1719
+ syntax: z.enum(["posix-argv", "windows-argv"])
1720
+ }).strict(),
1721
+ handle: ({ text }) => parseCommandPaste(text, deps.commands)
1722
+ });
1723
+ ctx.client.registerMethod({
1724
+ name: "listServers",
1725
+ params: Empty,
1726
+ result: ServerList,
1727
+ handle: () => ({ servers: summaries() })
1728
+ });
1729
+ ctx.client.registerMethod({
1730
+ name: "getServer",
1731
+ params: Id,
1732
+ result: ServerDetailSchema,
1733
+ handle: ({ id }) => detail(require(id))
1734
+ });
1735
+ ctx.client.registerMethod({
1736
+ name: "saveServer",
1737
+ params: SaveServerSchema,
1738
+ result: ServerDetailSchema,
1739
+ async handle(input) {
1740
+ return detail(await saveServer(management, input));
1741
+ }
1742
+ });
1743
+ ctx.client.registerMethod({
1744
+ name: "removeServer",
1745
+ params: Id,
1746
+ result: ServerList,
1747
+ async handle({ id }) {
1748
+ require(id);
1749
+ deps.agentConfig.save(store.agentsOf(id), () => store.removeServer(id));
1750
+ deps.clearCredentials(id);
1751
+ oauth.invalidate(id);
1752
+ tools.forget(id);
1753
+ connections.reconcile(id);
1754
+ announce();
1755
+ return { servers: summaries() };
1756
+ }
1757
+ });
1758
+ ctx.client.registerMethod({
1759
+ name: "setEnabled",
1760
+ params: z.object({
1761
+ id: z.string(),
1762
+ enabled: z.boolean()
1763
+ }).strict(),
1764
+ result: ServerSummarySchema,
1765
+ async handle({ id, enabled }) {
1766
+ require(id);
1767
+ store.setEnabled(id, enabled);
1768
+ connections.reconcile(id);
1769
+ announce();
1770
+ return summary(require(id));
1771
+ }
1772
+ });
1773
+ ctx.client.registerMethod({
1774
+ name: "retryServer",
1775
+ params: Id,
1776
+ result: ServerSummarySchema,
1777
+ handle({ id }) {
1778
+ require(id);
1779
+ connections.reconcile(id, { keepSnapshot: true });
1780
+ announce();
1781
+ return summary(require(id));
1782
+ }
1783
+ });
1784
+ ctx.client.registerMethod({
1785
+ name: "testServer",
1786
+ params: Id,
1787
+ result: TestResultSchema,
1788
+ handle: async ({ id }) => {
1789
+ require(id);
1790
+ return await connections.test(id);
1791
+ }
1792
+ });
1793
+ ctx.client.registerMethod({
1794
+ name: "authorize",
1795
+ params: Id,
1796
+ result: z.object({ url: z.string() }).strict(),
1797
+ async handle({ id }) {
1798
+ const record = require(id);
1799
+ if (record.transport !== "http" || record.config.auth !== "oauth") throw new Error("this server does not use OAuth");
1800
+ return await oauth.authorize(id, record.config.url, (outcome) => {
1801
+ if (outcome.ok) connections.reconcile(id);
1802
+ else connections.needsAuth(id, outcome.reason);
1803
+ announce();
1804
+ });
1805
+ }
1806
+ });
1807
+ ctx.client.registerMethod({
1808
+ name: "cancelAuthorize",
1809
+ params: Id,
1810
+ result: Empty,
1811
+ handle({ id }) {
1812
+ oauth.cancel(id);
1813
+ return {};
1814
+ }
1815
+ });
1816
+ ctx.client.registerMethod({
1817
+ name: "signOut",
1818
+ params: Id,
1819
+ result: ServerSummarySchema,
1820
+ handle({ id }) {
1821
+ require(id);
1822
+ oauth.signOut(id);
1823
+ connections.reconcile(id);
1824
+ announce();
1825
+ return summary(require(id));
1826
+ }
1827
+ });
1828
+ ctx.client.registerMethod({
1829
+ name: "agentServers",
1830
+ params: Agent,
1831
+ result: z.object({
1832
+ serverIds: z.array(z.string()),
1833
+ revision: z.number(),
1834
+ contentHash: z.string()
1835
+ }).strict(),
1836
+ handle: ({ agentId }) => ({
1837
+ serverIds: store.agentServers(agentId),
1838
+ ...deps.agentConfig.state(agentId)
1839
+ })
1840
+ });
1841
+ ctx.client.registerMethod({
1842
+ name: "setAgentServers",
1843
+ params: z.object({
1844
+ agentId: z.string().min(1),
1845
+ serverIds: z.array(z.string()),
1846
+ expectedRevision: z.number().int().positive(),
1847
+ expectedContentHash: z.string().regex(/^[a-f0-9]{64}$/)
1848
+ }).strict(),
1849
+ result: z.object({
1850
+ serverIds: z.array(z.string()),
1851
+ revision: z.number(),
1852
+ contentHash: z.string()
1853
+ }).strict(),
1854
+ async handle({ agentId, serverIds, expectedRevision, expectedContentHash }) {
1855
+ deps.agentConfig.check(agentId, expectedRevision, expectedContentHash);
1856
+ for (const id of serverIds) require(id);
1857
+ deps.agentConfig.save([agentId], () => store.setAgentServers(agentId, serverIds));
1858
+ selectionChanged.emit({ agentId });
1859
+ announce();
1860
+ return {
1861
+ serverIds: store.agentServers(agentId),
1862
+ ...deps.agentConfig.state(agentId)
1863
+ };
1864
+ }
1865
+ });
1866
+ ctx.client.registerMethod({
1867
+ name: "prompts",
1868
+ params: Agent,
1869
+ result: z.object({ prompts: z.array(PromptEntrySchema) }).strict(),
1870
+ handle: ({ agentId }) => ({ prompts: prompts.list(agentId) })
1871
+ });
1872
+ ctx.client.registerMethod({
1873
+ name: "getPrompt",
1874
+ params: z.object({
1875
+ agentId: z.string().min(1),
1876
+ serverId: z.string(),
1877
+ name: z.string(),
1878
+ args: z.record(z.string(), z.string())
1879
+ }).strict(),
1880
+ result: Text,
1881
+ handle: (input, call) => prompts.get(input, call.signal)
1882
+ });
1883
+ ctx.client.registerMethod({
1884
+ name: "resources",
1885
+ params: z.object({
1886
+ agentId: z.string().min(1),
1887
+ query: z.string()
1888
+ }).strict(),
1889
+ result: z.object({ resources: z.array(ResourceEntrySchema) }).strict(),
1890
+ handle: ({ agentId, query }) => ({ resources: prompts.resources(agentId, query) })
1891
+ });
1892
+ ctx.client.registerMethod({
1893
+ name: "readResource",
1894
+ params: z.object({
1895
+ agentId: z.string().min(1),
1896
+ serverId: z.string(),
1897
+ uri: z.string()
1898
+ }).strict(),
1899
+ result: Text,
1900
+ handle: (input, call) => prompts.read(input, call.signal)
1901
+ });
1902
+ return {
1903
+ announce,
1904
+ management
1905
+ };
1906
+ }
1907
+ /** The server needs a person to authorize it (again). */
1908
+ var NeedsAuthorizationError = class extends Error {
1909
+ constructor(message = "authorization required") {
1910
+ super(message);
1911
+ this.name = "NeedsAuthorizationError";
1912
+ }
1913
+ };
1914
+ const CALLBACK_PATH = "/callback";
1915
+ function clientMetadata(redirectUrl) {
1916
+ return {
1917
+ client_name: "YaoGuang",
1918
+ redirect_uris: [redirectUrl],
1919
+ grant_types: ["authorization_code", "refresh_token"],
1920
+ response_types: ["code"],
1921
+ token_endpoint_auth_method: "none"
1922
+ };
1923
+ }
1924
+ function page(title, body) {
1925
+ 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>`;
1926
+ }
1927
+ function respond(res, status, title, body) {
1928
+ res.writeHead(status, {
1929
+ "content-type": "text/html; charset=utf-8",
1930
+ "cache-control": "no-store"
1931
+ });
1932
+ res.end(page(title, body));
1933
+ }
1934
+ function listen(port) {
1935
+ return new Promise((resolve, reject) => {
1936
+ const server = createServer();
1937
+ server.once("error", reject);
1938
+ server.listen(port, "127.0.0.1", () => {
1939
+ server.off("error", reject);
1940
+ resolve(server);
1941
+ });
1942
+ });
1943
+ }
1944
+ function portOf(uri) {
1945
+ if (typeof uri !== "string") return void 0;
1946
+ try {
1947
+ const url = new URL(uri);
1948
+ return url.hostname === "127.0.0.1" && url.port !== "" ? Number(url.port) : void 0;
1949
+ } catch {
1950
+ return;
1951
+ }
1952
+ }
1953
+ /**
1954
+ * OAuth for remote servers: an `OAuthClientProvider` over the credential
1955
+ * manager (`oauth.tokens`, `oauth.client`), the one-shot loopback callback,
1956
+ * and a refresh made ahead of expiry, shared by concurrent requests.
1957
+ *
1958
+ * Every authorization and every refresh belongs to a generation per server;
1959
+ * signing out, reauthorizing, changing the endpoint and deleting bump it, and
1960
+ * a late result from an older generation is dropped before it writes.
1961
+ */
1962
+ function createOAuth(deps) {
1963
+ const now = deps.now ?? Date.now;
1964
+ const timeoutMs = deps.timeoutMs ?? 3e5;
1965
+ const flows = /* @__PURE__ */ new Map();
1966
+ const refreshes = /* @__PURE__ */ new Map();
1967
+ const discovery = /* @__PURE__ */ new Map();
1968
+ const generations = /* @__PURE__ */ new Map();
1969
+ const gen = (serverId) => generations.get(serverId) ?? 0;
1970
+ const readJson = (serverId, name) => {
1971
+ const raw = deps.credentials.get(serverId, name);
1972
+ if (raw === void 0) return void 0;
1973
+ try {
1974
+ return JSON.parse(raw);
1975
+ } catch {
1976
+ return;
1977
+ }
1978
+ };
1979
+ const readTokens = (serverId) => readJson(serverId, OAUTH_TOKENS);
1980
+ /**
1981
+ * Token documents a refresh replaced, newest last and at most
1982
+ * `REPLACED_KEPT` per server. A request already sent may still carry one,
1983
+ * and a server may echo it after the refresh, so redaction keeps checking
1984
+ * them until the tokens are cleared.
1985
+ */
1986
+ const replaced = /* @__PURE__ */ new Map();
1987
+ const remember = (serverId) => {
1988
+ let raw;
1989
+ try {
1990
+ raw = deps.credentials.get(serverId, OAUTH_TOKENS);
1991
+ } catch {
1992
+ raw = void 0;
1993
+ }
1994
+ if (raw === void 0) return;
1995
+ const kept = [...replaced.get(serverId) ?? [], raw].slice(-4);
1996
+ replaced.set(serverId, kept);
1997
+ };
1998
+ const readClient = (serverId) => readJson(serverId, OAUTH_CLIENT);
1999
+ const writeTokens = (serverId, generation, tokens) => {
2000
+ if (generation !== gen(serverId)) throw new Error("authorization was superseded");
2001
+ remember(serverId);
2002
+ const stored = {
2003
+ ...tokens,
2004
+ ...tokens.expires_in === void 0 ? {} : { expires_at: now() + tokens.expires_in * 1e3 }
2005
+ };
2006
+ deps.selfWrite(() => deps.credentials.set(serverId, OAUTH_TOKENS, JSON.stringify(stored)));
2007
+ return stored;
2008
+ };
2009
+ const writeClient = (serverId, generation, info) => {
2010
+ if (generation !== gen(serverId)) throw new Error("authorization was superseded");
2011
+ deps.selfWrite(() => deps.credentials.set(serverId, OAUTH_CLIENT, JSON.stringify(info)));
2012
+ };
2013
+ const clear = (serverId, name) => {
2014
+ const names = name === void 0 ? [OAUTH_TOKENS, OAUTH_CLIENT] : [name];
2015
+ if (names.includes("oauth.tokens")) replaced.delete(serverId);
2016
+ for (const item of names) deps.selfWrite(() => deps.credentials.clear(serverId, item));
2017
+ };
2018
+ const invalidateScope = (serverId, scope, flow) => {
2019
+ if (scope === "all" || scope === "tokens") clear(serverId, OAUTH_TOKENS);
2020
+ if (scope === "all" || scope === "client") clear(serverId, OAUTH_CLIENT);
2021
+ if (scope === "all" || scope === "discovery") discovery.delete(serverId);
2022
+ if ((scope === "all" || scope === "verifier") && flow) flow.verifier = void 0;
2023
+ };
2024
+ const strip = ({ expires_at: _expiresAt, ...tokens }) => tokens;
2025
+ /** One refresh per server at a time; concurrent callers share it. */
2026
+ const refresh = (serverId, serverUrl, current) => {
2027
+ const running = refreshes.get(serverId);
2028
+ if (running) return running;
2029
+ const generation = gen(serverId);
2030
+ const work = (async () => {
2031
+ const client = readClient(serverId);
2032
+ if (!client || !current.refresh_token) throw new NeedsAuthorizationError();
2033
+ let info = discovery.get(serverId);
2034
+ if (!info?.authorizationServerUrl) {
2035
+ info = await discoverOAuthServerInfo(serverUrl, { fetchFn: deps.fetch });
2036
+ discovery.set(serverId, info);
2037
+ }
2038
+ const selected = await selectResourceURL(serverUrl, {}, info.resourceMetadata);
2039
+ const resource = selected && info.resourceMetadata ? info.resourceMetadata.resource : selected;
2040
+ const tokens = await refreshAuthorization(info.authorizationServerUrl, {
2041
+ ...info.authorizationServerMetadata ? { metadata: info.authorizationServerMetadata } : {},
2042
+ clientInformation: client,
2043
+ refreshToken: current.refresh_token,
2044
+ ...resource === void 0 ? {} : { resource },
2045
+ fetchFn: deps.fetch
2046
+ });
2047
+ return writeTokens(serverId, generation, tokens);
2048
+ })().finally(() => refreshes.delete(serverId));
2049
+ refreshes.set(serverId, work);
2050
+ return work;
2051
+ };
2052
+ const finish = (serverId, flow, outcome) => {
2053
+ if (flow.settled) return;
2054
+ flow.settled = true;
2055
+ if (flow.timer) clearTimeout(flow.timer);
2056
+ flow.server.close();
2057
+ flow.server.closeAllConnections?.();
2058
+ if (flows.get(serverId) === flow) flows.delete(serverId);
2059
+ if (flow.gen === gen(serverId)) flow.done(outcome);
2060
+ };
2061
+ /** Drops every authorization and refresh in progress for a server. */
2062
+ const invalidate = (serverId) => {
2063
+ generations.set(serverId, gen(serverId) + 1);
2064
+ discovery.delete(serverId);
2065
+ const flow = flows.get(serverId);
2066
+ if (flow) finish(serverId, flow, {
2067
+ ok: false,
2068
+ reason: "authorization was cancelled"
2069
+ });
2070
+ };
2071
+ return {
2072
+ /** The current generation; a caller compares it after an await. */
2073
+ generation: gen,
2074
+ invalidate,
2075
+ /** Whether tokens are stored, and when the access token expires. */
2076
+ status(serverId) {
2077
+ let tokens;
2078
+ try {
2079
+ tokens = readTokens(serverId);
2080
+ } catch {
2081
+ tokens = void 0;
2082
+ }
2083
+ return {
2084
+ authorized: tokens !== void 0,
2085
+ ...tokens?.expires_at === void 0 ? {} : { expiresAt: tokens.expires_at },
2086
+ pending: flows.has(serverId)
2087
+ };
2088
+ },
2089
+ hasTokens(serverId) {
2090
+ return readTokens(serverId) !== void 0;
2091
+ },
2092
+ /** Clears this server's tokens and client registration. */
2093
+ signOut(serverId) {
2094
+ invalidate(serverId);
2095
+ clear(serverId);
2096
+ },
2097
+ /** The raw credential values a connection's requests may carry, for
2098
+ * redaction: the stored ones and the token documents a refresh replaced. */
2099
+ secrets(serverId) {
2100
+ const read = (name) => {
2101
+ try {
2102
+ return deps.credentials.get(serverId, name);
2103
+ } catch {
2104
+ return;
2105
+ }
2106
+ };
2107
+ return [
2108
+ read(OAUTH_TOKENS),
2109
+ read(OAUTH_CLIENT),
2110
+ ...replaced.get(serverId) ?? []
2111
+ ];
2112
+ },
2113
+ /**
2114
+ * The provider a connection uses. It never opens an authorization: when the
2115
+ * endpoint asks for one, the SDK's request fails and the server reads as
2116
+ * needing authorization. Its `tokens()` refreshes a token expiring within
2117
+ * a minute before handing it out.
2118
+ */
2119
+ connectionProvider(serverId, serverUrl) {
2120
+ const generation = gen(serverId);
2121
+ const recorded = () => readClient(serverId)?.redirect_uris?.[0] ?? "http://127.0.0.1/callback";
2122
+ return {
2123
+ get redirectUrl() {
2124
+ return recorded();
2125
+ },
2126
+ get clientMetadata() {
2127
+ return clientMetadata(recorded());
2128
+ },
2129
+ clientInformation: () => readClient(serverId),
2130
+ saveClientInformation() {
2131
+ throw new NeedsAuthorizationError();
2132
+ },
2133
+ async tokens() {
2134
+ const stored = readTokens(serverId);
2135
+ if (!stored) return void 0;
2136
+ if (stored.expires_at === void 0 || !stored.refresh_token || stored.expires_at - now() > 6e4) return strip(stored);
2137
+ try {
2138
+ return strip(await refresh(serverId, serverUrl, stored));
2139
+ } catch (error) {
2140
+ if (error instanceof NeedsAuthorizationError) throw error;
2141
+ if (error instanceof OAuthError && !(error instanceof ServerError)) throw new NeedsAuthorizationError(`token refresh was refused: ${error.errorCode}`);
2142
+ deps.log.warn(`token refresh for server ${serverId} failed; using the stored token`);
2143
+ return strip(stored);
2144
+ }
2145
+ },
2146
+ saveTokens(tokens) {
2147
+ writeTokens(serverId, generation, tokens);
2148
+ },
2149
+ redirectToAuthorization() {},
2150
+ saveCodeVerifier() {},
2151
+ codeVerifier() {
2152
+ throw new NeedsAuthorizationError();
2153
+ },
2154
+ invalidateCredentials(scope) {
2155
+ if (generation === gen(serverId)) invalidateScope(serverId, scope);
2156
+ },
2157
+ saveDiscoveryState(state) {
2158
+ discovery.set(serverId, state);
2159
+ },
2160
+ discoveryState: () => discovery.get(serverId)
2161
+ };
2162
+ },
2163
+ /**
2164
+ * Starts an authorization: listens once on a loopback port, registers a
2165
+ * client when needed (again when the recorded redirect port cannot be
2166
+ * bound), and returns the authorization URL a page opens. `done` is called
2167
+ * once, unless a newer generation replaced this one.
2168
+ */
2169
+ async authorize(serverId, serverUrl, done) {
2170
+ invalidate(serverId);
2171
+ const generation = gen(serverId);
2172
+ const recorded = readClient(serverId);
2173
+ const recordedPort = portOf(recorded?.redirect_uris?.[0]);
2174
+ let server;
2175
+ try {
2176
+ server = await listen(recordedPort ?? 0);
2177
+ } catch {
2178
+ server = await listen(0);
2179
+ }
2180
+ const address = server.address();
2181
+ const redirectUrl = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}${CALLBACK_PATH}`;
2182
+ if (recorded && recorded.redirect_uris?.[0] !== redirectUrl) clear(serverId, OAUTH_CLIENT);
2183
+ const flow = {
2184
+ gen: generation,
2185
+ server,
2186
+ state: randomBytes(24).toString("base64url"),
2187
+ done,
2188
+ exchanging: false,
2189
+ settled: false
2190
+ };
2191
+ const provider = {
2192
+ redirectUrl,
2193
+ clientMetadata: clientMetadata(redirectUrl),
2194
+ state: () => flow.state,
2195
+ clientInformation: () => readClient(serverId),
2196
+ saveClientInformation: (info) => writeClient(serverId, generation, info),
2197
+ tokens: () => void 0,
2198
+ saveTokens(tokens) {
2199
+ writeTokens(serverId, generation, tokens);
2200
+ },
2201
+ redirectToAuthorization(url) {
2202
+ flow.authorizationUrl = url;
2203
+ },
2204
+ saveCodeVerifier(verifier) {
2205
+ flow.verifier = verifier;
2206
+ },
2207
+ codeVerifier() {
2208
+ if (flow.verifier === void 0) throw new Error("no authorization in progress");
2209
+ return flow.verifier;
2210
+ },
2211
+ invalidateCredentials(scope) {
2212
+ if (generation === gen(serverId)) invalidateScope(serverId, scope, flow);
2213
+ },
2214
+ saveDiscoveryState(state) {
2215
+ discovery.set(serverId, state);
2216
+ },
2217
+ discoveryState: () => discovery.get(serverId)
2218
+ };
2219
+ try {
2220
+ const result = await auth(provider, {
2221
+ serverUrl,
2222
+ fetchFn: deps.fetch
2223
+ });
2224
+ if (generation !== gen(serverId)) throw new Error("authorization was superseded");
2225
+ if (result !== "REDIRECT" || !flow.authorizationUrl) throw new Error("the authorization server did not ask for a browser authorization");
2226
+ } catch (error) {
2227
+ server.close();
2228
+ throw error;
2229
+ }
2230
+ server.on("request", (req, res) => {
2231
+ handle(req, res);
2232
+ });
2233
+ const handle = async (req, res) => {
2234
+ const url = new URL(req.url ?? "/", redirectUrl);
2235
+ if (req.method !== "GET" || url.pathname !== CALLBACK_PATH) {
2236
+ res.writeHead(404).end();
2237
+ return;
2238
+ }
2239
+ if (url.searchParams.get("state") !== flow.state || flow.settled || flow.exchanging) {
2240
+ respond(res, 400, "YaoGuang", "This authorization link is not valid. 授权链接无效。");
2241
+ return;
2242
+ }
2243
+ const error = url.searchParams.get("error");
2244
+ if (error !== null) {
2245
+ const code = /^[a-z_]{1,64}$/.test(error) ? error : "error";
2246
+ respond(res, 200, "YaoGuang", "Authorization was not completed. 授权未完成,可以关闭此页。");
2247
+ finish(serverId, flow, {
2248
+ ok: false,
2249
+ reason: `authorization was declined (${code})`
2250
+ });
2251
+ return;
2252
+ }
2253
+ const code = url.searchParams.get("code");
2254
+ if (!code) {
2255
+ respond(res, 400, "YaoGuang", "The authorization code is missing. 缺少授权码。");
2256
+ return;
2257
+ }
2258
+ flow.exchanging = true;
2259
+ try {
2260
+ await auth(provider, {
2261
+ serverUrl,
2262
+ authorizationCode: code,
2263
+ fetchFn: deps.fetch
2264
+ });
2265
+ respond(res, 200, "YaoGuang", "Authorization complete. You can close this page. 授权完成,可以关闭此页。");
2266
+ finish(serverId, flow, { ok: true });
2267
+ } catch (failure) {
2268
+ respond(res, 200, "YaoGuang", "Authorization failed. 授权失败,可以关闭此页。");
2269
+ finish(serverId, flow, {
2270
+ ok: false,
2271
+ reason: `token exchange failed: ${failure instanceof Error ? failure.message : String(failure)}`
2272
+ });
2273
+ }
2274
+ };
2275
+ flow.timer = setTimeout(() => finish(serverId, flow, {
2276
+ ok: false,
2277
+ reason: "authorization timed out after 5 minutes"
2278
+ }), timeoutMs);
2279
+ flow.timer.unref?.();
2280
+ flows.set(serverId, flow);
2281
+ return { url: flow.authorizationUrl.href };
2282
+ },
2283
+ /** Cancels owned callbacks and invalidates late writes without reading revoked credentials. */
2284
+ shutdown() {
2285
+ const owned = /* @__PURE__ */ new Set([
2286
+ ...flows.keys(),
2287
+ ...generations.keys(),
2288
+ ...refreshes.keys(),
2289
+ ...discovery.keys()
2290
+ ]);
2291
+ for (const serverId of owned) invalidate(serverId);
2292
+ },
2293
+ /** Abandons the authorization in progress, if any. */
2294
+ cancel(serverId) {
2295
+ const flow = flows.get(serverId);
2296
+ if (flow) finish(serverId, flow, {
2297
+ ok: false,
2298
+ reason: "authorization was cancelled"
2299
+ });
2300
+ }
2301
+ };
2302
+ }
2303
+ //#endregion
2304
+ //#region src/content.ts
2305
+ /** A tool result's ceiling: 48 KiB of head and 16 KiB of tail at most. */
2306
+ const TOOL_RESULT_LIMIT = 65536;
2307
+ /** A resource read's ceiling. */
2308
+ const RESOURCE_LIMIT = 102400;
2309
+ const notice = (omitted) => `\n\n[… ${omitted} bytes omitted …]\n\n`;
2310
+ /**
2311
+ * `text` when it fits in `limit` UTF-8 bytes; otherwise its head and tail
2312
+ * split 3:1 around a line saying how much was left out. The notice's bytes
2313
+ * are reserved first, so the result never exceeds `limit`, and neither cut
2314
+ * splits a character.
2315
+ */
2316
+ function truncate(text, limit) {
2317
+ const bytes = Buffer.from(text, "utf8");
2318
+ if (bytes.length <= limit) return text;
2319
+ const budget = limit - Buffer.byteLength(notice(bytes.length));
2320
+ let head = Math.floor(budget * 3 / 4);
2321
+ let tail = bytes.length - (budget - head);
2322
+ while (head > 0 && ((bytes[head] ?? 0) & 192) === 128) head -= 1;
2323
+ while (tail < bytes.length && ((bytes[tail] ?? 0) & 192) === 128) tail += 1;
2324
+ return bytes.subarray(0, head).toString("utf8") + notice(tail - head) + bytes.subarray(tail).toString("utf8");
2325
+ }
2326
+ /** Bytes a base64 blob decodes to. */
2327
+ function blobBytes(blob) {
2328
+ const padding = blob.endsWith("==") ? 2 : blob.endsWith("=") ? 1 : 0;
2329
+ return Math.max(0, Math.floor(blob.length * 3 / 4) - padding);
2330
+ }
2331
+ /** One embedded resource: its text, or a line naming what it was. */
2332
+ function resourceText(resource) {
2333
+ if (typeof resource.text === "string") return resource.text;
2334
+ return `[二进制资源:${typeof resource.mimeType === "string" ? resource.mimeType : "application/octet-stream"},${typeof resource.blob === "string" ? blobBytes(resource.blob) : 0} 字节]`;
2335
+ }
2336
+ /** One content block as text; `undefined` for a block with no text form. */
2337
+ function blockText(block) {
2338
+ switch (block.type) {
2339
+ case "text": return typeof block.text === "string" ? block.text : "";
2340
+ case "image": return `[图片:${String(block.mimeType ?? "image")}]`;
2341
+ case "audio": return `[音频:${String(block.mimeType ?? "audio")}]`;
2342
+ case "resource": return resourceText(block.resource ?? {});
2343
+ case "resource_link": return `[资源:${String(block.uri ?? "")}]`;
2344
+ default: return `[${block.type}]`;
2345
+ }
2346
+ }
2347
+ const isImageType = (mime) => typeof mime === "string" && mime.startsWith("image/");
2348
+ /** The last path segment of `uri`, query and fragment removed and percent
2349
+ * escapes decoded; `undefined` when that leaves nothing to name a file by. */
2350
+ function uriBasename(uri) {
2351
+ if (typeof uri !== "string") return void 0;
2352
+ const path = uri.replace(/[?#].*$/, "").replace(/\/+$/, "");
2353
+ const slash = path.lastIndexOf("/");
2354
+ if (slash === -1 || path[slash - 1] === ":") return void 0;
2355
+ const segment = path.slice(slash + 1);
2356
+ try {
2357
+ return decodeURIComponent(segment) || void 0;
2358
+ } catch {
2359
+ return segment || void 0;
2360
+ }
2361
+ }
2362
+ /** The bytes one block hands back as an image, with the name it goes by, or
2363
+ * `undefined` for a block that stays text: an `image` block or an embedded
2364
+ * resource `blob`, either with base64 data and an `image/*` type. Whether the
2365
+ * host can take the format is the host's judgement, not this one's. */
2366
+ function blockImage(block, ordinal) {
2367
+ const fallback = `image-${ordinal}`;
2368
+ if (block.type === "image") {
2369
+ if (typeof block.data !== "string" || !isImageType(block.mimeType)) return void 0;
2370
+ const data = Buffer.from(block.data, "base64");
2371
+ return data.length === 0 ? void 0 : {
2372
+ data: new Uint8Array(data),
2373
+ name: fallback
2374
+ };
2375
+ }
2376
+ if (block.type === "resource") {
2377
+ const resource = block.resource ?? {};
2378
+ if (typeof resource.text === "string") return void 0;
2379
+ if (typeof resource.blob !== "string" || !isImageType(resource.mimeType)) return void 0;
2380
+ const data = Buffer.from(resource.blob, "base64");
2381
+ if (data.length === 0) return void 0;
2382
+ return {
2383
+ data: new Uint8Array(data),
2384
+ name: uriBasename(resource.uri) ?? fallback
2385
+ };
2386
+ }
2387
+ }
2388
+ /**
2389
+ * A `tools/call` result as the model reads it: text blocks in order, image
2390
+ * blocks and embedded image resources as files, other blocks as placeholders,
2391
+ * and `structuredContent` as JSON when no text block carried anything. An
2392
+ * image's ordinal counts every image this result hands back, in block order.
2393
+ */
2394
+ function toolResultContent(result) {
2395
+ const blocks = Array.isArray(result.content) ? result.content : [];
2396
+ const hasText = blocks.some((block) => block.type === "text");
2397
+ const files = [];
2398
+ const parts = [];
2399
+ for (const block of blocks) {
2400
+ const image = blockImage(block, files.length + 1);
2401
+ if (image) files.push(image);
2402
+ else parts.push(blockText(block));
2403
+ }
2404
+ if (!hasText && result.structuredContent !== void 0) parts.unshift(JSON.stringify(result.structuredContent));
2405
+ if (!blocks.length && result.structuredContent === void 0 && result.toolResult !== void 0) parts.push(JSON.stringify(result.toolResult));
2406
+ return {
2407
+ text: parts.join("\n"),
2408
+ files
2409
+ };
2410
+ }
2411
+ /**
2412
+ * A `prompts/get` result as the text a person's message carries: messages in
2413
+ * order, an assistant message introduced by a line saying so.
2414
+ */
2415
+ function promptText(result) {
2416
+ return result.messages.map((message) => {
2417
+ const text = blockText(message.content);
2418
+ return message.role === "assistant" ? `[以下为 prompt 中的 assistant 消息]\n${text}` : text;
2419
+ }).join("\n\n");
2420
+ }
2421
+ /** A `resources/read` result as text, contents in order. */
2422
+ function readResultText(result) {
2423
+ return result.contents.map((content) => resourceText(content)).join("\n\n");
2424
+ }
2425
+ /** A host composer command argument name. */
2426
+ const ARGUMENT_NAME = /^[A-Za-z0-9_][A-Za-z0-9_-]{0,63}$/;
2427
+ /** The first twelve hex characters of `sha256(slug + "\0" + name)`. */
2428
+ function digest(slug, name) {
2429
+ return createHash("sha256").update(`${slug}\0${name}`).digest("hex").slice(0, 12);
2430
+ }
2431
+ /**
2432
+ * Maps a candidate to a legal name: characters outside `allowed` become `_`;
2433
+ * when any was replaced or the result exceeds `max`, it is cut to
2434
+ * `max - 13` characters and `_<hash>` appended, so the result is unique per
2435
+ * `(slug, name)` and independent of listing order.
2436
+ */
2437
+ function legal(prefix, name, slug, allowed, max) {
2438
+ const body = name.replace(allowed, "_");
2439
+ const full = `${prefix}${body}`;
2440
+ if (body === name && full.length <= max) return full;
2441
+ return `${full.slice(0, max - 13)}_${digest(slug, name)}`;
2442
+ }
2443
+ /** `mcp_<slug>_<tool>`, at most 64 characters of `[A-Za-z0-9_-]`. */
2444
+ function toolName(slug, tool) {
2445
+ return legal(`mcp_${slug}_`, tool, slug, /[^A-Za-z0-9_-]/g, 64);
2446
+ }
2447
+ /** `<slug>.<prompt>`, a legal composer command name. */
2448
+ function commandName(slug, prompt) {
2449
+ return legal(`${slug}.`, prompt, slug, /[^A-Za-z0-9._-]/g, 200);
2450
+ }
2451
+ /** A legal composer argument name for an MCP prompt argument. */
2452
+ function argumentName(slug, argument) {
2453
+ const mapped = legal("", argument, slug, /[^A-Za-z0-9_-]/g, 64);
2454
+ return ARGUMENT_NAME.test(mapped) ? mapped : `_${mapped.slice(0, 63)}`;
2455
+ }
2456
+ /** Groups items by a mapped name and reports every name more than one item mapped to. */
2457
+ function collisions(items, name) {
2458
+ const seen = /* @__PURE__ */ new Map();
2459
+ for (const item of items) seen.set(name(item), (seen.get(name(item)) ?? 0) + 1);
2460
+ return new Set([...seen].filter(([, count]) => count > 1).map(([key]) => key));
2461
+ }
2462
+ const REFUSED_PROMPT = "maps to the same command name as another prompt of this server";
2463
+ /** Runs a server request; a failure's text is checked against the credentials first. */
2464
+ async function guarded(secrets, request) {
2465
+ try {
2466
+ return await request();
2467
+ } catch (error) {
2468
+ throw new Error(redact(error instanceof Error ? error.message : String(error), secrets));
2469
+ }
2470
+ }
2471
+ /**
2472
+ * The composer's MCP content: prompts as commands and resources as
2473
+ * attachments, for the servers an agent selects. Names a server gives are
2474
+ * mapped to what the host's command grammar accepts, and mapped back before
2475
+ * the server is asked; a prompt whose name or arguments collide is left out.
2476
+ */
2477
+ function createPrompts(deps) {
2478
+ const { store } = deps;
2479
+ const mappedPrompts = (serverId, slug) => {
2480
+ const prompts = deps.connections().snapshot(serverId)?.prompts ?? [];
2481
+ const nameOf = (prompt) => commandName(slug, prompt.name).slice(slug.length + 1);
2482
+ const clashes = collisions(prompts, nameOf);
2483
+ const kept = [];
2484
+ const refused = /* @__PURE__ */ new Map();
2485
+ for (const prompt of prompts) {
2486
+ const name = nameOf(prompt);
2487
+ const argNames = (prompt.arguments ?? []).map((arg) => argumentName(slug, arg.name));
2488
+ if (clashes.has(name) || new Set(argNames).size !== argNames.length) {
2489
+ refused.set(prompt.name, REFUSED_PROMPT);
2490
+ continue;
2491
+ }
2492
+ const args = /* @__PURE__ */ new Map();
2493
+ for (const [index, arg] of (prompt.arguments ?? []).entries()) args.set(argNames[index], arg.name);
2494
+ kept.push({
2495
+ prompt,
2496
+ name,
2497
+ args
2498
+ });
2499
+ }
2500
+ return {
2501
+ kept,
2502
+ refused
2503
+ };
2504
+ };
2505
+ /** The server, when `agentId` selects it; otherwise the refusal. */
2506
+ const selected = (agentId, serverId) => {
2507
+ const record = store.server(serverId);
2508
+ if (!record) throw new Error("no such MCP server");
2509
+ if (!store.isSelected(agentId, serverId)) throw new Error(`server "${record.slug}" is not selected by this agent`);
2510
+ const live = deps.connections().live(serverId);
2511
+ if (!live) {
2512
+ const status = deps.connections().status(serverId);
2513
+ throw new Error(`MCP server ${record.name} 当前未连接:${status.reason ?? status.state}`);
2514
+ }
2515
+ return {
2516
+ record,
2517
+ live
2518
+ };
2519
+ };
2520
+ return {
2521
+ refusedPrompts(serverId, slug) {
2522
+ return mappedPrompts(serverId, slug).refused;
2523
+ },
2524
+ list(agentId) {
2525
+ const entries = [];
2526
+ for (const id of store.agentServers(agentId)) {
2527
+ const record = store.server(id);
2528
+ if (!record || !deps.connections().live(id)) continue;
2529
+ for (const { prompt, name, args } of mappedPrompts(id, record.slug).kept) {
2530
+ const back = new Map([...args].map(([mapped, own]) => [own, mapped]));
2531
+ entries.push({
2532
+ serverId: id,
2533
+ slug: record.slug,
2534
+ serverName: record.name,
2535
+ name,
2536
+ ...prompt.description ? { description: prompt.description } : {},
2537
+ arguments: (prompt.arguments ?? []).map((arg) => ({
2538
+ name: back.get(arg.name),
2539
+ ...arg.description ? { description: arg.description } : {},
2540
+ ...arg.required ? { required: true } : {}
2541
+ }))
2542
+ });
2543
+ }
2544
+ }
2545
+ return entries;
2546
+ },
2547
+ async get(input, signal) {
2548
+ const { record, live } = selected(input.agentId, input.serverId);
2549
+ const found = mappedPrompts(record.id, record.slug).kept.find((one) => one.name === input.name);
2550
+ if (!found) throw new Error(`no prompt "${input.name}" on MCP server ${record.name}`);
2551
+ const args = {};
2552
+ for (const [mapped, own] of found.args) {
2553
+ const value = input.args[mapped];
2554
+ if (value !== void 0) args[own] = value;
2555
+ }
2556
+ for (const arg of found.prompt.arguments ?? []) if (arg.required && args[arg.name] === void 0) {
2557
+ const mapped = [...found.args].find(([, own]) => own === arg.name)?.[0] ?? arg.name;
2558
+ throw new Error(`missing argument "${mapped}"`);
2559
+ }
2560
+ return { text: redact(promptText(await guarded(live.secrets, () => live.client.getPrompt({
2561
+ name: found.prompt.name,
2562
+ arguments: args
2563
+ }, signal ? { signal } : void 0))), live.secrets) };
2564
+ },
2565
+ resources(agentId, query) {
2566
+ const needle = query.trim().toLowerCase();
2567
+ const entries = [];
2568
+ for (const id of store.agentServers(agentId)) {
2569
+ const record = store.server(id);
2570
+ if (!record || !deps.connections().live(id)) continue;
2571
+ for (const resource of deps.connections().snapshot(id)?.resources ?? []) {
2572
+ const haystack = [
2573
+ resource.name,
2574
+ resource.uri,
2575
+ resource.description
2576
+ ].filter(Boolean).join("\n").toLowerCase();
2577
+ if (needle && !haystack.includes(needle)) continue;
2578
+ entries.push({
2579
+ serverId: id,
2580
+ serverName: record.name,
2581
+ uri: resource.uri,
2582
+ ...resource.name ? { name: resource.name } : {},
2583
+ ...resource.description ? { description: resource.description } : {}
2584
+ });
2585
+ if (entries.length >= 200) return entries;
2586
+ }
2587
+ }
2588
+ return entries;
2589
+ },
2590
+ async read(input, signal) {
2591
+ const { live } = selected(input.agentId, input.serverId);
2592
+ return { text: truncate(redact(readResultText(await guarded(live.secrets, () => live.client.readResource({ uri: input.uri }, signal ? { signal } : void 0))), live.secrets), RESOURCE_LIMIT) };
2593
+ }
2594
+ };
2595
+ }
2596
+ //#endregion
2597
+ //#region src/store.ts
2598
+ /** The plugin's three tables, always under the host-issued prefix. */
2599
+ function createMcpStore(storage) {
2600
+ const { db, tableName } = storage;
2601
+ const servers = tableName("server");
2602
+ const selections = tableName("agent_server");
2603
+ db.exec(`CREATE TABLE IF NOT EXISTS ${servers} (
2604
+ id TEXT NOT NULL PRIMARY KEY,
2605
+ slug TEXT NOT NULL UNIQUE,
2606
+ name TEXT NOT NULL,
2607
+ transport TEXT NOT NULL,
2608
+ config TEXT NOT NULL,
2609
+ enabled INTEGER NOT NULL,
2610
+ acknowledged_at INTEGER,
2611
+ created_at INTEGER NOT NULL
2612
+ ) STRICT;
2613
+ CREATE TABLE IF NOT EXISTS ${selections} (
2614
+ agent_id TEXT NOT NULL,
2615
+ server_id TEXT NOT NULL,
2616
+ PRIMARY KEY (agent_id, server_id)
2617
+ ) STRICT;
2618
+ CREATE INDEX IF NOT EXISTS ${tableName("agent_server_by_server")} ON ${selections} (server_id);`);
2619
+ const selected = db.prepare(`SELECT 1 FROM ${selections} WHERE agent_id = ? AND server_id = ?`);
2620
+ const parse = (row) => {
2621
+ const base = {
2622
+ id: String(row.id),
2623
+ slug: String(row.slug),
2624
+ name: String(row.name),
2625
+ enabled: Number(row.enabled) === 1,
2626
+ createdAt: Number(row.created_at)
2627
+ };
2628
+ const config = JSON.parse(String(row.config));
2629
+ return row.transport === "stdio" ? {
2630
+ ...base,
2631
+ transport: "stdio",
2632
+ config: StdioConfigSchema.parse(config),
2633
+ acknowledgedAt: row.acknowledged_at === null ? null : Number(row.acknowledged_at)
2634
+ } : {
2635
+ ...base,
2636
+ transport: "http",
2637
+ config: HttpConfigSchema.parse(config),
2638
+ acknowledgedAt: null
2639
+ };
2640
+ };
2641
+ const transaction = (write) => {
2642
+ if (db.isTransaction) return write();
2643
+ db.exec("BEGIN IMMEDIATE");
2644
+ try {
2645
+ const result = write();
2646
+ db.exec("COMMIT");
2647
+ return result;
2648
+ } catch (error) {
2649
+ db.exec("ROLLBACK");
2650
+ throw error;
2651
+ }
2652
+ };
2653
+ const saveServer = (record) => {
2654
+ db.prepare(`INSERT INTO ${servers} (id, slug, name, transport, config, enabled, acknowledged_at, created_at)
2655
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
2656
+ ON CONFLICT(id) DO UPDATE SET slug = excluded.slug, name = excluded.name,
2657
+ transport = excluded.transport, config = excluded.config, enabled = excluded.enabled,
2658
+ 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);
2659
+ };
2660
+ const setServerSelected = (agentId, serverId, selected) => {
2661
+ if (selected) db.prepare(`INSERT OR IGNORE INTO ${selections} (agent_id, server_id) VALUES (?, ?)`).run(agentId, serverId);
2662
+ else db.prepare(`DELETE FROM ${selections} WHERE agent_id = ? AND server_id = ?`).run(agentId, serverId);
2663
+ };
2664
+ return {
2665
+ transaction,
2666
+ servers() {
2667
+ return db.prepare(`SELECT * FROM ${servers} ORDER BY created_at, id`).all().map((row) => parse(row));
2668
+ },
2669
+ server(id) {
2670
+ const row = db.prepare(`SELECT * FROM ${servers} WHERE id = ?`).get(id);
2671
+ return row ? parse(row) : void 0;
2672
+ },
2673
+ serverBySlug(slug) {
2674
+ const row = db.prepare(`SELECT * FROM ${servers} WHERE slug = ?`).get(slug);
2675
+ return row ? parse(row) : void 0;
2676
+ },
2677
+ /** Inserts or replaces one server row. */
2678
+ saveServer,
2679
+ /** Creates a server and its initial agent selection atomically. */
2680
+ createSelectedServer(record, agentId, selected) {
2681
+ transaction(() => {
2682
+ saveServer(record);
2683
+ if (selected) setServerSelected(agentId, record.id, true);
2684
+ });
2685
+ },
2686
+ /** Adds or removes one agent's selection without replacing other selections. */
2687
+ setServerSelected,
2688
+ setEnabled(id, enabled) {
2689
+ db.prepare(`UPDATE ${servers} SET enabled = ? WHERE id = ?`).run(enabled ? 1 : 0, id);
2690
+ },
2691
+ /** Deletes a server with its selections, in one transaction. Its tools'
2692
+ * remembered approvals are the host's grants, keyed by this server's id,
2693
+ * and a person revokes them in the access list. */
2694
+ removeServer(id) {
2695
+ transaction(() => {
2696
+ db.prepare(`DELETE FROM ${servers} WHERE id = ?`).run(id);
2697
+ db.prepare(`DELETE FROM ${selections} WHERE server_id = ?`).run(id);
2698
+ });
2699
+ },
2700
+ isSelected(agentId, serverId) {
2701
+ return selected.get(agentId, serverId) !== void 0;
2702
+ },
2703
+ agentServers(agentId) {
2704
+ return db.prepare(`SELECT server_id FROM ${selections} WHERE agent_id = ? ORDER BY server_id`).all(agentId).map((row) => String(row.server_id));
2705
+ },
2706
+ agentsOf(serverId) {
2707
+ return db.prepare(`SELECT agent_id FROM ${selections} WHERE server_id = ? ORDER BY agent_id`).all(serverId).map((row) => String(row.agent_id));
2708
+ },
2709
+ /** Replaces an agent's selection whole. */
2710
+ setAgentServers(agentId, serverIds) {
2711
+ transaction(() => {
2712
+ db.prepare(`DELETE FROM ${selections} WHERE agent_id = ?`).run(agentId);
2713
+ const insert = db.prepare(`INSERT INTO ${selections} (agent_id, server_id) VALUES (?, ?)`);
2714
+ for (const id of new Set(serverIds)) insert.run(agentId, id);
2715
+ });
2716
+ }
2717
+ };
2718
+ }
2719
+ /** The longest description a model is shown. */
2720
+ const DESCRIPTION_MAX = 2048;
2721
+ const RESOURCE_TOOL = "mcp_resource_read";
2722
+ const REFUSED_TAKEN = "name already taken";
2723
+ const REFUSED_COLLISION = "maps to the same name as another tool of this server";
2724
+ const RESERVED_TOOL_NAMES = /* @__PURE__ */ new Set([RESOURCE_TOOL, ...TOOL_NAMES]);
2725
+ /** Host-owned MCP tool names that a remote server cannot register, even if disabled. */
2726
+ function reservedToolName(name) {
2727
+ return RESERVED_TOOL_NAMES.has(name);
2728
+ }
2729
+ const AnyObject = z.record(z.string(), z.unknown());
2730
+ const ResourceInput = z.object({
2731
+ server: z.string().describe("The slug of an MCP server this agent selects."),
2732
+ uri: z.string().describe("The resource URI the server listed.")
2733
+ }).strict();
2734
+ const messageOf = (error) => error instanceof Error ? error.message : String(error);
2735
+ const isTimeout = (error) => error?.code === -32001;
2736
+ const isUnauthorized = (error) => error?.name === "UnauthorizedError" || error?.constructor?.name === "UnauthorizedError";
2737
+ /**
2738
+ * The model-visible side: one registration per server tool, visible to the
2739
+ * agents that select its server, replaced whole and synchronously when a new
2740
+ * snapshot arrives; the `mcp_resource_read` tool; approval per call.
2741
+ */
2742
+ function createTools(deps) {
2743
+ const { ctx, store } = deps;
2744
+ const callTimeout = deps.callTimeoutMs ?? 3e5;
2745
+ const registered = /* @__PURE__ */ new Map();
2746
+ const refused = /* @__PURE__ */ new Map();
2747
+ const mapped = /* @__PURE__ */ new Map();
2748
+ const scoped = /* @__PURE__ */ new Map();
2749
+ const handleFor = (serverId) => {
2750
+ let handle = scoped.get(serverId);
2751
+ if (!handle) {
2752
+ handle = ctx.forAgents((agentId) => store.isSelected(agentId, serverId));
2753
+ scoped.set(serverId, handle);
2754
+ }
2755
+ return handle;
2756
+ };
2757
+ const notConnected = (serverId, name) => {
2758
+ const status = deps.connections().status(serverId);
2759
+ if (status.state === "connected") return void 0;
2760
+ if (status.state === "needs-auth") return {
2761
+ content: `MCP server ${name} 需要重新授权`,
2762
+ isError: true
2763
+ };
2764
+ return {
2765
+ content: `MCP server ${name} 当前未连接:${status.reason ?? status.state}`,
2766
+ isError: true
2767
+ };
2768
+ };
2769
+ async function approve(serverId, server, tool, input, exec) {
2770
+ const decision = deps.approval.decide(exec, {
2771
+ id: `mcp:${server.slug}:${tool}`,
2772
+ subject: `call ${tool} on MCP server ${server.name}`,
2773
+ reason: truncate(JSON.stringify(input ?? {}), 2e3),
2774
+ accepts: [
2775
+ "allowed-once",
2776
+ "allowed-session",
2777
+ "allowed-always",
2778
+ "rejected"
2779
+ ],
2780
+ remember: {
2781
+ key: `mcp:${serverId}:${tool}`,
2782
+ label: `调用 MCP 服务器「${server.name}」的 ${tool}`
2783
+ }
2784
+ });
2785
+ if (decision.kind === "ask") return decision.result;
2786
+ const result = decision.result;
2787
+ switch (result.kind) {
2788
+ case "allowed-once":
2789
+ case "allowed-session":
2790
+ case "allowed-always": return;
2791
+ case "record-failed": return {
2792
+ content: `could not remember the approval, so the call was not made: ${result.message}`,
2793
+ isError: true
2794
+ };
2795
+ case "rejected": {
2796
+ const reason = result.reason?.trim() ?? "";
2797
+ return {
2798
+ content: reason ? `permission refused by the person: ${reason}` : "permission refused by the person.",
2799
+ isError: true
2800
+ };
2801
+ }
2802
+ case "unavailable": return {
2803
+ content: "approval prompts are disabled; this MCP tool cannot be called",
2804
+ isError: true
2805
+ };
2806
+ }
2807
+ }
2808
+ async function call(serverId, tool, input, exec) {
2809
+ const record = store.server(serverId);
2810
+ if (!record || !store.isSelected(exec.address.agentId, serverId)) return {
2811
+ content: "this MCP server is not selected by this agent",
2812
+ isError: true
2813
+ };
2814
+ const down = notConnected(serverId, record.name);
2815
+ if (down) return down;
2816
+ const gate = await approve(serverId, record, tool.name, input, exec);
2817
+ if (gate) return gate;
2818
+ const live = deps.connections().live(serverId);
2819
+ if (!live) return notConnected(serverId, record.name) ?? {
2820
+ content: "not connected",
2821
+ isError: true
2822
+ };
2823
+ try {
2824
+ const result = await live.client.callTool({
2825
+ name: tool.name,
2826
+ arguments: input
2827
+ }, void 0, {
2828
+ signal: exec.signal,
2829
+ timeout: callTimeout
2830
+ });
2831
+ const { text: raw, files } = toolResultContent(result);
2832
+ return {
2833
+ content: truncate(redact(raw, live.secrets), TOOL_RESULT_LIMIT),
2834
+ ...result.isError === true ? { isError: true } : {},
2835
+ ...files.length === 0 ? {} : { files }
2836
+ };
2837
+ } catch (error) {
2838
+ if (isTimeout(error)) return {
2839
+ content: `调用超时(${Math.round(callTimeout / 6e4)} 分钟)`,
2840
+ isError: true
2841
+ };
2842
+ if (exec.signal.aborted) return {
2843
+ content: "the call was cancelled",
2844
+ isError: true
2845
+ };
2846
+ if (isUnauthorized(error)) {
2847
+ deps.connections().needsAuth(serverId, "the server refused the stored authorization");
2848
+ return {
2849
+ content: `MCP server ${record.name} 需要重新授权`,
2850
+ isError: true
2851
+ };
2852
+ }
2853
+ return {
2854
+ content: `MCP server ${record.name} 调用失败:${redact(messageOf(error), live.secrets)}`,
2855
+ isError: true
2856
+ };
2857
+ }
2858
+ }
2859
+ const definitionKey = (serverName, tool) => JSON.stringify([
2860
+ serverName,
2861
+ tool.name,
2862
+ tool.description ?? "",
2863
+ tool.inputSchema
2864
+ ]);
2865
+ /**
2866
+ * Replaces a server's registrations with what `snapshot` lists, in one
2867
+ * synchronous pass: withdraws what disappeared, registers what is new and
2868
+ * re-registers what changed. `undefined` withdraws everything.
2869
+ */
2870
+ function apply(serverId, snapshot) {
2871
+ const current = registered.get(serverId) ?? /* @__PURE__ */ new Map();
2872
+ const record = store.server(serverId);
2873
+ const nextRefused = /* @__PURE__ */ new Map();
2874
+ const nextMapped = /* @__PURE__ */ new Map();
2875
+ const wanted = /* @__PURE__ */ new Map();
2876
+ if (snapshot && record) {
2877
+ const clashes = collisions(snapshot.tools, (tool) => toolName(record.slug, tool.name));
2878
+ for (const tool of snapshot.tools) {
2879
+ const name = toolName(record.slug, tool.name);
2880
+ nextMapped.set(tool.name, name);
2881
+ if (reservedToolName(name)) nextRefused.set(tool.name, REFUSED_TAKEN);
2882
+ else if (clashes.has(name)) nextRefused.set(tool.name, REFUSED_COLLISION);
2883
+ else wanted.set(name, {
2884
+ tool,
2885
+ key: definitionKey(record.name, tool)
2886
+ });
2887
+ }
2888
+ }
2889
+ for (const [name, entry] of current) {
2890
+ if (wanted.get(name)?.key === entry.key) continue;
2891
+ entry.dispose();
2892
+ current.delete(name);
2893
+ }
2894
+ for (const [name, { tool, key }] of wanted) {
2895
+ if (current.has(name) || !record) continue;
2896
+ const description = `[MCP · ${record.name}] ${tool.description ?? ""}`.slice(0, DESCRIPTION_MAX);
2897
+ try {
2898
+ const dispose = handleFor(serverId).tools.register({
2899
+ name,
2900
+ description,
2901
+ inputSchema: AnyObject,
2902
+ jsonSchema: tool.inputSchema,
2903
+ execute: (input, exec) => call(serverId, tool, input, exec)
2904
+ });
2905
+ current.set(name, {
2906
+ dispose,
2907
+ key
2908
+ });
2909
+ } catch (error) {
2910
+ nextRefused.set(tool.name, REFUSED_TAKEN);
2911
+ deps.log.warn(`MCP tool ${name} was not registered: ${messageOf(error)}`);
2912
+ }
2913
+ }
2914
+ registered.set(serverId, current);
2915
+ refused.set(serverId, nextRefused);
2916
+ mapped.set(serverId, nextMapped);
2917
+ if (!snapshot) {
2918
+ registered.delete(serverId);
2919
+ refused.delete(serverId);
2920
+ mapped.delete(serverId);
2921
+ }
2922
+ }
2923
+ /** Forgets a removed server's registrations. */
2924
+ function forget(serverId) {
2925
+ apply(serverId, void 0);
2926
+ scoped.delete(serverId);
2927
+ }
2928
+ async function readResource(input, exec) {
2929
+ const record = store.serverBySlug(input.server);
2930
+ if (!record || !store.isSelected(exec.address.agentId, record.id)) return {
2931
+ content: `server "${input.server}" is not selected by this agent`,
2932
+ isError: true
2933
+ };
2934
+ const down = notConnected(record.id, record.name);
2935
+ if (down) return down;
2936
+ const live = deps.connections().live(record.id);
2937
+ if (!live) return {
2938
+ content: `MCP server ${record.name} 当前未连接`,
2939
+ isError: true
2940
+ };
2941
+ try {
2942
+ return { content: truncate(redact(readResultText(await live.client.readResource({ uri: input.uri }, {
2943
+ signal: exec.signal,
2944
+ timeout: callTimeout
2945
+ })), live.secrets), RESOURCE_LIMIT) };
2946
+ } catch (error) {
2947
+ if (isTimeout(error)) return {
2948
+ content: `调用超时(${Math.round(callTimeout / 6e4)} 分钟)`,
2949
+ isError: true
2950
+ };
2951
+ return {
2952
+ content: `reading ${input.uri} from MCP server ${record.name} failed: ${redact(messageOf(error), live.secrets)}`,
2953
+ isError: true
2954
+ };
2955
+ }
2956
+ }
2957
+ /** Registers `mcp_resource_read`, visible to an agent that selects a server
2958
+ * offering resources. */
2959
+ function registerResourceTool() {
2960
+ return ctx.forAgents((agentId) => store.agentServers(agentId).some((id) => (deps.connections().snapshot(id)?.resources.length ?? 0) > 0)).tools.register({
2961
+ name: RESOURCE_TOOL,
2962
+ description: "Read a resource from an MCP server this agent selects, by the server slug and the resource URI.",
2963
+ inputSchema: ResourceInput,
2964
+ execute: readResource
2965
+ });
2966
+ }
2967
+ return {
2968
+ apply,
2969
+ forget,
2970
+ registerResourceTool,
2971
+ /** The catalog `getServer` shows: every listed tool, its mapped name and
2972
+ * why it was refused, if it was. */
2973
+ catalogTools(serverId, snapshot) {
2974
+ const names = mapped.get(serverId);
2975
+ const refusals = refused.get(serverId);
2976
+ return (snapshot?.tools ?? []).map((tool) => {
2977
+ const reason = refusals?.get(tool.name);
2978
+ return {
2979
+ name: tool.name,
2980
+ mappedName: names?.get(tool.name) ?? tool.name,
2981
+ ...reason ? { refused: reason } : {}
2982
+ };
2983
+ });
2984
+ }
2985
+ };
2986
+ }
2987
+ //#endregion
2988
+ //#region src/index.ts
2989
+ /** The plugin, with its connection timing replaced where a test asks. */
2990
+ function createMcpPlugin(options = {}) {
2991
+ return {
2992
+ name: "@eum-agent/integration-mcp",
2993
+ configSchema: McpConfig,
2994
+ requires: [
2995
+ "credentials",
2996
+ "host-commands",
2997
+ "protocol-processes",
2998
+ "network",
2999
+ "approval",
3000
+ "work-lifecycle",
3001
+ "agent-definition",
3002
+ "agent-definition-management",
3003
+ "agent-configuration-store"
3004
+ ],
3005
+ apply(ctx, config) {
3006
+ const store = createMcpStore(ctx.storage.open());
3007
+ const commands = ctx.services.get("host-commands");
3008
+ const credentials = ctx.services.get("credentials");
3009
+ const network = ctx.services.get("network");
3010
+ const processes = ctx.services.get("protocol-processes");
3011
+ const approval = ctx.services.get("approval");
3012
+ const definitions = ctx.services.get("agent-definition");
3013
+ const management = ctx.services.get("agent-definition-management");
3014
+ const configuration = ctx.services.get("agent-configuration-store");
3015
+ const agentConfig = {
3016
+ state: management.state,
3017
+ check: management.check,
3018
+ prepare: management.prepare,
3019
+ save(ids, write, execution) {
3020
+ return management.save(ids, () => {
3021
+ ctx.signal.throwIfAborted();
3022
+ const result = write();
3023
+ for (const id of ids) configuration.write(ctx.pluginName, id, { mcpServerIds: store.agentServers(id) });
3024
+ return result;
3025
+ }, execution);
3026
+ }
3027
+ };
3028
+ let selfWriting = 0;
3029
+ const selfWrite = (write) => {
3030
+ selfWriting += 1;
3031
+ try {
3032
+ return write();
3033
+ } finally {
3034
+ selfWriting -= 1;
3035
+ }
3036
+ };
3037
+ const oauth = createOAuth({
3038
+ credentials,
3039
+ fetch: network.fetch,
3040
+ selfWrite,
3041
+ log: ctx.log,
3042
+ ...options.authorizationTimeoutMs === void 0 ? {} : { timeoutMs: options.authorizationTimeoutMs }
3043
+ });
3044
+ let connections;
3045
+ const tools = createTools({
3046
+ ctx,
3047
+ store,
3048
+ connections: () => connections,
3049
+ approval,
3050
+ log: ctx.log,
3051
+ ...options.callTimeoutMs === void 0 ? {} : { callTimeoutMs: options.callTimeoutMs }
3052
+ });
3053
+ let announce = () => {};
3054
+ connections = createConnections({
3055
+ commands,
3056
+ owner: ctx.pluginName,
3057
+ store,
3058
+ processes,
3059
+ network,
3060
+ credentials,
3061
+ oauth,
3062
+ log: ctx.log,
3063
+ onSnapshot: (serverId, snapshot) => {
3064
+ if (!ctx.signal.aborted) tools.apply(serverId, snapshot);
3065
+ },
3066
+ onChanged: () => {
3067
+ if (!ctx.signal.aborted) announce();
3068
+ },
3069
+ ...options.timing ? { timing: options.timing } : {},
3070
+ ...options.inherited ? { inherited: options.inherited } : {}
3071
+ });
3072
+ const prompts = createPrompts({
3073
+ store,
3074
+ connections: () => connections
3075
+ });
3076
+ const secretsOf = (serverId) => {
3077
+ const record = store.server(serverId);
3078
+ if (!record) return [];
3079
+ const read = (name) => {
3080
+ try {
3081
+ return credentials.get(serverId, name);
3082
+ } catch {
3083
+ return;
3084
+ }
3085
+ };
3086
+ return [...credentialNames(record).map(read), ...oauth.secrets(serverId)];
3087
+ };
3088
+ const methods = registerMethods({
3089
+ commands,
3090
+ ctx,
3091
+ store,
3092
+ connections,
3093
+ tools,
3094
+ prompts,
3095
+ oauth,
3096
+ clearCredentials: (serverId) => selfWrite(() => credentials.clear(serverId)),
3097
+ secretsOf,
3098
+ agentConfig
3099
+ });
3100
+ ctx.agentConfiguration.register({
3101
+ schema: z.strictObject({ mcpServerIds: z.array(z.string().min(1)).default([]) }).default({ mcpServerIds: [] }),
3102
+ read: (id) => ({ mcpServerIds: store.agentServers(id) }),
3103
+ remove(id) {
3104
+ return {
3105
+ apply: () => store.setAgentServers(id, []),
3106
+ abort() {},
3107
+ settle() {}
3108
+ };
3109
+ },
3110
+ prepare(id, value) {
3111
+ for (const server of value.mcpServerIds) if (!store.server(server)) throw new Error(`Missing MCP server ${server}`);
3112
+ return {
3113
+ apply() {
3114
+ store.setAgentServers(id, value.mcpServerIds);
3115
+ configuration.write(ctx.pluginName, id, value);
3116
+ },
3117
+ abort() {},
3118
+ settle() {
3119
+ methods.management.selectionChanged(id);
3120
+ }
3121
+ };
3122
+ }
3123
+ });
3124
+ announce = methods.announce;
3125
+ const disabled = new Set(config.disabled);
3126
+ registerMcpManagementTools({
3127
+ definitions,
3128
+ approval,
3129
+ store,
3130
+ connections,
3131
+ credentials,
3132
+ oauth,
3133
+ management: methods.management,
3134
+ register: (tool) => {
3135
+ if (!disabled.has(tool.name)) ctx.tools.register(tool);
3136
+ },
3137
+ onDispose: (dispose) => ctx.onDispose(dispose)
3138
+ });
3139
+ ctx.tools.guide({
3140
+ title: "MCP servers",
3141
+ entries: [
3142
+ {
3143
+ tools: ["mcp_server_list"],
3144
+ 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."
3145
+ },
3146
+ {
3147
+ tools: ["mcp_server_create"],
3148
+ text: "`mcp_server_create` proposes a new server and normally selects it for this agent."
3149
+ },
3150
+ {
3151
+ tools: ["mcp_server_update"],
3152
+ text: "`mcp_server_update` proposes changes to a server this agent selects; shared changes affect every selecting agent."
3153
+ },
3154
+ {
3155
+ tools: ["mcp_server_set_selected"],
3156
+ text: "`mcp_server_set_selected` changes only this agent’s selection."
3157
+ }
3158
+ ]
3159
+ });
3160
+ tools.registerResourceTool();
3161
+ const offCredentials = credentials.onChanged((scope) => {
3162
+ if (ctx.signal.aborted || selfWriting > 0 || !store.server(scope)) return;
3163
+ connections.reconcile(scope, { keepSnapshot: true });
3164
+ });
3165
+ let withdrawn = false;
3166
+ let unbind = () => {};
3167
+ let drained;
3168
+ const drain = () => {
3169
+ drained ??= (async () => {
3170
+ oauth.shutdown();
3171
+ const results = await Promise.allSettled([connections.shutdown()]);
3172
+ results.push(...await Promise.allSettled([processes.shutdown()]));
3173
+ const failures = results.filter((result) => result.status === "rejected");
3174
+ if (failures.length) throw new AggregateError(failures.map((result) => result.reason), "MCP cleanup failed");
3175
+ if (withdrawn) {
3176
+ unbind();
3177
+ unbind = () => {};
3178
+ }
3179
+ })().catch((error) => {
3180
+ drained = void 0;
3181
+ throw error;
3182
+ });
3183
+ return drained;
3184
+ };
3185
+ unbind = ctx.services.get("work-lifecycle").register(drain);
3186
+ ctx.onDispose(async () => {
3187
+ withdrawn = true;
3188
+ offCredentials();
3189
+ await drain();
3190
+ unbind();
3191
+ unbind = () => {};
3192
+ });
3193
+ connections.boot();
3194
+ const ui = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
3195
+ if (!options.withoutUi && existsSync(ui)) ctx.client.registerUi({ module: ui });
3196
+ }
3197
+ };
3198
+ }
3199
+ const mcpPlugin = createMcpPlugin();
3200
+ //#endregion
3201
+ export { TOOL_NAMES, createMcpPlugin, mcpPlugin as default, mcpPlugin };