@eum-agent/integration-mcp 1.1.0 → 1.2.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.
package/dist/index.js CHANGED
@@ -1,51 +1,30 @@
1
+ import { a as withResourceBudget } from "./limits-CiNML2zk.js";
2
+ import { createRequire } from "node:module";
3
+ import { dirname, isAbsolute, posix, win32 } from "node:path";
1
4
  import { existsSync } from "node:fs";
2
5
  import { fileURLToPath } from "node:url";
3
6
  import { z } from "zod";
4
- import { isAbsolute, posix, win32 } from "node:path";
5
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
6
- import { PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
7
- import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
8
- import { AsyncLocalStorage } from "node:async_hooks";
9
- import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";
10
7
  import { createHash, randomBytes, randomUUID } from "node:crypto";
11
8
  import { isDeepStrictEqual } from "node:util";
12
9
  import { setImmediate } from "node:timers/promises";
13
10
  import { createServer } from "node:http";
14
- import { auth, discoverOAuthServerInfo, refreshAuthorization, selectResourceURL } from "@modelcontextprotocol/sdk/client/auth.js";
15
- import { OAuthError, ServerError } from "@modelcontextprotocol/sdk/server/auth/errors.js";
16
- import { Ajv } from "ajv";
17
- import { Ajv2019 } from "ajv/dist/2019.js";
18
- import { Ajv2020 } from "ajv/dist/2020.js";
19
- import addFormats from "ajv-formats";
20
11
  //#region src/names.ts
21
- /**
22
- * The name rules both halves apply: the gateway's zod in `config.ts` and the
23
- * settings form in `ui/draft.ts`. Imports nothing, so the browser program can
24
- * take it without Node types.
25
- */
26
- /** A server's short name: part of every tool and command name it contributes. */
27
12
  const SLUG = /^[a-z0-9][a-z0-9-]{0,23}$/;
28
- /** An environment variable a person configures: a portable shell identifier. */
29
13
  const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
30
- /** An HTTP header name (RFC 9110 token) that is also a valid credential name. */
31
14
  const HEADER_NAME = /^[A-Za-z0-9_][A-Za-z0-9_-]{0,99}$/;
32
15
  //#endregion
33
16
  //#region src/config.ts
34
17
  const EnvEntrySchema = z.object({
35
18
  name: z.string().regex(ENV_NAME, "environment variable names must match ^[A-Za-z_][A-Za-z0-9_]*$").refine((name) => !name.startsWith("YAOGUANG_"), "YAOGUANG_* variables are reserved").describe("Environment variable identifier; YAOGUANG_* is reserved."),
36
- /** A credential: its value lives in the credential manager as `env.<name>`. */
37
19
  secret: z.boolean().describe("True uses an existing env.<name> credential and forbids value; false requires a plain value."),
38
- /** The plain value; absent for a credential. */
39
20
  value: z.string().max(32768).refine((value) => !value.includes("\0"), "invalid environment value").optional().describe("Plain environment value, maximum 32768 UTF-16 code units and no NUL. Omit for a credential.")
40
21
  }).strict().refine((entry) => entry.secret || entry.value !== void 0, "a plain variable needs a value").refine((entry) => !entry.secret || entry.value === void 0, "a credential is not stored here");
41
- /** A local command. `command` is an absolute path or a bare name looked up on PATH. */
42
22
  const StdioConfigSchema = z.object({
43
23
  command: z.string().refine((command) => command.trim().length > 0 && !command.includes("\0"), "command is required").min(1, "command is required").max(4096).refine((command) => isAbsolute(command) || /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(command) || !/[\\/:]/.test(command), "command must be an absolute path or a bare command name").describe("Executable absolute path or bare PATH name, maximum 4096 UTF-16 code units. Shell command text is not accepted."),
44
24
  args: z.array(z.string().max(32768).refine((value) => !value.includes("\0"), "invalid argument")).max(256).default([]).describe("Direct argv array, default empty, maximum 256 arguments; each is at most 32768 UTF-16 code units and contains no NUL."),
45
25
  cwd: z.string().refine((cwd) => !cwd.includes("\0") && (isAbsolute(cwd) || /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(cwd)), "cwd must be an absolute path").optional().describe("Optional absolute working directory using host path syntax; no NUL."),
46
26
  env: z.array(EnvEntrySchema).max(256).default([]).describe("Environment entries, default empty, maximum 256. Duplicate names must declare equal values.")
47
27
  }).strict().refine((config) => config.env.every((entry, index) => config.env.slice(0, index).every((previous) => previous.name !== entry.name || previous.secret === entry.secret && previous.value === entry.value)), "environment variable aliases must have equal values");
48
- /** A remote Streamable HTTP endpoint. Header values are credentials (`header.<name>`). */
49
28
  const HttpConfigSchema = z.object({
50
29
  url: z.string().trim().refine((url) => {
51
30
  try {
@@ -62,7 +41,6 @@ const HttpConfigSchema = z.object({
62
41
  ]).describe("Authentication mode: none, stored header credentials, or OAuth."),
63
42
  headers: z.array(z.string().regex(HEADER_NAME, "invalid header name")).max(64).default([]).describe("Unique header credential names, maximum 64, default empty; allowed only with auth=headers. Values come from header.<name> credentials.")
64
43
  }).strict().refine((config) => new Set(config.headers.map((name) => name.toLowerCase())).size === config.headers.length, "header names must be unique").refine((config) => config.auth === "headers" || config.headers.length === 0, "headers are only sent when auth is \"headers\"");
65
- /** What a person saves; `id` absent creates a server. */
66
44
  const SaveServerSchema = z.discriminatedUnion("transport", [z.object({
67
45
  id: z.string().uuid().optional(),
68
46
  slug: z.string(),
@@ -78,12 +56,9 @@ const SaveServerSchema = z.discriminatedUnion("transport", [z.object({
78
56
  config: HttpConfigSchema,
79
57
  acknowledge: z.boolean().optional()
80
58
  }).strict()]);
81
- /** Refuses a slug that is malformed; uniqueness is the store's. */
82
59
  function checkSlug(slug) {
83
60
  if (!SLUG.test(slug)) throw new Error(`slug must match ${SLUG.source}`);
84
61
  }
85
- /** What a person acknowledges for a stdio server: the command line, where it
86
- * runs and which variables it is given. A value change is not in it. */
87
62
  function acknowledgementKey(config, platform = process.platform) {
88
63
  return JSON.stringify([
89
64
  config.command,
@@ -92,17 +67,13 @@ function acknowledgementKey(config, platform = process.platform) {
92
67
  [...new Set(config.env.map((entry) => platform === "win32" ? entry.name.toUpperCase() : entry.name))].sort()
93
68
  ]);
94
69
  }
95
- /** The credential name that holds a secret environment variable's value. */
96
70
  const envCredential = (name) => `env.${name}`;
97
- /** The credential name that holds a header's value. */
98
71
  const headerCredential = (name) => `header.${name}`;
99
72
  const OAUTH_TOKENS = "oauth.tokens";
100
73
  const OAUTH_CLIENT = "oauth.client";
101
- /** Every credential name a configuration refers to (OAuth excluded). */
102
74
  function credentialNames(record) {
103
75
  return record.transport === "stdio" ? record.config.env.filter((entry) => entry.secret).map((entry) => envCredential(entry.name)) : record.config.auth === "headers" ? record.config.headers.map(headerCredential) : [];
104
76
  }
105
- /** Resolves bare executables and the real cwd before their launch is acknowledged. */
106
77
  async function resolveStdioConfig(config, commands) {
107
78
  const plain = Object.fromEntries(config.env.filter((entry) => !entry.secret).map((entry) => [entry.name, entry.value]));
108
79
  const env = commands.environment([commands.childEnvironment(commands.env, "protocol"), plain]);
@@ -120,11 +91,6 @@ async function resolveStdioConfig(config, commands) {
120
91
  }
121
92
  //#endregion
122
93
  //#region src/env.ts
123
- /**
124
- * Filters inherited credentials, preserves explicit credentials and refuses reserved names.
125
- * Each source is validated before layer overrides. The gateway controls proxies; configured
126
- * proxy names are refused. Values are preserved exactly and never included in errors.
127
- */
128
94
  function childEnvironment(input) {
129
95
  const { commands } = input;
130
96
  const configuredSources = [];
@@ -148,11 +114,8 @@ function childEnvironment(input) {
148
114
  configuredEnv: commands.environment([configured])
149
115
  };
150
116
  }
151
- /** A configured credential variable has no stored value. */
152
117
  var MissingCredentialError = class extends Error {
153
- /** Variable name whose credential must be supplied. */
154
118
  variable;
155
- /** Reports the missing variable without revealing a credential value. */
156
119
  constructor(variable) {
157
120
  super(`credential for ${variable} is not set`);
158
121
  this.name = "MissingCredentialError";
@@ -161,25 +124,14 @@ var MissingCredentialError = class extends Error {
161
124
  };
162
125
  //#endregion
163
126
  //#region src/redact.ts
164
- /** What replaces a credential found in outward text. */
165
- const REDACTED = "[已隐去]";
166
- /** The text a status reason becomes when it contains a credential. */
167
- const REDACTED_REASON = "原因中含有凭据,已整段隐去";
168
- /** Fields of an OAuth JSON credential whose values are secrets in their own right. */
127
+ const REDACTED = "[\u5df2\u9690\u53bb]";
128
+ const REDACTED_REASON = "\u539f\u56e0\u4e2d\u542b\u6709\u51ed\u636e\uff0c\u5df2\u6574\u6bb5\u9690\u53bb";
169
129
  const JSON_SECRETS = [
170
130
  "access_token",
171
131
  "refresh_token",
172
132
  "id_token",
173
133
  "client_secret"
174
134
  ];
175
- /**
176
- * The values to compare outward text against, from the credentials a request
177
- * actually used. A JSON credential (`oauth.tokens`, `oauth.client`) is split
178
- * into its secret fields as well, because a server echoes a token, never the
179
- * JSON document holding it. Values shorter than four characters are left out:
180
- * replacing every occurrence of one would destroy the text without protecting
181
- * anything a hint (the last four characters) does not already show.
182
- */
183
135
  function secretValues(raw) {
184
136
  const values = /* @__PURE__ */ new Set();
185
137
  for (const value of raw) {
@@ -196,112 +148,18 @@ function secretValues(raw) {
196
148
  }
197
149
  return [...values].filter((value) => value.length >= 4).sort((a, b) => b.length - a.length);
198
150
  }
199
- /** Whether `text` contains any of `secrets`. */
200
151
  function containsSecret(text, secrets) {
201
152
  return secrets.some((secret) => text.includes(secret));
202
153
  }
203
- /** `text` with every occurrence of every secret replaced by `[已隐去]`. */
204
154
  function redact(text, secrets) {
205
155
  let out = text;
206
156
  for (const secret of secrets) if (out.includes(secret)) out = out.split(secret).join(REDACTED);
207
157
  return out;
208
158
  }
209
- /** A status reason as it may be shown: hidden whole when it contains a secret. */
210
159
  function redactReason(text, secrets) {
211
160
  return containsSecret(text, secrets) ? REDACTED_REASON : text;
212
161
  }
213
162
  //#endregion
214
- //#region src/transport/limits.ts
215
- /** Response framing bounds applied before the SDK accumulates or decodes upstream content. */
216
- /** The maximum complete encoded response admitted by this owner. */
217
- const RESPONSE_BYTES = 8388608;
218
- const resourceBudget = new AsyncLocalStorage();
219
- /** Binds one original resource request to its conservative encoded protocol capacity. */
220
- function withResourceBudget(maxBytes, request) {
221
- return resourceBudget.run(maxBytes, request);
222
- }
223
- /** Returns the current request's bound without adding vendor fields to the protocol. */
224
- function responseBudget() {
225
- const raw = resourceBudget.getStore();
226
- return raw === void 0 ? RESPONSE_BYTES : Math.min(RESPONSE_BYTES, Math.max(6 * raw, 4 * Math.ceil(raw / 3)) + 65536);
227
- }
228
- /** Safe limit failure without an upstream body or credentials. */
229
- function responseLimit() {
230
- return Object.assign(/* @__PURE__ */ new Error("MCP response exceeds declared budget"), { code: "read-limit" });
231
- }
232
- /** Bounds ordinary bodies and each SSE event while preserving HTTP metadata and cancellation. */
233
- function boundedFetch(fetch, maxBytes = RESPONSE_BYTES) {
234
- return async (input, init) => {
235
- const capacity = Math.min(maxBytes, responseBudget());
236
- const response = await fetch(input, init);
237
- if (!response.body) return response;
238
- const sse = response.headers.get("content-type")?.includes("text/event-stream") ?? false;
239
- const length = Number(response.headers.get("content-length"));
240
- if (!sse && Number.isFinite(length) && length > capacity) {
241
- await response.body.cancel();
242
- throw responseLimit();
243
- }
244
- const reader = response.body.getReader();
245
- let bytes = 0, lineBytes = 0;
246
- const body = new ReadableStream({
247
- async pull(controller) {
248
- try {
249
- const next = await reader.read();
250
- if (next.done) {
251
- controller.close();
252
- return;
253
- }
254
- if (sse) for (const byte of next.value) {
255
- bytes++;
256
- if (bytes > capacity) throw responseLimit();
257
- if (byte === 10) {
258
- if (lineBytes === 0 || lineBytes === 1 && previous === 13) bytes = 0;
259
- lineBytes = 0;
260
- } else lineBytes++;
261
- previous = byte;
262
- }
263
- else {
264
- bytes += next.value.byteLength;
265
- if (bytes > capacity) throw responseLimit();
266
- }
267
- controller.enqueue(next.value);
268
- } catch (error) {
269
- await reader.cancel(error).catch(() => {});
270
- controller.error(error);
271
- }
272
- },
273
- cancel: (reason) => reader.cancel(reason)
274
- });
275
- let previous = -1;
276
- const bounded = new Response(body, {
277
- status: response.status,
278
- statusText: response.statusText,
279
- headers: response.headers
280
- });
281
- for (const key of [
282
- "url",
283
- "redirected",
284
- "type"
285
- ]) Object.defineProperty(bounded, key, { value: response[key] });
286
- return bounded;
287
- };
288
- }
289
- //#endregion
290
- //#region src/transport/http.ts
291
- /**
292
- * A Streamable HTTP transport whose every request goes through the gateway's
293
- * network service: the endpoint is one a person configured, so it takes the
294
- * gateway's route and never passes through the allowed-host list. `headers`
295
- * carries the static header credentials; `authProvider` the OAuth tokens.
296
- */
297
- function httpTransport(input) {
298
- return new StreamableHTTPClientTransport(new URL(input.url), {
299
- fetch: boundedFetch(input.fetch),
300
- requestInit: { headers: { ...input.headers } },
301
- ...input.authProvider ? { authProvider: input.authProvider } : {}
302
- });
303
- }
304
- //#endregion
305
163
  //#region src/transport/output-schema.ts
306
164
  function record(value) {
307
165
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -374,12 +232,6 @@ function normalizeResult(result) {
374
232
  tools
375
233
  } : result;
376
234
  }
377
- /**
378
- * Adds a missing root object type only to provably object-only tool output schemas.
379
- * Only replies to tracked tools/list requests are normalized; the SDK still parses
380
- * the complete reply, caches output validators and validates subsequent tool results.
381
- * Delegates transport ownership, session metadata and protocol negotiation unchanged.
382
- */
383
235
  function objectOutputSchemas(transport) {
384
236
  const pending = /* @__PURE__ */ new Set();
385
237
  const wrapped = {
@@ -429,114 +281,12 @@ function objectOutputSchemas(transport) {
429
281
  return wrapped;
430
282
  }
431
283
  //#endregion
432
- //#region src/transport/stdio.ts
433
- /**
434
- * An MCP transport over a host-owned protocol process: newline-delimited
435
- * JSON-RPC on its stdin and stdout. The host spawned the process and alone
436
- * signals it; `close()` asks the host to stop the group and settles once it
437
- * has, rejecting when the host reports the cleanup failed.
438
- */
439
- var ProcessTransport = class {
440
- onclose;
441
- onerror;
442
- onmessage;
443
- process;
444
- buffer = new ReadBuffer();
445
- responseBounds = /* @__PURE__ */ new Map();
446
- bufferedBytes = 0;
447
- closed = false;
448
- stopping;
449
- maxBytes;
450
- constructor(process, maxBytes = RESPONSE_BYTES) {
451
- this.process = process;
452
- this.maxBytes = maxBytes;
453
- }
454
- async start() {
455
- const { stdout, stdin } = this.process;
456
- stdout.on("data", (chunk) => {
457
- if (this.closed) return;
458
- let offset = 0;
459
- while (offset < chunk.length) {
460
- const end = chunk.indexOf(10, offset);
461
- const finish = end === -1 ? chunk.length : end + 1;
462
- const fragment = chunk.subarray(offset, finish);
463
- this.bufferedBytes += fragment.length;
464
- const maximum = this.responseBounds.size ? Math.max(...this.responseBounds.values()) : this.maxBytes;
465
- if (this.bufferedBytes > Math.min(this.maxBytes, maximum)) {
466
- this.buffer.clear();
467
- this.onerror?.(responseLimit());
468
- this.close().catch((error) => this.onerror?.(error));
469
- return;
470
- }
471
- try {
472
- this.buffer.append(fragment);
473
- if (end !== -1) {
474
- this.bufferedBytes = 0;
475
- const message = this.buffer.readMessage();
476
- if (message) {
477
- if ("id" in message && message.id !== void 0) this.responseBounds.delete(message.id);
478
- this.onmessage?.(message);
479
- }
480
- }
481
- } catch (error) {
482
- this.bufferedBytes = 0;
483
- this.buffer.clear();
484
- this.onerror?.(error);
485
- }
486
- offset = finish;
487
- }
488
- });
489
- stdout.on("error", (error) => this.onerror?.(error));
490
- stdin.on("error", (error) => this.onerror?.(error));
491
- this.process.exited.then(() => this.finish(), () => this.finish());
492
- }
493
- send(message) {
494
- if (this.closed) return Promise.reject(/* @__PURE__ */ new Error("server process is not running"));
495
- if ("method" in message && message.method === "notifications/cancelled" && "params" in message) {
496
- const id = message.params?.requestId;
497
- if (typeof id === "string" || typeof id === "number") this.responseBounds.delete(id);
498
- }
499
- if ("id" in message && message.id !== void 0 && "method" in message) {
500
- if (this.responseBounds.size >= 1024) return Promise.reject(Object.assign(/* @__PURE__ */ new Error("too many pending MCP requests"), { code: "read-limit" }));
501
- this.responseBounds.set(message.id, responseBudget());
502
- }
503
- return new Promise((resolve, reject) => {
504
- const { stdin } = this.process;
505
- const done = (error) => error ? reject(error) : void 0;
506
- if (stdin.write(serializeMessage(message), done)) resolve();
507
- else stdin.once("drain", () => resolve());
508
- });
509
- }
510
- close() {
511
- this.stopping ??= Promise.resolve().then(() => this.process.stop()).then(() => this.finish()).catch((error) => {
512
- this.stopping = void 0;
513
- try {
514
- this.finish();
515
- } catch (notification) {
516
- throw new AggregateError([error, notification], "transport stop and close notification failed", { cause: error });
517
- }
518
- throw error;
519
- });
520
- return this.stopping;
521
- }
522
- /** Whether `close()` was asked for, as opposed to the process ending on its own. */
523
- get stopRequested() {
524
- return this.stopping !== void 0;
525
- }
526
- /** The promise of the stop in progress, if any. */
527
- get stopped() {
528
- return this.stopping;
529
- }
530
- finish() {
531
- if (this.closed) return;
532
- this.closed = true;
533
- this.buffer.clear();
534
- this.responseBounds.clear();
535
- this.onclose?.();
536
- }
537
- };
538
- //#endregion
539
284
  //#region src/connections.ts
285
+ let connectionSdk;
286
+ async function loadConnectionSdk() {
287
+ connectionSdk ??= await import("./connection-sdk-DYfRLV61.js");
288
+ return connectionSdk;
289
+ }
540
290
  const TIMING = {
541
291
  handshakeMs: 3e4,
542
292
  backoffMs: 1e3,
@@ -546,8 +296,8 @@ const TIMING = {
546
296
  concurrency: 4,
547
297
  stderrSettleMs: 50
548
298
  };
549
- const UNACKNOWLEDGED = "尚未确认以用户权限运行";
550
- const CREDENTIAL_UNAVAILABLE = "凭据无法读取,请重新填写";
299
+ const UNACKNOWLEDGED = "\u5c1a\u672a\u786e\u8ba4\u4ee5\u7528\u6237\u6743\u9650\u8fd0\u884c";
300
+ const CREDENTIAL_UNAVAILABLE = "\u51ed\u636e\u65e0\u6cd5\u8bfb\u53d6\uff0c\u8bf7\u91cd\u65b0\u586b\u5199";
551
301
  const CLIENT_INFO = {
552
302
  name: "yaoguang",
553
303
  version: "1.0.0"
@@ -558,15 +308,6 @@ function isNeedsAuth(error) {
558
308
  return name === "UnauthorizedError" || name === "NeedsAuthorizationError" || error?.constructor?.name === "UnauthorizedError";
559
309
  }
560
310
  const messageOf$1 = (error) => error instanceof Error ? error.message : String(error);
561
- /**
562
- * One connection per enabled server: the state machine, generations, the
563
- * start queue, handshake deadline, paged listing, serial snapshot updates,
564
- * reconnection with backoff, and closing.
565
- *
566
- * Every change of configuration, enablement, authorization or credentials
567
- * bumps the server's generation first; anything that resolves afterwards
568
- * compares its generation before it writes, registers or changes a status.
569
- */
570
311
  function createConnections(deps) {
571
312
  const timing = {
572
313
  ...TIMING,
@@ -575,10 +316,7 @@ function createConnections(deps) {
575
316
  const connections = /* @__PURE__ */ new Map();
576
317
  let closed = false;
577
318
  let active = 0;
578
- /** Attempts and test connections under way; shutdown waits for each. */
579
319
  const running = /* @__PURE__ */ new Set();
580
- /** Transports of attempts and tests not yet live; shutdown closes them so
581
- * a handshake in progress ends at once rather than at its deadline. */
582
320
  const starting = /* @__PURE__ */ new Set();
583
321
  const receipts = /* @__PURE__ */ new Set();
584
322
  const pendingStops = /* @__PURE__ */ new Map();
@@ -647,7 +385,6 @@ function createConnections(deps) {
647
385
  task.catch(() => {});
648
386
  return task;
649
387
  };
650
- /** Closes the live transport, retaining failed cleanup for the next drain. */
651
388
  const drop = (conn) => {
652
389
  const live = conn.live;
653
390
  conn.live = void 0;
@@ -662,9 +399,8 @@ function createConnections(deps) {
662
399
  conn.snapshot = snapshot;
663
400
  deps.onSnapshot(conn.id, snapshot);
664
401
  };
665
- /** The credential values and transport one attempt uses. Throws a reason.
666
- * `secrets` answers the values current at the moment it is called. */
667
402
  const prepare = async (record, conn, gen) => {
403
+ const sdk = await loadConnectionSdk();
668
404
  const current = () => {
669
405
  if (closed || conn.gen !== gen) throw new Superseded();
670
406
  };
@@ -727,7 +463,7 @@ function createConnections(deps) {
727
463
  }
728
464
  const fixed = secretValues(used);
729
465
  return {
730
- transport: new ProcessTransport(process_),
466
+ transport: new sdk.ProcessTransport(process_),
731
467
  secrets: () => fixed,
732
468
  process: process_
733
469
  };
@@ -742,7 +478,7 @@ function createConnections(deps) {
742
478
  }
743
479
  const oauth = record.config.auth === "oauth";
744
480
  return {
745
- transport: httpTransport({
481
+ transport: sdk.httpTransport({
746
482
  url: record.config.url,
747
483
  fetch: deps.network.fetch,
748
484
  headers,
@@ -751,8 +487,7 @@ function createConnections(deps) {
751
487
  secrets: () => secretValues(oauth ? [...used, ...deps.oauth.secrets(record.id)] : used)
752
488
  };
753
489
  };
754
- /** Lists everything the server declared, page by page, in full. */
755
- const list = async (client, capabilities, options, only, previous) => {
490
+ const list = async (client, capabilities, options, instructions, only, previous) => {
756
491
  const pages = async (fetchPage) => {
757
492
  const items = [];
758
493
  const seen = /* @__PURE__ */ new Set();
@@ -768,7 +503,6 @@ function createConnections(deps) {
768
503
  } while (cursor !== void 0);
769
504
  return items;
770
505
  };
771
- /** A kind outside `only` keeps what `previous` had; an undeclared one is empty. */
772
506
  const read = async (kind, fetchPage) => {
773
507
  if (only !== void 0 && only !== kind) return void 0;
774
508
  return capabilities[kind] === void 0 ? [] : await pages(fetchPage);
@@ -798,6 +532,7 @@ function createConnections(deps) {
798
532
  const description = client.getServerVersion()?.description?.trim();
799
533
  return {
800
534
  ...description ? { description } : {},
535
+ ...instructions?.trim() ? { instructions } : {},
801
536
  tools: (tools ?? previous?.tools ?? []).map((tool) => ({
802
537
  name: tool.name,
803
538
  ...tool.description ? { description: tool.description } : {},
@@ -816,8 +551,8 @@ function createConnections(deps) {
816
551
  }))
817
552
  };
818
553
  };
819
- /** Initialize plus the first full listing, inside the handshake deadline. */
820
- const handshake = async (transport) => {
554
+ const handshake = async (transport, secrets) => {
555
+ const { Client } = await loadConnectionSdk();
821
556
  const client = new Client(CLIENT_INFO, { capabilities: {} });
822
557
  const deadline = new AbortController();
823
558
  const timer = setTimeout(() => deadline.abort(), timing.handshakeMs);
@@ -827,11 +562,13 @@ function createConnections(deps) {
827
562
  };
828
563
  try {
829
564
  await client.connect(objectOutputSchemas(transport), options);
565
+ const rawInstructions = client.getInstructions();
566
+ const instructions = rawInstructions ? redact(rawInstructions, secrets()) : void 0;
830
567
  const capabilities = client.getServerCapabilities() ?? {};
831
568
  return {
832
569
  client,
833
570
  capabilities,
834
- snapshot: await list(client, capabilities, options)
571
+ snapshot: await list(client, capabilities, options, instructions)
835
572
  };
836
573
  } catch (error) {
837
574
  await client.close().catch(() => {});
@@ -869,7 +606,6 @@ function createConnections(deps) {
869
606
  }, delay);
870
607
  conn.retry.unref?.();
871
608
  };
872
- /** Watches one live connection for an end it did not ask for. */
873
609
  const watch = (conn, gen, client, process_, secrets) => {
874
610
  client.onclose = () => {
875
611
  if (conn.live?.client !== client || conn.gen !== gen || closed) return;
@@ -885,7 +621,7 @@ function createConnections(deps) {
885
621
  const live = conn.live;
886
622
  if (!live || live.client !== client || conn.gen !== gen) return;
887
623
  try {
888
- const next = await list(client, live.capabilities, { timeout: timing.handshakeMs }, kind, conn.snapshot);
624
+ const next = await list(client, live.capabilities, { timeout: timing.handshakeMs }, conn.snapshot?.instructions, kind, conn.snapshot);
889
625
  if (conn.live?.client !== client || conn.gen !== gen) return;
890
626
  publish(conn, next);
891
627
  changed(conn.id);
@@ -899,11 +635,10 @@ function createConnections(deps) {
899
635
  }
900
636
  });
901
637
  };
902
- client.setNotificationHandler(ToolListChangedNotificationSchema, refresh("tools"));
903
- client.setNotificationHandler(ResourceListChangedNotificationSchema, refresh("resources"));
904
- client.setNotificationHandler(PromptListChangedNotificationSchema, refresh("prompts"));
638
+ client.setNotificationHandler(connectionSdk.ToolListChangedNotificationSchema, refresh("tools"));
639
+ client.setNotificationHandler(connectionSdk.ResourceListChangedNotificationSchema, refresh("resources"));
640
+ client.setNotificationHandler(connectionSdk.PromptListChangedNotificationSchema, refresh("prompts"));
905
641
  };
906
- /** One connection attempt within generation `gen`, tracked for shutdown. */
907
642
  const attempt = (conn, gen) => {
908
643
  const work = track(attemptOnce(conn, gen));
909
644
  conn.pending.add(work);
@@ -932,7 +667,7 @@ function createConnections(deps) {
932
667
  prepared = await prepare(record, conn, gen);
933
668
  starting.add(prepared.transport);
934
669
  if (conn.gen !== gen || closed) throw new Superseded();
935
- const { client, capabilities, snapshot } = await handshake(prepared.transport);
670
+ const { client, capabilities, snapshot } = await handshake(prepared.transport, prepared.secrets);
936
671
  if (conn.gen !== gen || closed) {
937
672
  await client.close().catch(() => {});
938
673
  throw new Superseded();
@@ -991,8 +726,6 @@ function createConnections(deps) {
991
726
  release();
992
727
  }
993
728
  };
994
- /** Brings one server's connection in line with its stored record.
995
- * Returns the initial attempt when an enabled server can connect. */
996
729
  const reconcile = (id, options = {}) => {
997
730
  if (closed) return;
998
731
  const conn = connection(id);
@@ -1044,7 +777,6 @@ function createConnections(deps) {
1044
777
  setStatus(conn, { state: "connecting" });
1045
778
  return attempt(conn, conn.gen);
1046
779
  };
1047
- /** The work of `test`, untracked. */
1048
780
  const testOnce = async (id) => {
1049
781
  if (closed) return {
1050
782
  ok: false,
@@ -1070,7 +802,7 @@ function createConnections(deps) {
1070
802
  if (conn?.live && conn.status.state === "connected") {
1071
803
  const live = conn.live;
1072
804
  try {
1073
- const snapshot = await list(live.client, live.capabilities, { timeout: timing.handshakeMs });
805
+ const snapshot = await list(live.client, live.capabilities, { timeout: timing.handshakeMs }, conn.snapshot?.instructions);
1074
806
  if (closed || conn.gen !== gen || conn.live !== live) return {
1075
807
  ok: false,
1076
808
  reason: "the connection changed during testing"
@@ -1124,7 +856,7 @@ function createConnections(deps) {
1124
856
  prepared = await prepare(record, conn, gen);
1125
857
  starting.add(prepared.transport);
1126
858
  if (closed) throw new Error("the plugin is stopping");
1127
- const { client, snapshot } = await handshake(prepared.transport);
859
+ const { client, snapshot } = await handshake(prepared.transport, prepared.secrets);
1128
860
  await client.close().catch(() => {});
1129
861
  return count(snapshot);
1130
862
  } catch (error) {
@@ -1147,12 +879,10 @@ function createConnections(deps) {
1147
879
  }
1148
880
  };
1149
881
  return {
1150
- /** Starts every stored server in the background; returns at once. */
1151
882
  boot() {
1152
- for (const record of deps.store.servers()) reconcile(record.id);
883
+ for (const record of deps.store.servers()) if (!connections.get(record.id)?.gen) reconcile(record.id);
1153
884
  },
1154
885
  reconcile,
1155
- /** Defers only these servers' notifications, leaving other lifecycle events independent. */
1156
886
  async collection(ids, work, publish = true) {
1157
887
  const context = {
1158
888
  ids: new Set(ids),
@@ -1167,7 +897,6 @@ function createConnections(deps) {
1167
897
  if (publish && context.dirty.size) deps.onChanged(context.dirty.values().next().value);
1168
898
  }
1169
899
  },
1170
- /** Joins actual superseded resources; failed handles stay owned for cleanup retry. */
1171
900
  async cleanup(id) {
1172
901
  const conn = cleanupOwners.get(id) ?? connections.get(id);
1173
902
  if (!conn) return {
@@ -1208,12 +937,10 @@ function createConnections(deps) {
1208
937
  snapshot(id) {
1209
938
  return connections.get(id)?.snapshot;
1210
939
  },
1211
- /** The live connection, or `undefined` while not connected. */
1212
940
  live(id) {
1213
941
  const conn = connections.get(id);
1214
942
  return conn?.status.state === "connected" ? conn.live : void 0;
1215
943
  },
1216
- /** A call learned the server wants authorization again. */
1217
944
  needsAuth(id, reason) {
1218
945
  const conn = connections.get(id);
1219
946
  if (!conn || closed) return;
@@ -1226,17 +953,9 @@ function createConnections(deps) {
1226
953
  ...reason ? { reason } : {}
1227
954
  });
1228
955
  },
1229
- /**
1230
- * Lists capabilities: through the live connection when there is one,
1231
- * otherwise restores the enabled server's resident connection and status.
1232
- * Disabled servers use a temporary connection closed before this returns.
1233
- */
1234
956
  test(id) {
1235
957
  return track(testOnce(id));
1236
958
  },
1237
- /** Closes every connection and stops reconnecting; settles once every
1238
- * process group this plugin started has been stopped, including those of
1239
- * handshakes and test connections still under way. */
1240
959
  shutdown() {
1241
960
  closed = true;
1242
961
  shuttingDown ??= Promise.resolve().then(async () => {
@@ -1267,8 +986,6 @@ function createConnections(deps) {
1267
986
  });
1268
987
  return shuttingDown;
1269
988
  },
1270
- /** Whether the stored stdio configuration carries a confirmation that
1271
- * still matches it. */
1272
989
  acknowledged(record, previous) {
1273
990
  if (record.transport !== "stdio" || !previous || previous.transport !== "stdio") return false;
1274
991
  return previous.acknowledgedAt !== null && acknowledgementKey(previous.config, deps.commands.platform) === acknowledgementKey(record.config, deps.commands.platform);
@@ -1277,18 +994,14 @@ function createConnections(deps) {
1277
994
  }
1278
995
  //#endregion
1279
996
  //#region src/batch.ts
1280
- /** Owner-local bounded collection schemas and safe member settlement. */
1281
- /** Stable safe error facts; decrypted server credentials never enter this shape. */
1282
997
  const MemberError = z.strictObject({
1283
998
  code: z.string().max(64),
1284
999
  message: z.string().max(512)
1285
1000
  });
1286
- /** Declared encoded query capacities, independent of collection/page sizes. */
1287
1001
  const queryBudgets = {
1288
1002
  maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
1289
1003
  maxTotalBytes: z.number().int().min(1).max(8388608).default(8388608)
1290
1004
  };
1291
- /** Validates complete input bytes and all declared capacities before any owner IO. */
1292
1005
  function batchInput(shape, key) {
1293
1006
  return z.strictObject(shape).superRefine((value, context) => {
1294
1007
  const input = value;
@@ -1303,7 +1016,6 @@ function batchInput(shape, key) {
1303
1016
  });
1304
1017
  });
1305
1018
  }
1306
- /** Publishes an ordered result only with the explicit nonsensitive target projection. */
1307
1019
  function batchResult(value, target) {
1308
1020
  const identity = {
1309
1021
  index: z.number().int().nonnegative(),
@@ -1319,7 +1031,6 @@ function batchResult(value, target) {
1319
1031
  error: MemberError
1320
1032
  })])) });
1321
1033
  }
1322
- /** Keeps committed business facts immutable while reflecting uncertain or retained cleanup. */
1323
1034
  function operationResult(value) {
1324
1035
  return z.discriminatedUnion("operationState", [
1325
1036
  z.strictObject({
@@ -1340,7 +1051,6 @@ function operationResult(value) {
1340
1051
  })
1341
1052
  ]);
1342
1053
  }
1343
- /** Settles every target in order and enforces complete encoded member and aggregate sizes. */
1344
1054
  async function settle(targets, work, limits, failure) {
1345
1055
  const results = [];
1346
1056
  let bytes = 8192;
@@ -1370,7 +1080,6 @@ async function settle(targets, work, limits, failure) {
1370
1080
  }
1371
1081
  return { results };
1372
1082
  }
1373
- /** Complete resource declarations reserve raw bytes and worst encoded protocol/output capacity. */
1374
1083
  function resourceInput(extra, member) {
1375
1084
  return batchInput({
1376
1085
  ...extra,
@@ -1393,10 +1102,6 @@ function resourceInput(extra, member) {
1393
1102
  }
1394
1103
  //#endregion
1395
1104
  //#region src/management.ts
1396
- /**
1397
- * Validates and saves one server, optionally selecting a new one for an agent.
1398
- * Rejects edits whose captured server changed during asynchronous command resolution.
1399
- */
1400
1105
  async function saveServer(deps, input, selectFor, ctx) {
1401
1106
  const { store, connections, tools, oauth } = deps;
1402
1107
  checkSlug(input.slug);
@@ -1445,45 +1150,107 @@ async function saveServer(deps, input, selectFor, ctx) {
1445
1150
  return record;
1446
1151
  }
1447
1152
  //#endregion
1448
- //#region src/output-schema.ts
1449
- /** Validates complete owner business results and bounded recoverable delivery failures. */
1450
- /** Adds the standard failure envelope and bounded text refusals to an owner's result schema. */
1451
- function toolOutputSchema(body, input, name) {
1452
- return z.union([
1453
- body,
1454
- z.strictObject({
1455
- ok: z.literal(false),
1456
- error: z.strictObject({
1457
- code: z.string().min(1).max(128),
1458
- message: z.string().refine((value) => [...value].length <= 256).meta({ maxLength: 256 }),
1459
- retryable: z.boolean(),
1460
- field: z.string().max(256).optional(),
1461
- maximum: z.number().finite().optional()
1462
- }),
1463
- next: z.strictObject({
1464
- tool: z.literal(name),
1465
- arguments: input
1466
- }).nullable(),
1467
- execution: z.strictObject({ state: z.enum([
1468
- "not-started",
1469
- "committed",
1470
- "unknown"
1471
- ]) }).optional()
1472
- }),
1473
- z.string().max(1024)
1474
- ]);
1153
+ //#region src/body-document.ts
1154
+ const LocalBodyRefSchema = z.strictObject({
1155
+ bodyId: z.uuid(),
1156
+ codec: z.enum([
1157
+ "utf8-text",
1158
+ "json",
1159
+ "opaque"
1160
+ ]),
1161
+ formatVersion: z.literal(1),
1162
+ byteLength: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
1163
+ sha256: z.string().regex(/^[a-f0-9]{64}$/)
1164
+ });
1165
+ async function captureTextBody(text, ctx) {
1166
+ ctx.signal.throwIfAborted();
1167
+ const writer = await ctx.openBody("utf8-text", ctx.signal);
1168
+ const encoder = new TextEncoder();
1169
+ let offset = 0;
1170
+ let index = 0;
1171
+ try {
1172
+ while (index < text.length) {
1173
+ ctx.signal.throwIfAborted();
1174
+ const chunk = /* @__PURE__ */ new Uint8Array(65536);
1175
+ let end = Math.min(text.length, index + 32768);
1176
+ if (end < text.length && /[\uD800-\uDBFF]/u.test(text[end - 1])) end--;
1177
+ const { read, written } = encoder.encodeInto(text.slice(index, end), chunk);
1178
+ if (!read) throw new Error("text_encoding_failed");
1179
+ await writer.write(offset, chunk.subarray(0, written), ctx.signal);
1180
+ offset += written;
1181
+ index += read;
1182
+ }
1183
+ return (await writer.seal(ctx.signal)).body;
1184
+ } catch (error) {
1185
+ await writer.abort();
1186
+ throw error;
1187
+ }
1188
+ }
1189
+ function createTextDocuments(render) {
1190
+ const documents = /* @__PURE__ */ new WeakMap();
1191
+ const prepare = (value, ctx) => {
1192
+ const key = typeof value === "object" && value !== null ? value : void 0;
1193
+ const prior = key ? documents.get(key) : void 0;
1194
+ if (prior) return prior;
1195
+ const work = (async () => {
1196
+ const input = render(value);
1197
+ const literals = input.nodes.filter((node) => node.kind === "literal");
1198
+ const lengths = literals.map((node) => new TextEncoder().encode(node.text).byteLength);
1199
+ if (literals.length === input.nodes.length && (lengths.some((length) => length > 4096) || lengths.reduce((sum, length) => sum + length, 0) > 16384 || input.nodes.length > 256)) {
1200
+ const body = await captureTextBody(literals.map((node) => node.text).join(""), ctx);
1201
+ return {
1202
+ formatVersion: 1,
1203
+ rendererVersion: 1,
1204
+ nodes: [{
1205
+ id: "text",
1206
+ kind: "text-range",
1207
+ body,
1208
+ startByte: 0,
1209
+ endByte: body.byteLength
1210
+ }]
1211
+ };
1212
+ }
1213
+ if (lengths.some((length) => length > 4096) || lengths.reduce((sum, length) => sum + length, 0) > 16384) {
1214
+ const nodes = [];
1215
+ const all = lengths.reduce((sum, length) => sum + length, 0) > 16384;
1216
+ for (const node of input.nodes) {
1217
+ if (node.kind !== "literal" || !all && new TextEncoder().encode(node.text).byteLength <= 4096) {
1218
+ nodes.push(node);
1219
+ continue;
1220
+ }
1221
+ const body = await captureTextBody(node.text, ctx);
1222
+ nodes.push({
1223
+ id: node.id,
1224
+ kind: "text-range",
1225
+ body,
1226
+ startByte: 0,
1227
+ endByte: body.byteLength
1228
+ });
1229
+ }
1230
+ return {
1231
+ ...input,
1232
+ nodes
1233
+ };
1234
+ }
1235
+ return input;
1236
+ })();
1237
+ if (key) documents.set(key, work);
1238
+ return work;
1239
+ };
1240
+ return {
1241
+ prepare,
1242
+ formatModel: prepare
1243
+ };
1475
1244
  }
1476
1245
  //#endregion
1477
1246
  //#region src/cursor-cache.ts
1478
- const bytesOf = (value) => 2048 + 2 * (value.content?.length ?? 0);
1479
- /** Owns metadata snapshots; each query and all successor positions share one opaque host lease. */
1247
+ const bytesOf = (value) => 2048 + 2 * (value.metadata?.length ?? 0);
1480
1248
  var QueryCursorCache = class extends Map {
1481
1249
  pending = /* @__PURE__ */ new Map();
1482
1250
  roots = /* @__PURE__ */ new Map();
1483
1251
  resources;
1484
1252
  facts;
1485
1253
  timer;
1486
- /** Measures only retained metadata; source IO uses a separate bounded reservation. */
1487
1254
  constructor(facts, resources) {
1488
1255
  super();
1489
1256
  this.facts = facts;
@@ -1596,7 +1363,6 @@ var QueryCursorCache = class extends Map {
1596
1363
  this.settle(root);
1597
1364
  };
1598
1365
  }
1599
- /** Runs source acquisition under the actual authenticated call, releasing only after its cleanup. */
1600
1366
  async runExclusive(input, call, action, sourceBytes = 4194304) {
1601
1367
  const cursor = typeof input === "object" && input !== null && "cursor" in input ? input.cursor : void 0;
1602
1368
  const saved = cursor === void 0 ? void 0 : this.get(cursor);
@@ -1616,7 +1382,7 @@ var QueryCursorCache = class extends Map {
1616
1382
  "cursor_invalid"
1617
1383
  ].includes(error.message)) throw error;
1618
1384
  return {
1619
- content: JSON.stringify({
1385
+ data: {
1620
1386
  ok: false,
1621
1387
  error: {
1622
1388
  code: error.message,
@@ -1624,14 +1390,14 @@ var QueryCursorCache = class extends Map {
1624
1390
  retryable: false
1625
1391
  },
1626
1392
  next: null
1627
- }),
1393
+ },
1394
+ execution: { state: "not-started" },
1628
1395
  isError: true
1629
1396
  };
1630
1397
  } finally {
1631
1398
  finish?.();
1632
1399
  }
1633
1400
  }
1634
- /** Joins same-cursor preparation before revalidating and replaying its accepted exact page. */
1635
1401
  async run(input, call, action, sourceBytes = 4194304) {
1636
1402
  const cursor = typeof input === "object" && input !== null && "cursor" in input ? input.cursor : void 0;
1637
1403
  if (cursor === void 0) return this.runExclusive(input, call, action, sourceBytes);
@@ -1650,7 +1416,6 @@ var QueryCursorCache = class extends Map {
1650
1416
  if (this.pending.get(cursor) === gate) this.pending.delete(cursor);
1651
1417
  }
1652
1418
  }
1653
- /** Applies the same resource lifecycle to a native model-tool registration. */
1654
1419
  wrap(tool, sourceBytes = 4194304) {
1655
1420
  const execute = tool.execute;
1656
1421
  return {
@@ -1658,12 +1423,11 @@ var QueryCursorCache = class extends Map {
1658
1423
  execute: (input, call) => this.run(input, call, async () => await execute(input, call), sourceBytes)
1659
1424
  };
1660
1425
  }
1661
- /** Accounts an exact candidate before accepting or retaining its snapshot. */
1662
- async prepare(initial, content) {
1426
+ async prepare(initial, metadata) {
1663
1427
  const root = this.roots.get(initial);
1664
1428
  if (!root || root.closing) throw new Error("cursor_invalid");
1665
1429
  root.lease.signal.throwIfAborted();
1666
- const bytes = 2048 + 2 * content.length;
1430
+ const bytes = 2048 + 2 * metadata.length;
1667
1431
  const additional = this.total(root) - root.pendingBytes + bytes - root.heldBytes;
1668
1432
  if (additional > 0) {
1669
1433
  await root.lease.grow(root.call, {
@@ -1674,7 +1438,6 @@ var QueryCursorCache = class extends Map {
1674
1438
  }
1675
1439
  root.pendingBytes = bytes;
1676
1440
  }
1677
- /** Awaits metadata admission before installing a new cursor. */
1678
1441
  async save(key, value) {
1679
1442
  const root = this.roots.get(this.facts(value).initial);
1680
1443
  if (!root || root.closing) throw new Error("cursor_invalid");
@@ -1700,12 +1463,10 @@ var QueryCursorCache = class extends Map {
1700
1463
  }
1701
1464
  return deleted;
1702
1465
  }
1703
- /** Drops retained metadata before releasing its shared reservation. */
1704
1466
  clear() {
1705
1467
  for (const root of [...this.roots.values()]) this.invalidate(root);
1706
1468
  }
1707
1469
  };
1708
- /** Applies a tighter owner-local memory ceiling while preserving shared resident accounting. */
1709
1470
  function trimCursorCache(entries, retained) {
1710
1471
  let bytes = 0;
1711
1472
  for (const entry of entries.values()) bytes += bytesOf(retained(entry));
@@ -1717,26 +1478,120 @@ function trimCursorCache(entries, retained) {
1717
1478
  }
1718
1479
  }
1719
1480
  //#endregion
1720
- //#region src/server-pages.ts
1721
- /** Header-only server pages and explicit bounded safe-detail fragments. */
1722
- const Tokens = z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional().describe("Desired delivery tokens; the host may allocate fewer.");
1723
- const Query = z.union([z.strictObject({ all: z.literal(true).describe("List configured server headers without configuration bodies.") }), z.strictObject({ serverIds: z.array(z.uuid().describe("Exact selected MCP server id.")).min(1).max(64).describe("Selected server ids whose summaries are needed; unknown or unselected members refuse this query.") })]);
1724
- const Start = z.union([z.strictObject({
1725
- queries: z.array(Query).min(1).max(64).describe("Ordered directory queries; limit and tokens are shared by the whole page."),
1726
- view: z.literal("summary").default("summary").describe("Header summaries only; default summary, no configuration bodies."),
1727
- limit: z.number().int().min(1).max(100).default(50).describe("Maximum total server headers on this page; default 50, hard maximum 100."),
1728
- outputTokens: Tokens
1729
- }), z.strictObject({
1730
- queries: z.tuple([z.strictObject({ serverIds: z.tuple([z.uuid()]).describe("Exactly one selected server id for safe configuration details.") })]).describe("Exactly one query containing exactly one selected server id."),
1731
- view: z.literal("details").describe("Safe configuration fragments for exactly one selected server."),
1732
- outputTokens: Tokens
1481
+ //#region src/tool-data.ts
1482
+ const fileVariant = z.strictObject({
1483
+ id: z.string().regex(/^[a-f0-9]{64}$/),
1484
+ mediaType: z.string().min(1),
1485
+ size: z.number().int().positive(),
1486
+ width: z.number().int().positive().optional(),
1487
+ height: z.number().int().positive().optional()
1488
+ });
1489
+ const savedFile = fileVariant.extend({
1490
+ name: z.string().min(1).max(200),
1491
+ forModel: fileVariant.optional()
1492
+ });
1493
+ const McpFailureSchema = z.strictObject({
1494
+ ok: z.literal(false),
1495
+ code: z.string(),
1496
+ message: z.string().max(1024)
1497
+ });
1498
+ const McpRemoteDataSchema = z.union([McpFailureSchema, z.strictObject({
1499
+ ok: z.literal(true),
1500
+ serverId: z.string(),
1501
+ serverName: z.string(),
1502
+ remoteTool: z.string(),
1503
+ registeredName: z.string(),
1504
+ remoteIsError: z.boolean(),
1505
+ mediaCount: z.number().int().nonnegative(),
1506
+ media: z.array(savedFile),
1507
+ publicationNotes: z.array(z.string()),
1508
+ representationError: z.literal("media_not_published").optional(),
1509
+ complete: z.boolean(),
1510
+ body: LocalBodyRefSchema.optional(),
1511
+ captureError: z.literal("source_capture_failed").optional()
1733
1512
  })]);
1734
- const Continue = z.strictObject({
1735
- cursor: z.string().min(1).max(512).regex(/^[\x21-\x7e]+$/).describe("Opaque continuation; copy next.arguments without changing queries or view."),
1736
- outputTokens: Tokens
1513
+ const McpResourceValueSchema = z.strictObject({
1514
+ serverId: z.string(),
1515
+ uri: z.string(),
1516
+ representationError: z.literal("binary_source_unavailable").optional(),
1517
+ binary: z.strictObject({
1518
+ count: z.number().int().positive(),
1519
+ files: z.array(savedFile),
1520
+ notes: z.array(z.string())
1521
+ }).optional(),
1522
+ complete: z.boolean(),
1523
+ body: LocalBodyRefSchema.optional(),
1524
+ captureError: z.literal("source_capture_failed").optional()
1737
1525
  });
1738
- const Input = z.union([Start, Continue]);
1739
- const Header = z.strictObject({
1526
+ const McpResourceDataSchema = z.strictObject({ results: z.array(z.discriminatedUnion("ok", [z.strictObject({
1527
+ index: z.number().int().nonnegative(),
1528
+ target: z.strictObject({
1529
+ server: z.string(),
1530
+ uri: z.string()
1531
+ }),
1532
+ ok: z.literal(true),
1533
+ value: McpResourceValueSchema
1534
+ }), z.strictObject({
1535
+ index: z.number().int().nonnegative(),
1536
+ target: z.strictObject({
1537
+ server: z.string(),
1538
+ uri: z.string()
1539
+ }),
1540
+ ok: z.literal(false),
1541
+ error: z.strictObject({
1542
+ code: z.string(),
1543
+ message: z.string()
1544
+ })
1545
+ })])) });
1546
+ const McpMutationSuccessSchema = z.strictObject({
1547
+ ok: z.literal(true),
1548
+ committed: z.boolean(),
1549
+ status: z.enum(["ok", "unknown"]),
1550
+ data: z.union([
1551
+ z.strictObject({
1552
+ serverId: z.string(),
1553
+ selected: z.boolean(),
1554
+ summary: z.string().max(256)
1555
+ }),
1556
+ z.strictObject({
1557
+ serverId: z.string(),
1558
+ revision: z.string(),
1559
+ summary: z.string().max(256)
1560
+ }),
1561
+ z.strictObject({ summary: z.string().max(256) }),
1562
+ z.discriminatedUnion("operationState", [
1563
+ z.strictObject({
1564
+ operationId: z.uuid(),
1565
+ operationState: z.literal("admitted"),
1566
+ uncertain: z.literal(true)
1567
+ }),
1568
+ z.strictObject({
1569
+ operationId: z.uuid(),
1570
+ operationState: z.literal("committed"),
1571
+ value: z.strictObject({
1572
+ serverIds: z.array(z.string()),
1573
+ revision: z.number(),
1574
+ contentHash: z.string()
1575
+ })
1576
+ }),
1577
+ z.strictObject({
1578
+ operationId: z.uuid(),
1579
+ operationState: z.literal("cleanup-pending"),
1580
+ value: z.strictObject({
1581
+ serverIds: z.array(z.string()),
1582
+ revision: z.number(),
1583
+ contentHash: z.string()
1584
+ }),
1585
+ cleanup: z.array(z.strictObject({
1586
+ code: z.string(),
1587
+ message: z.string()
1588
+ }))
1589
+ })
1590
+ ])
1591
+ ])
1592
+ });
1593
+ const McpMutationDataSchema = z.union([McpMutationSuccessSchema, McpFailureSchema]);
1594
+ const McpServerHeaderSchema = z.strictObject({
1740
1595
  id: z.string(),
1741
1596
  slug: z.string(),
1742
1597
  name: z.string(),
@@ -1745,21 +1600,19 @@ const Header = z.strictObject({
1745
1600
  selected: z.boolean(),
1746
1601
  connectionState: z.string()
1747
1602
  });
1748
- const Next = z.strictObject({
1749
- tool: z.literal("mcp_server_list"),
1750
- arguments: Continue
1751
- });
1752
- const Output = z.strictObject({
1603
+ const McpServerPageSchema = z.strictObject({
1753
1604
  ok: z.literal(true),
1754
1605
  complete: z.boolean(),
1755
1606
  results: z.array(z.union([z.strictObject({
1756
1607
  index: z.number().int().nonnegative(),
1757
1608
  ok: z.literal(true),
1758
1609
  complete: z.boolean(),
1759
- value: z.union([z.array(Header), z.strictObject({
1610
+ value: z.union([z.array(McpServerHeaderSchema), z.strictObject({
1760
1611
  serverId: z.string(),
1761
1612
  field: z.literal("details"),
1762
- text: z.string(),
1613
+ body: LocalBodyRefSchema,
1614
+ startByte: z.number().int().nonnegative(),
1615
+ endByte: z.number().int().nonnegative(),
1763
1616
  range: z.strictObject({
1764
1617
  offset: z.number(),
1765
1618
  length: z.number(),
@@ -1775,41 +1628,273 @@ const Output = z.strictObject({
1775
1628
  message: z.string().refine((value) => [...value].length <= 256).meta({ maxLength: 256 })
1776
1629
  })
1777
1630
  })])),
1778
- next: Next.nullable(),
1631
+ next: z.strictObject({
1632
+ tool: z.literal("mcp_server_list"),
1633
+ arguments: z.object({
1634
+ cursor: z.string(),
1635
+ outputTokens: z.number().optional()
1636
+ })
1637
+ }).nullable(),
1779
1638
  effective: z.strictObject({
1780
1639
  limit: z.number(),
1781
1640
  outputTokens: z.number()
1782
1641
  })
1783
1642
  });
1784
- /** Builds exact pages over native headers; a details call opens only one selected configuration. */
1643
+ const McpServerDataSchema = z.union([McpServerPageSchema, z.strictObject({
1644
+ ok: z.literal(false),
1645
+ error: z.strictObject({
1646
+ code: z.string(),
1647
+ message: z.string(),
1648
+ retryable: z.boolean()
1649
+ }),
1650
+ next: z.unknown()
1651
+ })]);
1652
+ //#endregion
1653
+ //#region src/tool-document.ts
1654
+ function mcpRemoteDocument(data) {
1655
+ if (!data.ok) return {
1656
+ formatVersion: 1,
1657
+ rendererVersion: 1,
1658
+ nodes: [{
1659
+ id: "failure",
1660
+ kind: "literal",
1661
+ text: `${data.code}: ${data.message}`
1662
+ }]
1663
+ };
1664
+ return {
1665
+ formatVersion: 1,
1666
+ rendererVersion: 1,
1667
+ nodes: [
1668
+ {
1669
+ id: "source",
1670
+ kind: "literal",
1671
+ text: `MCP ${data.serverName} (${data.serverId}), ${data.registeredName} / ${data.remoteTool}: ${data.remoteIsError ? "server reported an error" : "response received"}.\n`
1672
+ },
1673
+ ...data.representationError ? [{
1674
+ id: "media-unavailable",
1675
+ kind: "literal",
1676
+ text: `${data.mediaCount - data.media.length} media item(s) could not be published. ${data.publicationNotes.join(" ")}\n`
1677
+ }] : [],
1678
+ ...data.media.map((file, index) => ({
1679
+ id: `media-${index}`,
1680
+ kind: "media-ref",
1681
+ file
1682
+ })),
1683
+ ...data.body ? [{
1684
+ id: "original",
1685
+ kind: "text-range",
1686
+ body: data.body,
1687
+ startByte: 0,
1688
+ endByte: data.body.byteLength
1689
+ }] : [{
1690
+ id: "unavailable",
1691
+ kind: "literal",
1692
+ text: "The remote response completed, but its original text could not be captured. Do not repeat the operation to recover display text."
1693
+ }]
1694
+ ]
1695
+ };
1696
+ }
1697
+ function mcpFailure(message, state = "not-started", code = "mcp_unavailable") {
1698
+ return {
1699
+ data: {
1700
+ ok: false,
1701
+ code,
1702
+ message: message.slice(0, 1024)
1703
+ },
1704
+ execution: { state },
1705
+ isError: true,
1706
+ error: {
1707
+ code,
1708
+ retryable: false
1709
+ }
1710
+ };
1711
+ }
1712
+ function mcpResourceDocument(data) {
1713
+ const nodes = [];
1714
+ for (const row of data.results) {
1715
+ nodes.push({
1716
+ id: `resource-${row.index}`,
1717
+ kind: "literal",
1718
+ text: `MCP resource ${row.target.server}: ${row.target.uri}\n`
1719
+ });
1720
+ if (row.ok && row.value.representationError) nodes.push({
1721
+ id: `binary-unavailable-${row.index}`,
1722
+ kind: "literal",
1723
+ text: `Some binary originals could not be published. ${row.ok ? row.value.binary?.notes.join(" ") ?? "" : ""} The following text is a summary.\n`
1724
+ });
1725
+ if (row.ok) for (const [index, file] of (row.value.binary?.files ?? []).entries()) nodes.push({
1726
+ id: `resource-media-${row.index}-${index}`,
1727
+ kind: "media-ref",
1728
+ file
1729
+ });
1730
+ if (!row.ok) nodes.push({
1731
+ id: `error-${row.index}`,
1732
+ kind: "literal",
1733
+ text: `${row.error.code}: ${row.error.message}\n`
1734
+ });
1735
+ else if (row.value.body) nodes.push({
1736
+ id: `original-${row.index}`,
1737
+ kind: "text-range",
1738
+ body: row.value.body,
1739
+ startByte: 0,
1740
+ endByte: row.value.body.byteLength
1741
+ });
1742
+ else nodes.push({
1743
+ id: `unavailable-${row.index}`,
1744
+ kind: "literal",
1745
+ text: "The resource was read, but its original text could not be captured.\n"
1746
+ });
1747
+ }
1748
+ return {
1749
+ formatVersion: 1,
1750
+ rendererVersion: 1,
1751
+ nodes
1752
+ };
1753
+ }
1754
+ function mcpMutationDocument(data) {
1755
+ let text;
1756
+ if (!data.ok) text = `${data.code}: ${data.message}`;
1757
+ else if ("operationId" in data.data) text = `MCP selection ${data.data.operationId}: ${data.data.operationState}; selected servers: ${"value" in data.data ? data.data.value.serverIds.join(", ") || "none" : "unknown"}.`;
1758
+ else text = `MCP ${"serverId" in data.data ? data.data.serverId : ""}: ${data.data.summary}${"revision" in data.data ? ` Revision ${data.data.revision}.` : ""}${"selected" in data.data ? ` Selected: ${data.data.selected}.` : ""}`;
1759
+ return {
1760
+ formatVersion: 1,
1761
+ rendererVersion: 1,
1762
+ nodes: [{
1763
+ id: "receipt",
1764
+ kind: "literal",
1765
+ text
1766
+ }]
1767
+ };
1768
+ }
1769
+ function mcpMutationBusiness(value) {
1770
+ const known = !("operationState" in value) || value.operationState !== "admitted";
1771
+ const cleanup = "operationState" in value && value.operationState === "cleanup-pending";
1772
+ return {
1773
+ data: {
1774
+ ok: true,
1775
+ committed: known,
1776
+ status: known ? "ok" : "unknown",
1777
+ data: value
1778
+ },
1779
+ execution: { state: known ? "committed" : "unknown" },
1780
+ isError: !known || cleanup,
1781
+ presentation: {
1782
+ type: "mcp-mutation",
1783
+ schemaVersion: 1,
1784
+ summary: "MCP configuration receipt",
1785
+ state: known && !cleanup ? "ready" : "partial",
1786
+ fields: { committed: known },
1787
+ actions: [],
1788
+ bodyRefs: []
1789
+ }
1790
+ };
1791
+ }
1792
+ function mcpServerDocument(data) {
1793
+ const nodes = [];
1794
+ if (!data.ok) nodes.push({
1795
+ id: "failure",
1796
+ kind: "literal",
1797
+ text: `${data.error.code}: ${data.error.message}\n`
1798
+ });
1799
+ else for (const row of data.results) if (!row.ok) nodes.push({
1800
+ id: `error-${row.index}`,
1801
+ kind: "literal",
1802
+ text: `${row.error.code}: ${row.error.message}\n`
1803
+ });
1804
+ else if (Array.isArray(row.value)) for (const header of row.value) nodes.push({
1805
+ id: `server-${row.index}-${header.id}`,
1806
+ kind: "literal",
1807
+ text: `MCP ${header.name} (${header.id}, ${header.slug}): ${header.transport}, ${header.enabled ? "enabled" : "disabled"}, ${header.selected ? "selected" : "not selected"}, ${header.connectionState}.\n`
1808
+ });
1809
+ else {
1810
+ nodes.push({
1811
+ id: `range-${row.index}`,
1812
+ kind: "literal",
1813
+ text: `MCP ${row.value.serverId} safe details: Unicode offset ${row.value.range.offset}, length ${row.value.range.length}.\n`
1814
+ });
1815
+ nodes.push({
1816
+ id: `detail-${row.index}`,
1817
+ kind: "text-range",
1818
+ body: row.value.body,
1819
+ startByte: row.value.startByte,
1820
+ endByte: row.value.endByte
1821
+ });
1822
+ }
1823
+ if (data.next) nodes.push({
1824
+ id: "continuation",
1825
+ kind: "literal",
1826
+ text: `Continue with ${JSON.stringify(data.next)}\n`
1827
+ });
1828
+ return {
1829
+ formatVersion: 1,
1830
+ rendererVersion: 1,
1831
+ nodes
1832
+ };
1833
+ }
1834
+ function mcpServerBusiness(data) {
1835
+ const failed = !data.ok || data.results.some((row) => !row.ok), successful = data.ok && data.results.some((row) => row.ok);
1836
+ const bodies = data.ok ? data.results.flatMap((row) => row.ok && !Array.isArray(row.value) ? [row.value.body] : []) : [];
1837
+ return {
1838
+ data,
1839
+ execution: { state: failed ? successful ? "partial" : "not-started" : "committed" },
1840
+ isError: failed,
1841
+ presentation: {
1842
+ type: "mcp-server-page",
1843
+ schemaVersion: 1,
1844
+ summary: "MCP server details",
1845
+ state: failed || data.ok && !data.complete ? "partial" : "ready",
1846
+ fields: {},
1847
+ actions: [],
1848
+ bodyRefs: bodies
1849
+ }
1850
+ };
1851
+ }
1852
+ //#endregion
1853
+ //#region src/server-pages.ts
1854
+ const Tokens = z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional().describe("Desired delivery tokens; the host may allocate fewer.");
1855
+ const Query = z.union([z.strictObject({ all: z.literal(true).describe("List configured server headers without configuration bodies.") }), z.strictObject({ serverIds: z.array(z.uuid().describe("Exact selected MCP server id.")).min(1).max(64).describe("Selected server ids whose summaries are needed; unknown or unselected members refuse this query.") })]);
1856
+ const Start = z.union([z.strictObject({
1857
+ queries: z.array(Query).min(1).max(64).describe("Ordered directory queries; limit and tokens are shared by the whole page."),
1858
+ view: z.literal("summary").default("summary").describe("Header summaries only; default summary, no configuration bodies."),
1859
+ limit: z.number().int().min(1).max(100).default(50).describe("Maximum total server headers on this page; default 50, hard maximum 100."),
1860
+ outputTokens: Tokens
1861
+ }), z.strictObject({
1862
+ queries: z.tuple([z.strictObject({ serverIds: z.tuple([z.uuid()]).check(z.minLength(1), z.maxLength(1)).describe("Exactly one selected server id for safe configuration details.") })]).check(z.minLength(1), z.maxLength(1)).describe("Exactly one query containing exactly one selected server id."),
1863
+ view: z.literal("details").describe("Safe configuration fragments for exactly one selected server."),
1864
+ outputTokens: Tokens
1865
+ })]);
1866
+ const Continue = z.strictObject({
1867
+ cursor: z.string().min(1).max(512).regex(/^[\x21-\x7e]+$/).describe("Opaque continuation; copy next.arguments without changing queries or view."),
1868
+ outputTokens: Tokens
1869
+ });
1870
+ const Input = z.union([Start, Continue]);
1785
1871
  function serverPages(deps) {
1786
1872
  const cursors = new QueryCursorCache((state) => ({
1787
1873
  initial: state.position.initial,
1788
- content: state.result && "content" in state.result ? state.result.content : void 0
1874
+ metadata: state.selection ? JSON.stringify(state.selection) : void 0
1789
1875
  }), deps.resources);
1790
1876
  const sourceVersion = () => {
1791
1877
  const hash = createHash("sha256").update(String(deps.store.directoryVersion()));
1792
1878
  for (const secret of [...deps.secrets()].sort()) hash.update(JSON.stringify(secret));
1793
1879
  return hash.digest("hex");
1794
1880
  };
1795
- const failure = (code, message, next = null) => ({
1796
- content: JSON.stringify({
1797
- ok: false,
1798
- error: {
1799
- code,
1800
- message,
1801
- retryable: next !== null
1802
- },
1803
- next
1804
- }),
1805
- isError: true
1881
+ const documents = createTextDocuments(mcpServerDocument);
1882
+ const failure = (code, message, next = null) => mcpServerBusiness({
1883
+ ok: false,
1884
+ error: {
1885
+ code,
1886
+ message,
1887
+ retryable: next !== null
1888
+ },
1889
+ next
1806
1890
  });
1807
1891
  return cursors.wrap({
1808
1892
  name: "mcp_server_list",
1809
1893
  preload: false,
1810
1894
  description: "Read bounded MCP server summaries by default. view=details accepts exactly one selected server id and pages its safe configuration. Follow next.arguments; complete tool definitions use tool_search.",
1811
1895
  inputSchema: Input,
1812
- outputSchema: toolOutputSchema(Output, Input, "mcp_server_list"),
1896
+ outputSchema: McpServerDataSchema,
1897
+ formatModel: documents.formatModel,
1813
1898
  deliveryKind: "exact-page",
1814
1899
  async execute(input, call) {
1815
1900
  call.signal.throwIfAborted();
@@ -1830,22 +1915,15 @@ function serverPages(deps) {
1830
1915
  tool: "mcp_server_list",
1831
1916
  arguments: p.initial
1832
1917
  });
1833
- if (saved?.result) {
1834
- const cost = call.output.measure(saved.result);
1835
- if (cost > call.output.outputTokens) return failure("page_too_small", "The saved exact server page needs a larger independent allocation.", cost <= call.output.maximumTokens ? {
1836
- tool: "mcp_server_list",
1837
- arguments: {
1838
- ...input,
1839
- outputTokens: cost
1840
- }
1841
- } : null);
1842
- call.output.acceptExact(saved.result);
1843
- saved.used = now;
1844
- return saved.result;
1845
- }
1846
- const limit = p.initial.view === "summary" ? p.initial.limit : 1, cursor = randomUUID(), query = p.initial.queries[p.index], last = p.index === p.initial.queries.length - 1;
1918
+ const limit = p.initial.view === "summary" ? p.initial.limit : 1, cursor = saved?.selection?.cursor ?? randomUUID(), query = p.initial.queries[p.index], last = p.index === p.initial.queries.length - 1;
1919
+ const selectedAllowance = saved?.selection?.outputTokens ?? call.output.outputTokens;
1920
+ let selection = {
1921
+ outputTokens: selectedAllowance,
1922
+ cursor
1923
+ };
1924
+ const measure = async (result) => call.output.measure(result, await documents.prepare(result.data, call), call.signal);
1847
1925
  let following, result;
1848
- const build = (row, complete) => ({ content: JSON.stringify({
1926
+ const build = (row, complete) => mcpServerBusiness({
1849
1927
  ok: true,
1850
1928
  complete: complete && last,
1851
1929
  results: [row],
@@ -1855,13 +1933,33 @@ function serverPages(deps) {
1855
1933
  },
1856
1934
  effective: {
1857
1935
  limit,
1858
- outputTokens: call.output.outputTokens
1936
+ outputTokens: selectedAllowance
1859
1937
  }
1860
- }) });
1938
+ });
1861
1939
  try {
1862
1940
  if (p.initial.view === "details") {
1863
- const id = p.initial.queries[0].serverIds[0], window = unicodeWindow(JSON.stringify(deps.details(id, call)), p.offset, Math.min(32768, Math.max(1, call.output.outputTokens * 4))), remaining = window.points;
1864
- let length = Math.min(remaining.length, call.output.outputTokens * 4);
1941
+ const id = p.initial.queries[0].serverIds[0];
1942
+ const current = deps.details(id, call);
1943
+ let snapshot = current;
1944
+ if (current && typeof current === "object" && !Array.isArray(current)) {
1945
+ const value = current;
1946
+ p.detailState ??= {
1947
+ ...typeof value.connectionState === "string" ? { connectionState: value.connectionState } : {},
1948
+ ...typeof value.oauthAuthorized === "boolean" ? { oauthAuthorized: value.oauthAuthorized } : {}
1949
+ };
1950
+ snapshot = {
1951
+ ...value,
1952
+ ...p.detailState
1953
+ };
1954
+ }
1955
+ const text = JSON.stringify(snapshot), sourceHash = createHash("sha256").update(text).digest("hex");
1956
+ if (p.detailSha256 && p.detailSha256 !== sourceHash) return failure("source_changed", "The recorded safe configuration is no longer available.");
1957
+ p.detailSha256 = sourceHash;
1958
+ const window = unicodeWindow(text, p.offset, Math.min(32768, Math.max(1, selectedAllowance * 4))), remaining = window.points;
1959
+ const body = await captureTextBody(remaining.join(""), call);
1960
+ call.signal.throwIfAborted();
1961
+ if (p.version !== sourceVersion()) return failure("source_changed", "Server configuration changed while capturing this page.");
1962
+ let length = saved?.selection?.length ?? Math.min(remaining.length, selectedAllowance * 4);
1865
1963
  const make = (n) => build({
1866
1964
  index: 0,
1867
1965
  ok: true,
@@ -1869,7 +1967,9 @@ function serverPages(deps) {
1869
1967
  value: {
1870
1968
  serverId: id,
1871
1969
  field: "details",
1872
- text: remaining.slice(0, n).join(""),
1970
+ body,
1971
+ startByte: 0,
1972
+ endByte: Buffer.byteLength(remaining.slice(0, n).join("")),
1873
1973
  range: {
1874
1974
  offset: p.offset,
1875
1975
  length: n,
@@ -1878,16 +1978,20 @@ function serverPages(deps) {
1878
1978
  }
1879
1979
  }, window.complete && n === remaining.length);
1880
1980
  result = make(length);
1881
- if (call.output.measure(result) > call.output.outputTokens) {
1981
+ if (!saved?.selection && await measure(result) > call.output.outputTokens) {
1882
1982
  let low = 0, high = length;
1883
1983
  while (low < high) {
1884
1984
  const mid = Math.ceil((low + high) / 2);
1885
- if (call.output.measure(make(mid)) <= call.output.outputTokens) low = mid;
1985
+ if (await measure(make(mid)) <= call.output.outputTokens) low = mid;
1886
1986
  else high = mid - 1;
1887
1987
  }
1888
1988
  length = low;
1889
1989
  result = make(length);
1890
1990
  }
1991
+ selection = {
1992
+ ...selection,
1993
+ length
1994
+ };
1891
1995
  if (length === 0 && remaining.length > 0) return failure("page_too_small", "Detail metadata does not fit this allowance.");
1892
1996
  if (!window.complete || length < remaining.length) following = {
1893
1997
  ...p,
@@ -1902,15 +2006,18 @@ function serverPages(deps) {
1902
2006
  slug: redact(item.slug, secrets),
1903
2007
  connectionState: deps.state(item.id)
1904
2008
  }));
1905
- let count = items.length;
2009
+ const recorded = saved?.selection?.headers;
2010
+ if (recorded && recorded.some((row, index) => items[index]?.id !== row.id)) return failure("source_changed", "Server membership changed; restart the query.");
2011
+ const displayed = recorded ?? items;
2012
+ let count = saved?.selection?.count ?? items.length;
1906
2013
  const make = (n) => build({
1907
2014
  index: p.index,
1908
2015
  ok: true,
1909
2016
  complete: page.complete && n === items.length,
1910
- value: items.slice(0, n)
2017
+ value: displayed.slice(0, n)
1911
2018
  }, page.complete && n === items.length);
1912
2019
  result = make(count);
1913
- if (count > 0 && call.output.measure(result) > call.output.outputTokens) {
2020
+ if (!saved?.selection && count > 0 && await measure(result) > call.output.outputTokens) {
1914
2021
  let low = 1;
1915
2022
  let high = count - 1;
1916
2023
  count = 0;
@@ -1919,7 +2026,7 @@ function serverPages(deps) {
1919
2026
  call.signal.throwIfAborted();
1920
2027
  const candidateCount = Math.floor((low + high) / 2);
1921
2028
  const candidate = make(candidateCount);
1922
- if (call.output.measure(candidate) <= call.output.outputTokens) {
2029
+ if (await measure(candidate) <= call.output.outputTokens) {
1923
2030
  count = candidateCount;
1924
2031
  result = candidate;
1925
2032
  low = candidateCount + 1;
@@ -1929,13 +2036,18 @@ function serverPages(deps) {
1929
2036
  await setImmediate();
1930
2037
  call.signal.throwIfAborted();
1931
2038
  const candidate = make(candidateCount);
1932
- if (call.output.measure(candidate) <= call.output.outputTokens) {
2039
+ if (await measure(candidate) <= call.output.outputTokens) {
1933
2040
  count = candidateCount;
1934
2041
  result = candidate;
1935
2042
  break;
1936
2043
  }
1937
2044
  }
1938
2045
  }
2046
+ selection = {
2047
+ ...selection,
2048
+ count,
2049
+ headers: structuredClone(displayed.slice(0, count))
2050
+ };
1939
2051
  if (count === 0 && items.length > 0) return failure("page_too_small", "One server summary does not fit this allowance.");
1940
2052
  if (!(page.complete && count === items.length)) following = {
1941
2053
  ...p,
@@ -1965,9 +2077,9 @@ function serverPages(deps) {
1965
2077
  offset: 0
1966
2078
  };
1967
2079
  }
1968
- if (call.output.measure(result) > call.output.outputTokens) return failure("page_too_small", "Server page metadata does not fit this allowance.");
1969
- await cursors.prepare(p.initial, result.content);
1970
- call.output.acceptExact(result);
2080
+ if (await measure(result) > call.output.outputTokens) return failure("page_too_small", "Server page metadata does not fit this allowance.");
2081
+ await cursors.prepare(p.initial, JSON.stringify(selection));
2082
+ await call.output.acceptExact(result, await documents.prepare(result.data, call), call.signal);
1971
2083
  if (following) {
1972
2084
  for (const [key, state] of cursors) if (now - state.created > 36e5 || state.session === call.sessionId && state.generation !== call.historyGeneration) cursors.delete(key);
1973
2085
  while (cursors.size >= 4096) {
@@ -1984,22 +2096,21 @@ function serverPages(deps) {
1984
2096
  });
1985
2097
  }
1986
2098
  if (saved) {
1987
- saved.result = result;
2099
+ saved.selection = selection;
1988
2100
  trimCursorCache(cursors, (state) => ({
1989
2101
  initial: state.position.initial,
1990
- content: state.result && "content" in state.result ? state.result.content : void 0
2102
+ metadata: state.selection ? JSON.stringify(state.selection) : void 0
1991
2103
  }));
1992
2104
  saved.used = now;
1993
2105
  }
1994
2106
  trimCursorCache(cursors, (state) => ({
1995
2107
  initial: state.position.initial,
1996
- content: state.result && "content" in state.result ? state.result.content : void 0
2108
+ metadata: state.selection ? JSON.stringify(state.selection) : void 0
1997
2109
  }));
1998
2110
  return result;
1999
2111
  }
2000
2112
  });
2001
2113
  }
2002
- /** Builds a bounded Unicode window without allocating an array for the complete source. */
2003
2114
  function unicodeWindow(text, offset, maximum) {
2004
2115
  let unit = 0, skipped = 0;
2005
2116
  while (unit < text.length && skipped < offset) {
@@ -2019,7 +2130,6 @@ function unicodeWindow(text, offset, maximum) {
2019
2130
  }
2020
2131
  //#endregion
2021
2132
  //#region src/tool-names.ts
2022
- /** Canonical names shared by tool registration and browser presentation. */
2023
2133
  const TOOL_NAMES = [
2024
2134
  "mcp_server_list",
2025
2135
  "mcp_server_create",
@@ -2028,28 +2138,23 @@ const TOOL_NAMES = [
2028
2138
  ];
2029
2139
  //#endregion
2030
2140
  //#region src/management-tools.ts
2031
- /** Strict plugin configuration for individually disabling management tools. */
2032
2141
  const McpConfig = z.object({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).strict().default({ disabled: [] });
2033
- /** One server's creation, `transport` paired with its own `config`. */
2034
2142
  const CreatePaired = z.discriminatedUnion("transport", [z.object({
2035
2143
  slug: z.string().describe("Unique mapped-name prefix matching ^[a-z0-9][a-z0-9-]{0,23}$; cannot be changed after creation."),
2036
- name: z.string().trim().min(1).max(80).describe("Server display name, 1–80 UTF-16 code units after trimming."),
2144
+ name: z.string().trim().min(1).max(80).describe("Server display name, 1\u201380 UTF-16 code units after trimming."),
2037
2145
  transport: z.literal("stdio"),
2038
2146
  config: StdioConfigSchema,
2039
2147
  select: z.boolean().default(true).describe("Select the new server for this Agent after approval; default true.")
2040
2148
  }).strict(), z.object({
2041
2149
  slug: z.string().describe("Unique mapped-name prefix matching ^[a-z0-9][a-z0-9-]{0,23}$; cannot be changed after creation."),
2042
- name: z.string().trim().min(1).max(80).describe("Server display name, 1–80 UTF-16 code units after trimming."),
2150
+ name: z.string().trim().min(1).max(80).describe("Server display name, 1\u201380 UTF-16 code units after trimming."),
2043
2151
  transport: z.literal("http"),
2044
2152
  config: HttpConfigSchema,
2045
2153
  select: z.boolean().default(true).describe("Select the new server for this Agent after approval; default true.")
2046
2154
  }).strict()]);
2047
- /** The parameters as the model sees them: one object, because an
2048
- * OpenAI-compatible endpoint refuses a tool whose top level is not
2049
- * `type: "object"`. The pairing `CreatePaired` states is checked here. */
2050
2155
  const Create = z.object({
2051
2156
  slug: z.string().describe("Unique mapped-name prefix matching ^[a-z0-9][a-z0-9-]{0,23}$; cannot be changed after creation."),
2052
- name: z.string().trim().min(1).max(80).describe("Server display name, 1–80 UTF-16 code units after trimming."),
2157
+ name: z.string().trim().min(1).max(80).describe("Server display name, 1\u201380 UTF-16 code units after trimming."),
2053
2158
  transport: z.enum(["stdio", "http"]).describe("Transport paired with its matching config: local stdio command or remote HTTP endpoint."),
2054
2159
  config: z.union([StdioConfigSchema, HttpConfigSchema]).describe("Complete configuration matching transport; credentials are referenced by names, never included as plain values."),
2055
2160
  select: z.boolean().default(true).describe("Select the new server for this Agent after approval; default true.")
@@ -2062,7 +2167,7 @@ const Create = z.object({
2062
2167
  });
2063
2168
  const Update = z.object({
2064
2169
  serverId: z.string().uuid().describe("Exact configured MCP server UUID from mcp_server_list."),
2065
- name: z.string().trim().min(1).max(80).optional().describe("Replacement display name, 1–80 UTF-16 code units after trimming; omit to retain."),
2170
+ name: z.string().trim().min(1).max(80).optional().describe("Replacement display name, 1\u201380 UTF-16 code units after trimming; omit to retain."),
2066
2171
  config: z.union([StdioConfigSchema, HttpConfigSchema]).optional().describe("Complete replacement configuration matching the existing transport; omit to retain."),
2067
2172
  expectedRevision: z.string().optional().describe("Observed configuration revision; a mismatch refuses the update before writing.")
2068
2173
  }).strict().refine((value) => value.name !== void 0 || value.config !== void 0, "a change is required");
@@ -2072,40 +2177,12 @@ const Select = z.object({
2072
2177
  }).strict();
2073
2178
  const SelectInput = batchInput({
2074
2179
  operationId: z.uuid().describe("New UUID for this selection operation; reuse only when retrying the identical operation."),
2075
- changes: z.array(Select).min(1).max(64).describe("Selection changes, 1–64 members under one approval and transaction.")
2180
+ changes: z.array(Select).min(1).max(64).describe("Selection changes, 1\u201364 members under one approval and transaction.")
2076
2181
  }, "changes");
2077
- const MutationOutput = z.strictObject({
2078
- ok: z.literal(true),
2079
- committed: z.literal(true),
2080
- status: z.literal("ok"),
2081
- data: z.union([
2082
- z.strictObject({
2083
- serverId: z.string(),
2084
- selected: z.boolean(),
2085
- summary: z.string().max(256)
2086
- }),
2087
- z.strictObject({
2088
- serverId: z.string(),
2089
- revision: z.string(),
2090
- summary: z.string().max(256)
2091
- }),
2092
- z.strictObject({ summary: z.string().max(256) }),
2093
- z.strictObject({
2094
- operationId: z.uuid(),
2095
- operationState: z.enum(["admitted", "committed"]),
2096
- value: z.strictObject({
2097
- serverIds: z.array(z.string()),
2098
- revision: z.number(),
2099
- contentHash: z.string()
2100
- })
2101
- })
2102
- ])
2103
- });
2104
2182
  const revisionOf = (record) => createHash("sha256").update(JSON.stringify(record)).digest("hex");
2105
2183
  const fail = (code, message) => {
2106
2184
  throw Object.assign(new Error(message), { code });
2107
2185
  };
2108
- /** Registers the five model-facing management tools. */
2109
2186
  function registerMcpManagementTools(deps) {
2110
2187
  const { store, connections, credentials, oauth } = deps;
2111
2188
  const requireServer = (serverId) => {
@@ -2157,12 +2234,7 @@ function registerMcpManagementTools(deps) {
2157
2234
  if (Array.isArray(value)) return value.some((item) => containsKnownSecret(item, secrets));
2158
2235
  return value !== null && typeof value === "object" && Object.values(value).some((item) => containsKnownSecret(item, secrets));
2159
2236
  };
2160
- const readResult = (data) => ({ content: JSON.stringify({
2161
- ok: true,
2162
- committed: true,
2163
- status: "ok",
2164
- data
2165
- }) });
2237
+ const readResult = (value) => mcpMutationBusiness(McpMutationSuccessSchema.shape.data.parse(value));
2166
2238
  const serverDetail = (serverId, agentId) => {
2167
2239
  try {
2168
2240
  const record = requireSelected(serverId, agentId);
@@ -2198,7 +2270,8 @@ function registerMcpManagementTools(deps) {
2198
2270
  preload: false,
2199
2271
  description: "Create an MCP server and optionally select it for this agent after approval.",
2200
2272
  inputSchema: Create,
2201
- outputSchema: toolOutputSchema(MutationOutput, Create, "mcp_server_create"),
2273
+ outputSchema: McpMutationDataSchema,
2274
+ formatModel: async (data) => mcpMutationDocument(data),
2202
2275
  deliveryKind: "receipt",
2203
2276
  async execute(fields, ctx) {
2204
2277
  let input = CreatePaired.parse(fields);
@@ -2229,10 +2302,7 @@ function registerMcpManagementTools(deps) {
2229
2302
  }
2230
2303
  });
2231
2304
  if (decision.kind === "ask") return decision.result;
2232
- if (!decision.result.kind.startsWith("allowed-")) return {
2233
- content: "MCP creation was not approved.",
2234
- isError: true
2235
- };
2305
+ if (!decision.result.kind.startsWith("allowed-")) return mcpFailure("MCP creation was not approved");
2236
2306
  const record = await saveServer(deps.management, {
2237
2307
  ...input,
2238
2308
  acknowledge: true
@@ -2252,7 +2322,8 @@ function registerMcpManagementTools(deps) {
2252
2322
  preload: false,
2253
2323
  description: "Update a selected shared MCP server after approval.",
2254
2324
  inputSchema: Update,
2255
- outputSchema: toolOutputSchema(MutationOutput, Update, "mcp_server_update"),
2325
+ outputSchema: McpMutationDataSchema,
2326
+ formatModel: async (data) => mcpMutationDocument(data),
2256
2327
  deliveryKind: "receipt",
2257
2328
  async execute(input, ctx) {
2258
2329
  const agentId = deps.definitions.read(ctx).agentId;
@@ -2295,10 +2366,7 @@ function registerMcpManagementTools(deps) {
2295
2366
  }
2296
2367
  });
2297
2368
  if (decision.kind === "ask") return decision.result;
2298
- if (!decision.result.kind.startsWith("allowed-")) return {
2299
- content: "MCP update was not approved.",
2300
- isError: true
2301
- };
2369
+ if (!decision.result.kind.startsWith("allowed-")) return mcpFailure("MCP update was not approved");
2302
2370
  const record = await saveServer(deps.management, {
2303
2371
  id: previous.id,
2304
2372
  slug: previous.slug,
@@ -2319,7 +2387,8 @@ function registerMcpManagementTools(deps) {
2319
2387
  preload: false,
2320
2388
  description: "Apply one complete Agent MCP selection intent atomically after one approval binds its original revision/hash and every change.",
2321
2389
  inputSchema: SelectInput,
2322
- outputSchema: toolOutputSchema(MutationOutput, SelectInput, "mcp_server_set_selected"),
2390
+ outputSchema: McpMutationDataSchema,
2391
+ formatModel: async (data) => mcpMutationDocument(data),
2323
2392
  deliveryKind: "receipt",
2324
2393
  async execute(input, ctx) {
2325
2394
  const agentId = deps.definitions.read(ctx).agentId;
@@ -2366,10 +2435,7 @@ function registerMcpManagementTools(deps) {
2366
2435
  }
2367
2436
  });
2368
2437
  if (decision.kind === "ask") return decision.result;
2369
- if (!decision.result.kind.startsWith("allowed-")) return {
2370
- content: "MCP selection was not approved.",
2371
- isError: true
2372
- };
2438
+ if (!decision.result.kind.startsWith("allowed-")) return mcpFailure("MCP selection was not approved");
2373
2439
  }
2374
2440
  deps.management.agentConfig.check(agentId, state.revision, state.contentHash);
2375
2441
  const changed = JSON.stringify(before) !== JSON.stringify(serverIds);
@@ -2401,8 +2467,6 @@ function registerMcpManagementTools(deps) {
2401
2467
  }
2402
2468
  //#endregion
2403
2469
  //#region src/command-paste.ts
2404
- /** Executable-field paste rules follow the resident physical host. */
2405
- /** Preserves raw absolute executable-field pastes; other input uses direct host argv grammar. */
2406
2470
  function parseCommandPaste(text, commands) {
2407
2471
  if (!text || /[\0\r\n]/.test(text)) throw new Error("invalid-command-text");
2408
2472
  const windows = commands.platform === "win32";
@@ -2414,9 +2478,7 @@ function parseCommandPaste(text, commands) {
2414
2478
  }
2415
2479
  //#endregion
2416
2480
  //#region src/command-text.ts
2417
- /** Shared command-paste input bounds for the owner RPC and browser editor. */
2418
2481
  const COMMAND_TEXT_LIMIT = 65536;
2419
- /** Checks the UTF-8 byte limit before command text crosses the authenticated connection. */
2420
2482
  function commandTextFits(text) {
2421
2483
  return new TextEncoder().encode(text).length <= COMMAND_TEXT_LIMIT;
2422
2484
  }
@@ -2433,7 +2495,6 @@ const StatusSchema = z.object({
2433
2495
  ]),
2434
2496
  reason: z.string().optional()
2435
2497
  }).strict();
2436
- /** Credential-free catalogue row used by owner frames and complete mutation receipts. */
2437
2498
  const ServerSummarySchema = z.object({
2438
2499
  id: z.string(),
2439
2500
  slug: z.string(),
@@ -2443,7 +2504,6 @@ const ServerSummarySchema = z.object({
2443
2504
  status: StatusSchema,
2444
2505
  agentIds: z.array(z.string())
2445
2506
  }).strict();
2446
- /** One named input of a tool or a prompt, as a settings page lists it. */
2447
2507
  const ParameterSchema = z.object({
2448
2508
  name: z.string(),
2449
2509
  type: z.string().optional(),
@@ -2528,16 +2588,8 @@ z.strictObject({
2528
2588
  revision: z.number(),
2529
2589
  contentHash: z.string()
2530
2590
  });
2531
- /** The longest server-written description a page is sent. */
2532
2591
  const DESCRIPTION_LIMIT = 2048;
2533
- /** The most inputs listed for one tool or prompt. */
2534
2592
  const PARAMETER_LIMIT = 64;
2535
- /**
2536
- * A tool's inputs read off its JSON Schema: the top-level properties, in the
2537
- * order the server wrote them, each with its type, whether `required` names it
2538
- * and its own description. Nothing deeper — a settings page answers what the
2539
- * tool asks for, and the model is the one handed the whole schema.
2540
- */
2541
2593
  function schemaParameters(schema, shown) {
2542
2594
  const properties = schema?.properties;
2543
2595
  if (!properties || typeof properties !== "object") return [];
@@ -2554,11 +2606,6 @@ function schemaParameters(schema, shown) {
2554
2606
  };
2555
2607
  });
2556
2608
  }
2557
- /**
2558
- * The plugin's wire methods and its two broadcast frames. Every result is
2559
- * validated by the host against these schemas, and none carries a
2560
- * credential value.
2561
- */
2562
2609
  function registerMethods(deps) {
2563
2610
  const { ctx, store, connections, tools, prompts, oauth } = deps;
2564
2611
  const serversChanged = ctx.client.registerFrame({
@@ -2994,7 +3041,10 @@ function registerMethods(deps) {
2994
3041
  management
2995
3042
  };
2996
3043
  }
2997
- /** The server needs a person to authorize it (again). */
3044
+ //#endregion
3045
+ //#region src/oauth.ts
3046
+ const loadAuth = () => import("@modelcontextprotocol/sdk/client/auth.js");
3047
+ const loadAuthErrors = () => import("@modelcontextprotocol/sdk/server/auth/errors.js");
2998
3048
  var NeedsAuthorizationError = class extends Error {
2999
3049
  constructor(message = "authorization required") {
3000
3050
  super(message);
@@ -3040,15 +3090,6 @@ function portOf(uri) {
3040
3090
  return;
3041
3091
  }
3042
3092
  }
3043
- /**
3044
- * OAuth for remote servers: an `OAuthClientProvider` over the credential
3045
- * manager (`oauth.tokens`, `oauth.client`), the one-shot loopback callback,
3046
- * and a refresh made ahead of expiry, shared by concurrent requests.
3047
- *
3048
- * Every authorization and every refresh belongs to a generation per server;
3049
- * signing out, reauthorizing, changing the endpoint and deleting bump it, and
3050
- * a late result from an older generation is dropped before it writes.
3051
- */
3052
3093
  function createOAuth(deps) {
3053
3094
  const now = deps.now ?? Date.now;
3054
3095
  const timeoutMs = deps.timeoutMs ?? 3e5;
@@ -3067,12 +3108,6 @@ function createOAuth(deps) {
3067
3108
  }
3068
3109
  };
3069
3110
  const readTokens = (serverId) => readJson(serverId, OAUTH_TOKENS);
3070
- /**
3071
- * Token documents a refresh replaced, newest last and at most
3072
- * `REPLACED_KEPT` per server. A request already sent may still carry one,
3073
- * and a server may echo it after the refresh, so redaction keeps checking
3074
- * them until the tokens are cleared.
3075
- */
3076
3111
  const replaced = /* @__PURE__ */ new Map();
3077
3112
  const remember = (serverId) => {
3078
3113
  let raw;
@@ -3122,7 +3157,6 @@ function createOAuth(deps) {
3122
3157
  if ((scope === "all" || scope === "verifier") && flow) flow.verifier = void 0;
3123
3158
  };
3124
3159
  const strip = ({ expires_at: _expiresAt, ...tokens }) => tokens;
3125
- /** One refresh per server at a time; concurrent callers share it. */
3126
3160
  const refresh = (serverId, serverUrl, current) => {
3127
3161
  const running = refreshes.get(serverId);
3128
3162
  if (running) return running;
@@ -3132,12 +3166,12 @@ function createOAuth(deps) {
3132
3166
  if (!client || !current.refresh_token) throw new NeedsAuthorizationError();
3133
3167
  let info = discovery.get(serverId);
3134
3168
  if (!info?.authorizationServerUrl) {
3135
- info = await discoverOAuthServerInfo(serverUrl, { fetchFn: deps.fetch });
3169
+ info = await (await loadAuth()).discoverOAuthServerInfo(serverUrl, { fetchFn: deps.fetch });
3136
3170
  discovery.set(serverId, info);
3137
3171
  }
3138
- const selected = await selectResourceURL(serverUrl, {}, info.resourceMetadata);
3172
+ const selected = await (await loadAuth()).selectResourceURL(serverUrl, {}, info.resourceMetadata);
3139
3173
  const resource = selected && info.resourceMetadata ? info.resourceMetadata.resource : selected;
3140
- const tokens = await refreshAuthorization(info.authorizationServerUrl, {
3174
+ const tokens = await (await loadAuth()).refreshAuthorization(info.authorizationServerUrl, {
3141
3175
  ...info.authorizationServerMetadata ? { metadata: info.authorizationServerMetadata } : {},
3142
3176
  clientInformation: client,
3143
3177
  refreshToken: current.refresh_token,
@@ -3158,7 +3192,6 @@ function createOAuth(deps) {
3158
3192
  if (flows.get(serverId) === flow) flows.delete(serverId);
3159
3193
  if (flow.gen === gen(serverId)) flow.done(outcome);
3160
3194
  };
3161
- /** Drops every authorization and refresh in progress for a server. */
3162
3195
  const invalidate = (serverId) => {
3163
3196
  generations.set(serverId, gen(serverId) + 1);
3164
3197
  discovery.delete(serverId);
@@ -3169,10 +3202,8 @@ function createOAuth(deps) {
3169
3202
  });
3170
3203
  };
3171
3204
  return {
3172
- /** The current generation; a caller compares it after an await. */
3173
3205
  generation: gen,
3174
3206
  invalidate,
3175
- /** Whether tokens are stored, and when the access token expires. */
3176
3207
  status(serverId) {
3177
3208
  let tokens;
3178
3209
  try {
@@ -3189,13 +3220,10 @@ function createOAuth(deps) {
3189
3220
  hasTokens(serverId) {
3190
3221
  return readTokens(serverId) !== void 0;
3191
3222
  },
3192
- /** Clears this server's tokens and client registration. */
3193
3223
  signOut(serverId) {
3194
3224
  invalidate(serverId);
3195
3225
  clear(serverId);
3196
3226
  },
3197
- /** The raw credential values a connection's requests may carry, for
3198
- * redaction: the stored ones and the token documents a refresh replaced. */
3199
3227
  secrets(serverId) {
3200
3228
  const read = (name) => {
3201
3229
  try {
@@ -3210,12 +3238,6 @@ function createOAuth(deps) {
3210
3238
  ...replaced.get(serverId) ?? []
3211
3239
  ];
3212
3240
  },
3213
- /**
3214
- * The provider a connection uses. It never opens an authorization: when the
3215
- * endpoint asks for one, the SDK's request fails and the server reads as
3216
- * needing authorization. Its `tokens()` refreshes a token expiring within
3217
- * a minute before handing it out.
3218
- */
3219
3241
  connectionProvider(serverId, serverUrl) {
3220
3242
  const generation = gen(serverId);
3221
3243
  const recorded = () => readClient(serverId)?.redirect_uris?.[0] ?? "http://127.0.0.1/callback";
@@ -3238,6 +3260,7 @@ function createOAuth(deps) {
3238
3260
  return strip(await refresh(serverId, serverUrl, stored));
3239
3261
  } catch (error) {
3240
3262
  if (error instanceof NeedsAuthorizationError) throw error;
3263
+ const { OAuthError, ServerError } = await loadAuthErrors();
3241
3264
  if (error instanceof OAuthError && !(error instanceof ServerError)) throw new NeedsAuthorizationError(`token refresh was refused: ${error.errorCode}`);
3242
3265
  deps.log.emit({
3243
3266
  level: "warn",
@@ -3264,12 +3287,6 @@ function createOAuth(deps) {
3264
3287
  discoveryState: () => discovery.get(serverId)
3265
3288
  };
3266
3289
  },
3267
- /**
3268
- * Starts an authorization: listens once on a loopback port, registers a
3269
- * client when needed (again when the recorded redirect port cannot be
3270
- * bound), and returns the authorization URL a page opens. `done` is called
3271
- * once, unless a newer generation replaced this one.
3272
- */
3273
3290
  async authorize(serverId, serverUrl, done) {
3274
3291
  invalidate(serverId);
3275
3292
  const generation = gen(serverId);
@@ -3321,7 +3338,7 @@ function createOAuth(deps) {
3321
3338
  discoveryState: () => discovery.get(serverId)
3322
3339
  };
3323
3340
  try {
3324
- const result = await auth(provider, {
3341
+ const result = await (await loadAuth()).auth(provider, {
3325
3342
  serverUrl,
3326
3343
  fetchFn: deps.fetch
3327
3344
  });
@@ -3341,13 +3358,13 @@ function createOAuth(deps) {
3341
3358
  return;
3342
3359
  }
3343
3360
  if (url.searchParams.get("state") !== flow.state || flow.settled || flow.exchanging) {
3344
- respond(res, 400, "YaoGuang", "This authorization link is not valid. 授权链接无效。");
3361
+ respond(res, 400, "YaoGuang", "This authorization link is not valid. \u6388\u6743\u94fe\u63a5\u65e0\u6548\u3002");
3345
3362
  return;
3346
3363
  }
3347
3364
  const error = url.searchParams.get("error");
3348
3365
  if (error !== null) {
3349
3366
  const code = /^[a-z_]{1,64}$/.test(error) ? error : "error";
3350
- respond(res, 200, "YaoGuang", "Authorization was not completed. 授权未完成,可以关闭此页。");
3367
+ respond(res, 200, "YaoGuang", "Authorization was not completed. \u6388\u6743\u672a\u5b8c\u6210\uff0c\u53ef\u4ee5\u5173\u95ed\u6b64\u9875\u3002");
3351
3368
  finish(serverId, flow, {
3352
3369
  ok: false,
3353
3370
  reason: `authorization was declined (${code})`
@@ -3356,20 +3373,20 @@ function createOAuth(deps) {
3356
3373
  }
3357
3374
  const code = url.searchParams.get("code");
3358
3375
  if (!code) {
3359
- respond(res, 400, "YaoGuang", "The authorization code is missing. 缺少授权码。");
3376
+ respond(res, 400, "YaoGuang", "The authorization code is missing. \u7f3a\u5c11\u6388\u6743\u7801\u3002");
3360
3377
  return;
3361
3378
  }
3362
3379
  flow.exchanging = true;
3363
3380
  try {
3364
- await auth(provider, {
3381
+ await (await loadAuth()).auth(provider, {
3365
3382
  serverUrl,
3366
3383
  authorizationCode: code,
3367
3384
  fetchFn: deps.fetch
3368
3385
  });
3369
- respond(res, 200, "YaoGuang", "Authorization complete. You can close this page. 授权完成,可以关闭此页。");
3386
+ respond(res, 200, "YaoGuang", "Authorization complete. You can close this page. \u6388\u6743\u5b8c\u6210\uff0c\u53ef\u4ee5\u5173\u95ed\u6b64\u9875\u3002");
3370
3387
  finish(serverId, flow, { ok: true });
3371
3388
  } catch (failure) {
3372
- respond(res, 200, "YaoGuang", "Authorization failed. 授权失败,可以关闭此页。");
3389
+ respond(res, 200, "YaoGuang", "Authorization failed. \u6388\u6743\u5931\u8d25\uff0c\u53ef\u4ee5\u5173\u95ed\u6b64\u9875\u3002");
3373
3390
  finish(serverId, flow, {
3374
3391
  ok: false,
3375
3392
  reason: `token exchange failed: ${failure instanceof Error ? failure.message : String(failure)}`
@@ -3384,7 +3401,6 @@ function createOAuth(deps) {
3384
3401
  flows.set(serverId, flow);
3385
3402
  return { url: flow.authorizationUrl.href };
3386
3403
  },
3387
- /** Cancels owned callbacks and invalidates late writes without reading revoked credentials. */
3388
3404
  shutdown() {
3389
3405
  const owned = /* @__PURE__ */ new Set([
3390
3406
  ...flows.keys(),
@@ -3394,7 +3410,6 @@ function createOAuth(deps) {
3394
3410
  ]);
3395
3411
  for (const serverId of owned) invalidate(serverId);
3396
3412
  },
3397
- /** Abandons the authorization in progress, if any. */
3398
3413
  cancel(serverId) {
3399
3414
  const flow = flows.get(serverId);
3400
3415
  if (flow) finish(serverId, flow, {
@@ -3406,13 +3421,7 @@ function createOAuth(deps) {
3406
3421
  }
3407
3422
  //#endregion
3408
3423
  //#region src/content.ts
3409
- const notice = (omitted) => `\n\n[… ${omitted} bytes omitted …]\n\n`;
3410
- /**
3411
- * `text` when it fits in `limit` UTF-8 bytes; otherwise its head and tail
3412
- * split 3:1 around a line saying how much was left out. The notice's bytes
3413
- * are reserved first, so the result never exceeds `limit`, and neither cut
3414
- * splits a character.
3415
- */
3424
+ const notice = (omitted) => `\n\n[\u2026 ${omitted} bytes omitted \u2026]\n\n`;
3416
3425
  function truncate(text, limit) {
3417
3426
  const bytes = Buffer.from(text, "utf8");
3418
3427
  if (bytes.length <= limit) return text;
@@ -3423,30 +3432,25 @@ function truncate(text, limit) {
3423
3432
  while (tail < bytes.length && ((bytes[tail] ?? 0) & 192) === 128) tail += 1;
3424
3433
  return bytes.subarray(0, head).toString("utf8") + notice(tail - head) + bytes.subarray(tail).toString("utf8");
3425
3434
  }
3426
- /** Bytes a base64 blob decodes to. */
3427
3435
  function blobBytes(blob) {
3428
3436
  const padding = blob.endsWith("==") ? 2 : blob.endsWith("=") ? 1 : 0;
3429
3437
  return Math.max(0, Math.floor(blob.length * 3 / 4) - padding);
3430
3438
  }
3431
- /** One embedded resource: its text, or a line naming what it was. */
3432
3439
  function resourceText(resource) {
3433
3440
  if (typeof resource.text === "string") return resource.text;
3434
- return `[二进制资源:${typeof resource.mimeType === "string" ? resource.mimeType : "application/octet-stream"},${typeof resource.blob === "string" ? blobBytes(resource.blob) : 0} 字节]`;
3441
+ return `[\u4e8c\u8fdb\u5236\u8d44\u6e90\uff1a${typeof resource.mimeType === "string" ? resource.mimeType : "application/octet-stream"}\uff0c${typeof resource.blob === "string" ? blobBytes(resource.blob) : 0} \u5b57\u8282]`;
3435
3442
  }
3436
- /** One content block as text; `undefined` for a block with no text form. */
3437
3443
  function blockText(block) {
3438
3444
  switch (block.type) {
3439
3445
  case "text": return typeof block.text === "string" ? block.text : "";
3440
- case "image": return `[图片:${String(block.mimeType ?? "image")}]`;
3441
- case "audio": return `[音频:${String(block.mimeType ?? "audio")}]`;
3446
+ case "image": return `[\u56fe\u7247\uff1a${String(block.mimeType ?? "image")}]`;
3447
+ case "audio": return `[\u97f3\u9891\uff1a${String(block.mimeType ?? "audio")}]`;
3442
3448
  case "resource": return resourceText(block.resource ?? {});
3443
- case "resource_link": return `[资源:${String(block.uri ?? "")}]`;
3449
+ case "resource_link": return `[\u8d44\u6e90\uff1a${String(block.uri ?? "")}]`;
3444
3450
  default: return `[${block.type}]`;
3445
3451
  }
3446
3452
  }
3447
3453
  const isImageType = (mime) => typeof mime === "string" && mime.startsWith("image/");
3448
- /** The last path segment of `uri`, query and fragment removed and percent
3449
- * escapes decoded; `undefined` when that leaves nothing to name a file by. */
3450
3454
  function uriBasename(uri) {
3451
3455
  if (typeof uri !== "string") return void 0;
3452
3456
  const path = uri.replace(/[?#].*$/, "").replace(/\/+$/, "");
@@ -3459,10 +3463,6 @@ function uriBasename(uri) {
3459
3463
  return segment || void 0;
3460
3464
  }
3461
3465
  }
3462
- /** The bytes one block hands back as an image, with the name it goes by, or
3463
- * `undefined` for a block that stays text: an `image` block or an embedded
3464
- * resource `blob`, either with base64 data and an `image/*` type. Whether the
3465
- * host can take the format is the host's judgement, not this one's. */
3466
3466
  function blockImage(block, ordinal) {
3467
3467
  const fallback = `image-${ordinal}`;
3468
3468
  if (block.type === "image") {
@@ -3485,15 +3485,8 @@ function blockImage(block, ordinal) {
3485
3485
  };
3486
3486
  }
3487
3487
  }
3488
- /**
3489
- * A `tools/call` result as the model reads it: text blocks in order, image
3490
- * blocks and embedded image resources as files, other blocks as placeholders,
3491
- * and `structuredContent` as JSON when no text block carried anything. An
3492
- * image's ordinal counts every image this result hands back, in block order.
3493
- */
3494
3488
  function toolResultContent(result) {
3495
3489
  const blocks = Array.isArray(result.content) ? result.content : [];
3496
- const hasText = blocks.some((block) => block.type === "text");
3497
3490
  const files = [];
3498
3491
  const parts = [];
3499
3492
  for (const block of blocks) {
@@ -3501,28 +3494,25 @@ function toolResultContent(result) {
3501
3494
  if (image) files.push(image);
3502
3495
  else parts.push(blockText(block));
3503
3496
  }
3504
- if (!hasText && result.structuredContent !== void 0) parts.unshift(JSON.stringify(result.structuredContent));
3497
+ if (result.structuredContent !== void 0) {
3498
+ const structured = JSON.stringify(result.structuredContent);
3499
+ if (!blocks.some((block) => block.type === "text" && block.text === structured)) parts.unshift(structured);
3500
+ }
3505
3501
  if (!blocks.length && result.structuredContent === void 0 && result.toolResult !== void 0) parts.push(JSON.stringify(result.toolResult));
3506
3502
  return {
3507
3503
  text: parts.join("\n"),
3508
3504
  files
3509
3505
  };
3510
3506
  }
3511
- /**
3512
- * A `prompts/get` result as the text a person's message carries: messages in
3513
- * order, an assistant message introduced by a line saying so.
3514
- */
3515
3507
  function promptText(result) {
3516
3508
  return result.messages.map((message) => {
3517
3509
  const text = blockText(message.content);
3518
- return message.role === "assistant" ? `[以下为 prompt 中的 assistant 消息]\n${text}` : text;
3510
+ return message.role === "assistant" ? `[\u4ee5\u4e0b\u4e3a prompt \u4e2d\u7684 assistant \u6d88\u606f]\n${text}` : text;
3519
3511
  }).join("\n\n");
3520
3512
  }
3521
- /** A `resources/read` result as text, contents in order. */
3522
3513
  function readResultText(result) {
3523
3514
  return result.contents.map((content) => resourceText(content)).join("\n\n");
3524
3515
  }
3525
- /** Counts original resource contents without allocating decoded binary blobs or a combined body. */
3526
3516
  function assertResourceBytes(result, maxBytes) {
3527
3517
  let bytes = 0;
3528
3518
  for (const item of result.contents) {
@@ -3530,45 +3520,32 @@ function assertResourceBytes(result, maxBytes) {
3530
3520
  if (bytes > maxBytes) throw Object.assign(/* @__PURE__ */ new Error("MCP resource exceeds declared budget"), { code: "read-limit" });
3531
3521
  }
3532
3522
  }
3533
- /** A host composer command argument name. */
3534
3523
  const ARGUMENT_NAME = /^[A-Za-z0-9_][A-Za-z0-9_-]{0,63}$/;
3535
- /** The first twelve hex characters of `sha256(slug + "\0" + name)`. */
3536
3524
  function digest(slug, name) {
3537
3525
  return createHash("sha256").update(`${slug}\0${name}`).digest("hex").slice(0, 12);
3538
3526
  }
3539
- /**
3540
- * Maps a candidate to a legal name: characters outside `allowed` become `_`;
3541
- * when any was replaced or the result exceeds `max`, it is cut to
3542
- * `max - 13` characters and `_<hash>` appended, so the result is unique per
3543
- * `(slug, name)` and independent of listing order.
3544
- */
3545
3527
  function legal(prefix, name, slug, allowed, max) {
3546
3528
  const body = name.replace(allowed, "_");
3547
3529
  const full = `${prefix}${body}`;
3548
3530
  if (body === name && full.length <= max) return full;
3549
3531
  return `${full.slice(0, max - 13)}_${digest(slug, name)}`;
3550
3532
  }
3551
- /** `mcp_<slug>_<tool>`, at most 64 characters of `[A-Za-z0-9_-]`. */
3552
3533
  function toolName(slug, tool) {
3553
3534
  return legal(`mcp_${slug}_`, tool, slug, /[^A-Za-z0-9_-]/g, 64);
3554
3535
  }
3555
- /** `<slug>.<prompt>`, a legal composer command name. */
3556
3536
  function commandName(slug, prompt) {
3557
3537
  return legal(`${slug}.`, prompt, slug, /[^A-Za-z0-9._-]/g, 200);
3558
3538
  }
3559
- /** A legal composer argument name for an MCP prompt argument. */
3560
3539
  function argumentName(slug, argument) {
3561
3540
  const mapped = legal("", argument, slug, /[^A-Za-z0-9_-]/g, 64);
3562
3541
  return ARGUMENT_NAME.test(mapped) ? mapped : `_${mapped.slice(0, 63)}`;
3563
3542
  }
3564
- /** Groups items by a mapped name and reports every name more than one item mapped to. */
3565
3543
  function collisions(items, name) {
3566
3544
  const seen = /* @__PURE__ */ new Map();
3567
3545
  for (const item of items) seen.set(name(item), (seen.get(name(item)) ?? 0) + 1);
3568
3546
  return new Set([...seen].filter(([, count]) => count > 1).map(([key]) => key));
3569
3547
  }
3570
3548
  const REFUSED_PROMPT = "maps to the same command name as another prompt of this server";
3571
- /** Runs a server request; a failure's text is checked against the credentials first. */
3572
3549
  async function guarded(secrets, request) {
3573
3550
  try {
3574
3551
  return await request();
@@ -3578,12 +3555,6 @@ async function guarded(secrets, request) {
3578
3555
  throw safe;
3579
3556
  }
3580
3557
  }
3581
- /**
3582
- * The composer's MCP content: prompts as commands and resources as
3583
- * attachments, for the servers an agent selects. Names a server gives are
3584
- * mapped to what the host's command grammar accepts, and mapped back before
3585
- * the server is asked; a prompt whose name or arguments collide is left out.
3586
- */
3587
3558
  function createPrompts(deps) {
3588
3559
  const { store } = deps;
3589
3560
  const mappedPrompts = (serverId, slug) => {
@@ -3612,7 +3583,6 @@ function createPrompts(deps) {
3612
3583
  refused
3613
3584
  };
3614
3585
  };
3615
- /** The server, when `agentId` selects it; otherwise the refusal. */
3616
3586
  const selected = (agentId, serverId) => {
3617
3587
  const record = store.server(serverId);
3618
3588
  if (!record) throw new Error("no such MCP server");
@@ -3620,7 +3590,7 @@ function createPrompts(deps) {
3620
3590
  const live = deps.connections().live(serverId);
3621
3591
  if (!live) {
3622
3592
  const status = deps.connections().status(serverId);
3623
- throw new Error(`MCP server ${record.name} 当前未连接:${status.reason ?? status.state}`);
3593
+ throw new Error(`MCP server ${record.name} \u5f53\u524d\u672a\u8fde\u63a5\uff1a${status.reason ?? status.state}`);
3624
3594
  }
3625
3595
  return {
3626
3596
  record,
@@ -3708,8 +3678,67 @@ function createPrompts(deps) {
3708
3678
  };
3709
3679
  }
3710
3680
  //#endregion
3681
+ //#region src/requests.ts
3682
+ const REQUEST_KIND = "request";
3683
+ const RequestDescriptorSchema = z.strictObject({ dispatched: z.boolean() });
3684
+ const settled = (remote) => ({
3685
+ managedCleanup: "complete",
3686
+ descendantCoverage: "not-applicable",
3687
+ residual: "none",
3688
+ remote
3689
+ });
3690
+ const requestCleanup = {
3691
+ descriptorSchema: RequestDescriptorSchema,
3692
+ async recover(_context, descriptor) {
3693
+ const { dispatched } = RequestDescriptorSchema.parse(descriptor);
3694
+ return settled(dispatched ? "unknown" : "not-applicable");
3695
+ }
3696
+ };
3697
+ function registerRequestRecovery(ctx) {
3698
+ ctx.register(REQUEST_KIND, requestCleanup);
3699
+ }
3700
+ function createSessionRequests(lifecycle) {
3701
+ lifecycle.register(REQUEST_KIND, requestCleanup);
3702
+ return { async run(lease, signal, send) {
3703
+ if (!lease) return send(signal);
3704
+ const receipt = lifecycle.reserve(lease, {
3705
+ kind: REQUEST_KIND,
3706
+ descriptor: { dispatched: false }
3707
+ });
3708
+ const closing = new AbortController();
3709
+ let remote = "not-applicable";
3710
+ let running;
3711
+ let answered = false;
3712
+ receipt.retain({ async cleanup() {
3713
+ if (!answered) closing.abort(/* @__PURE__ */ new Error("session_archived"));
3714
+ await running?.catch(() => {});
3715
+ return settled(remote);
3716
+ } });
3717
+ const linked = AbortSignal.any([signal, closing.signal]);
3718
+ const onClosed = () => {
3719
+ if (!answered) closing.abort(/* @__PURE__ */ new Error("session_archived"));
3720
+ };
3721
+ lease.signal.addEventListener("abort", onClosed, { once: true });
3722
+ try {
3723
+ receipt.acquired({ dispatched: true });
3724
+ const request = send(linked);
3725
+ running = request;
3726
+ const value = await request;
3727
+ remote = "confirmed-ended";
3728
+ return value;
3729
+ } catch (error) {
3730
+ remote = "unknown";
3731
+ throw error;
3732
+ } finally {
3733
+ answered = true;
3734
+ lease.signal.removeEventListener("abort", onClosed);
3735
+ receipt.finishAcquisition();
3736
+ receipt.retire();
3737
+ }
3738
+ } };
3739
+ }
3740
+ //#endregion
3711
3741
  //#region src/store.ts
3712
- /** The plugin's three tables, always under the host-issued prefix. */
3713
3742
  function createMcpStore(storage) {
3714
3743
  const { db, tableName } = storage;
3715
3744
  const servers = tableName("server");
@@ -3780,7 +3809,6 @@ CREATE INDEX IF NOT EXISTS ${tableName("agent_server_by_server")} ON ${selection
3780
3809
  };
3781
3810
  return {
3782
3811
  transaction,
3783
- /** Header-only keyset query; selected-id filtering precedes LIMIT and never parses config. */
3784
3812
  headerPage(agentId, after, limit, ids) {
3785
3813
  if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new Error("invalid header page limit");
3786
3814
  const filter = ids ? `AND s.id IN (${ids.map(() => "?").join(",")}) AND EXISTS (SELECT 1 FROM ${selections} a WHERE a.agent_id=? AND a.server_id=s.id)` : "";
@@ -3800,7 +3828,6 @@ CREATE INDEX IF NOT EXISTS ${tableName("agent_server_by_server")} ON ${selection
3800
3828
  queryVersion: directoryVersion
3801
3829
  };
3802
3830
  },
3803
- /** Advances for every owner catalogue mutation; process restart invalidates owner cursor state. */
3804
3831
  directoryVersion: () => directoryVersion,
3805
3832
  servers() {
3806
3833
  return db.prepare(`SELECT * FROM ${servers} ORDER BY created_at, id`).all().map((row) => parse(row));
@@ -3813,24 +3840,18 @@ CREATE INDEX IF NOT EXISTS ${tableName("agent_server_by_server")} ON ${selection
3813
3840
  const row = db.prepare(`SELECT * FROM ${servers} WHERE slug = ?`).get(slug);
3814
3841
  return row ? parse(row) : void 0;
3815
3842
  },
3816
- /** Inserts or replaces one server row. */
3817
3843
  saveServer,
3818
- /** Creates a server and its initial agent selection atomically. */
3819
3844
  createSelectedServer(record, agentId, selected) {
3820
3845
  transaction(() => {
3821
3846
  saveServer(record);
3822
3847
  if (selected) setServerSelected(agentId, record.id, true);
3823
3848
  });
3824
3849
  },
3825
- /** Adds or removes one agent's selection without replacing other selections. */
3826
3850
  setServerSelected,
3827
3851
  setEnabled(id, enabled) {
3828
3852
  directoryVersion++;
3829
3853
  db.prepare(`UPDATE ${servers} SET enabled = ? WHERE id = ?`).run(enabled ? 1 : 0, id);
3830
3854
  },
3831
- /** Deletes a server with its selections, in one transaction. Its tools'
3832
- * remembered approvals are the host's grants, keyed by this server's id,
3833
- * and a person revokes them in the access list. */
3834
3855
  removeServer(id) {
3835
3856
  directoryVersion++;
3836
3857
  transaction(() => {
@@ -3847,7 +3868,6 @@ CREATE INDEX IF NOT EXISTS ${tableName("agent_server_by_server")} ON ${selection
3847
3868
  agentsOf(serverId) {
3848
3869
  return db.prepare(`SELECT agent_id FROM ${selections} WHERE server_id = ? ORDER BY agent_id`).all(serverId).map((row) => String(row.agent_id));
3849
3870
  },
3850
- /** Replaces an agent's selection whole. */
3851
3871
  setAgentServers(agentId, serverIds) {
3852
3872
  directoryVersion++;
3853
3873
  transaction(() => {
@@ -3860,9 +3880,17 @@ CREATE INDEX IF NOT EXISTS ${tableName("agent_server_by_server")} ON ${selection
3860
3880
  }
3861
3881
  //#endregion
3862
3882
  //#region src/input-schema.ts
3863
- /** Compiles a remote input contract before a tool becomes callable. */
3864
- /** Enforces complete remote schemas locally; absent dialect declarations use MCP's 2020-12 default. */
3883
+ function loadAjv() {
3884
+ const load = createRequire(import.meta.url);
3885
+ return {
3886
+ Ajv: load("ajv").Ajv,
3887
+ Ajv2019: load("ajv/dist/2019.js").Ajv2019,
3888
+ Ajv2020: load("ajv/dist/2020.js").Ajv2020,
3889
+ addFormats: load("ajv-formats")
3890
+ };
3891
+ }
3865
3892
  function inputValidator(schema) {
3893
+ const { Ajv, Ajv2019, Ajv2020, addFormats } = loadAjv();
3866
3894
  const version = schema.$schema;
3867
3895
  const options = {
3868
3896
  strict: false,
@@ -3888,7 +3916,6 @@ const RESOURCE_TOOL = "mcp_resource_read";
3888
3916
  const REFUSED_TAKEN = "name already taken";
3889
3917
  const REFUSED_COLLISION = "maps to the same name as another tool of this server";
3890
3918
  const RESERVED_TOOL_NAMES = /* @__PURE__ */ new Set([RESOURCE_TOOL, ...TOOL_NAMES]);
3891
- /** Host-owned MCP tool names that a remote server cannot register, even if disabled. */
3892
3919
  function reservedToolName(name) {
3893
3920
  return RESERVED_TOOL_NAMES.has(name);
3894
3921
  }
@@ -3899,11 +3926,6 @@ const ResourceInput = z.object({
3899
3926
  const messageOf = (error) => error instanceof Error ? error.message : String(error);
3900
3927
  const isTimeout = (error) => error?.code === -32001;
3901
3928
  const isUnauthorized = (error) => error?.name === "UnauthorizedError" || error?.constructor?.name === "UnauthorizedError";
3902
- /**
3903
- * The model-visible side: one registration per server tool, visible to the
3904
- * agents that select its server, replaced whole and synchronously when a new
3905
- * snapshot arrives; the `mcp_resource_read` tool; approval per call.
3906
- */
3907
3929
  function createTools(deps) {
3908
3930
  const { ctx, store } = deps;
3909
3931
  const callTimeout = deps.callTimeoutMs ?? 3e5;
@@ -3922,14 +3944,8 @@ function createTools(deps) {
3922
3944
  const notConnected = (serverId, name) => {
3923
3945
  const status = deps.connections().status(serverId);
3924
3946
  if (status.state === "connected") return void 0;
3925
- if (status.state === "needs-auth") return {
3926
- content: `MCP server ${name} 需要重新授权`,
3927
- isError: true
3928
- };
3929
- return {
3930
- content: `MCP server ${name} 当前未连接:${status.reason ?? status.state}`,
3931
- isError: true
3932
- };
3947
+ if (status.state === "needs-auth") return mcpFailure(`MCP server ${name} needs authorization`);
3948
+ return mcpFailure(`MCP server ${name} is disconnected: ${status.reason ?? status.state}`);
3933
3949
  };
3934
3950
  async function approve(serverId, server, tool, input, exec) {
3935
3951
  const decision = deps.approval.decide(exec, {
@@ -3944,7 +3960,7 @@ function createTools(deps) {
3944
3960
  ],
3945
3961
  remember: {
3946
3962
  key: `mcp:${serverId}:${tool}`,
3947
- label: `调用 MCP 服务器「${server.name}」的 ${tool}`
3963
+ label: `\u8c03\u7528 MCP \u670d\u52a1\u5668\u300c${server.name}\u300d\u7684 ${tool}`
3948
3964
  }
3949
3965
  });
3950
3966
  if (decision.kind === "ask") return decision.result;
@@ -3953,81 +3969,103 @@ function createTools(deps) {
3953
3969
  case "allowed-once":
3954
3970
  case "allowed-session":
3955
3971
  case "allowed-always": return;
3956
- case "record-failed": return {
3957
- content: `could not remember the approval, so the call was not made: ${result.message}`,
3958
- isError: true
3959
- };
3972
+ case "record-failed": return mcpFailure(`Could not remember the approval; no call was made: ${result.message}`);
3960
3973
  case "rejected": {
3961
3974
  const reason = result.reason?.trim() ?? "";
3962
- return {
3963
- content: reason ? `permission refused by the person: ${reason}` : "permission refused by the person.",
3964
- isError: true
3965
- };
3975
+ return mcpFailure(reason ? `Permission refused: ${reason}` : "Permission refused by the person");
3966
3976
  }
3967
- case "unavailable": return {
3968
- content: "approval prompts are disabled; this MCP tool cannot be called",
3969
- isError: true
3970
- };
3977
+ case "unavailable": return mcpFailure("Approval prompts are disabled; no MCP call was made");
3971
3978
  }
3972
3979
  }
3973
3980
  async function call(serverId, tool, input, exec) {
3974
3981
  const record = store.server(serverId);
3975
- if (!record || !store.isSelected(exec.address.agentId, serverId)) return {
3976
- content: "this MCP server is not selected by this agent",
3977
- isError: true
3978
- };
3982
+ if (!record || !store.isSelected(exec.address.agentId, serverId)) return mcpFailure("This MCP server is not selected by this agent");
3979
3983
  const current = deps.connections().snapshot(serverId)?.tools.find((candidate) => candidate.name === tool.name);
3980
- if (!current || definitionKey(record.name, current) !== definitionKey(record.name, tool)) return {
3981
- content: "MCP tool definition changed; search for the current definition again.",
3982
- isError: true
3983
- };
3984
+ if (!current || definitionKey(record.name, current) !== definitionKey(record.name, tool)) return mcpFailure("MCP tool definition changed; search for the current definition again");
3984
3985
  const down = notConnected(serverId, record.name);
3985
3986
  if (down) return down;
3986
3987
  const gate = await approve(serverId, record, tool.name, input, exec);
3987
3988
  if (gate) return gate;
3988
3989
  const live = deps.connections().live(serverId);
3989
- if (!live) return notConnected(serverId, record.name) ?? {
3990
- content: "not connected",
3991
- isError: true
3992
- };
3990
+ if (!live) return notConnected(serverId, record.name) ?? mcpFailure("Not connected");
3991
+ const send = (signal) => live.client.callTool({
3992
+ name: tool.name,
3993
+ arguments: input
3994
+ }, void 0, {
3995
+ signal,
3996
+ timeout: callTimeout
3997
+ });
3998
+ const sent = {};
3993
3999
  try {
3994
- const result = await live.client.callTool({
3995
- name: tool.name,
3996
- arguments: input
3997
- }, void 0, {
3998
- signal: exec.signal,
3999
- timeout: callTimeout
4000
- });
4000
+ const result = deps.requests ? await deps.requests.run(exec.session, exec.signal, (signal) => {
4001
+ sent.signal = signal;
4002
+ return send(signal);
4003
+ }) : await send(exec.signal);
4001
4004
  const { text: raw, files } = toolResultContent(result);
4002
4005
  const text = redact(raw, live.secrets);
4003
- return {
4004
- content: JSON.stringify({
4005
- text,
4006
- sourceComplete: true
4007
- }),
4008
- ...result.isError === true ? { isError: true } : {},
4009
- ...files.length === 0 ? {} : { files }
4006
+ let capture;
4007
+ try {
4008
+ capture = { body: await captureTextBody(text, exec) };
4009
+ } catch {
4010
+ capture = { captureError: "source_capture_failed" };
4011
+ }
4012
+ let publication = {
4013
+ refs: [],
4014
+ notes: []
4010
4015
  };
4011
- } catch (error) {
4012
- if (isTimeout(error)) return {
4013
- content: `调用超时(${Math.round(callTimeout / 6e4)} 分钟)`,
4014
- isError: true
4016
+ if (files.length) try {
4017
+ publication = await exec.publishFiles(files, exec.signal);
4018
+ } catch {
4019
+ publication = {
4020
+ refs: [],
4021
+ notes: ["MCP media publication failed after the remote response completed."]
4022
+ };
4023
+ }
4024
+ const mediaMissing = publication.notes.length > 0 || publication.refs.length !== files.length;
4025
+ const data = {
4026
+ ok: true,
4027
+ serverId,
4028
+ serverName: redact(record.name, live.secrets),
4029
+ remoteTool: tool.name,
4030
+ registeredName: toolName(record.slug, tool.name),
4031
+ remoteIsError: result.isError === true,
4032
+ mediaCount: files.length,
4033
+ media: [...publication.refs],
4034
+ publicationNotes: publication.notes.map((note) => redact(note, live.secrets)),
4035
+ ...mediaMissing ? { representationError: "media_not_published" } : {},
4036
+ complete: !("captureError" in capture) && !mediaMissing,
4037
+ ...capture
4015
4038
  };
4016
- if (exec.signal.aborted) return {
4017
- content: "the call was cancelled",
4018
- isError: true
4039
+ return {
4040
+ data,
4041
+ execution: { state: "committed" },
4042
+ isError: result.isError === true,
4043
+ ..."body" in capture ? { source: {
4044
+ complete: data.complete,
4045
+ bodies: [capture.body]
4046
+ } } : {},
4047
+ presentation: {
4048
+ type: "mcp-remote",
4049
+ schemaVersion: 1,
4050
+ state: "captureError" in capture || mediaMissing ? "partial" : result.isError ? "error" : "ready",
4051
+ summary: `${data.serverName}: ${tool.name}`,
4052
+ fields: {
4053
+ serverId,
4054
+ remoteTool: tool.name
4055
+ },
4056
+ actions: [],
4057
+ bodyRefs: "body" in capture ? [capture.body] : []
4058
+ }
4019
4059
  };
4060
+ } catch (error) {
4061
+ if (!sent.signal && /^session_(archived|lifetime_stale)/.test(messageOf(error))) return mcpFailure(messageOf(error), "not-started", "session_archived");
4062
+ if (isTimeout(error)) return mcpFailure(`MCP call timed out after ${callTimeout} ms`, "unknown", "mcp_timeout");
4063
+ if (exec.signal.aborted || sent.signal?.aborted) return mcpFailure("The remote call was cancelled; its outcome is unknown", "unknown", "mcp_cancelled");
4020
4064
  if (isUnauthorized(error)) {
4021
4065
  deps.connections().needsAuth(serverId, "the server refused the stored authorization");
4022
- return {
4023
- content: `MCP server ${record.name} 需要重新授权`,
4024
- isError: true
4025
- };
4066
+ return mcpFailure(`MCP server ${record.name} needs authorization`, "unknown", "mcp_unauthorized");
4026
4067
  }
4027
- return {
4028
- content: `MCP server ${record.name} 调用失败:${redact(messageOf(error), live.secrets)}`,
4029
- isError: true
4030
- };
4068
+ return mcpFailure(`MCP server ${record.name} call failed: ${redact(messageOf(error), live.secrets)}`, "unknown", "mcp_call_failed");
4031
4069
  }
4032
4070
  }
4033
4071
  const definitionKey = (serverName, tool) => createHash("sha256").update(JSON.stringify([
@@ -4036,11 +4074,6 @@ function createTools(deps) {
4036
4074
  tool.description ?? "",
4037
4075
  tool.inputSchema
4038
4076
  ])).digest("hex");
4039
- /**
4040
- * Replaces a server's registrations with what `snapshot` lists, in one
4041
- * synchronous pass: withdraws what disappeared, registers what is new and
4042
- * re-registers what changed. `undefined` withdraws everything.
4043
- */
4044
4077
  function apply(serverId, snapshot) {
4045
4078
  const current = registered.get(serverId) ?? /* @__PURE__ */ new Map();
4046
4079
  const record = store.server(serverId);
@@ -4072,7 +4105,7 @@ function createTools(deps) {
4072
4105
  }
4073
4106
  for (const [name, { tool, key, input }] of wanted) {
4074
4107
  if (current.has(name) || !record) continue;
4075
- const description = `[MCP · ${record.name}] ${tool.description ?? ""}`;
4108
+ const description = `[MCP \u00b7 ${record.name}] ${tool.description ?? ""}`;
4076
4109
  try {
4077
4110
  const dispose = handleFor(serverId).tools.register({
4078
4111
  name,
@@ -4081,10 +4114,8 @@ function createTools(deps) {
4081
4114
  preload: false,
4082
4115
  catalogKind: "dynamic",
4083
4116
  deliveryKind: "preview",
4084
- outputSchema: z.union([z.strictObject({
4085
- text: z.string(),
4086
- sourceComplete: z.boolean()
4087
- }), z.string().max(1024)]),
4117
+ outputSchema: McpRemoteDataSchema,
4118
+ formatModel: async (data) => mcpRemoteDocument(data),
4088
4119
  available: () => deps.connections().status(serverId).state === "connected",
4089
4120
  jsonSchema: tool.inputSchema,
4090
4121
  execute: (input, exec) => call(serverId, tool, input, exec)
@@ -4111,47 +4142,67 @@ function createTools(deps) {
4111
4142
  mapped.delete(serverId);
4112
4143
  }
4113
4144
  }
4114
- /** Forgets a removed server's registrations. */
4115
4145
  function forget(serverId) {
4116
4146
  apply(serverId, void 0);
4117
4147
  scoped.delete(serverId);
4118
4148
  }
4119
4149
  async function readResource(input, exec, maxBytes) {
4120
4150
  const record = store.serverBySlug(input.server);
4121
- if (!record || !store.isSelected(exec.address.agentId, record.id)) return {
4122
- content: `server "${input.server}" is not selected by this agent`,
4123
- isError: true
4124
- };
4151
+ if (!record || !store.isSelected(exec.address.agentId, record.id)) throw new Error(`Server ${input.server} is not selected by this agent`);
4125
4152
  const down = notConnected(record.id, record.name);
4126
- if (down) return down;
4153
+ if (down) throw new Error(down.data.ok ? "MCP disconnected" : down.data.message);
4127
4154
  const live = deps.connections().live(record.id);
4128
- if (!live) return {
4129
- content: `MCP server ${record.name} 当前未连接`,
4130
- isError: true
4131
- };
4155
+ if (!live) throw new Error(`MCP server ${record.name} is disconnected`);
4132
4156
  try {
4133
- const result = await withResourceBudget(maxBytes, () => live.client.readResource({ uri: input.uri }, {
4134
- signal: exec.signal,
4157
+ const read = (signal) => live.client.readResource({ uri: input.uri }, {
4158
+ signal,
4135
4159
  timeout: callTimeout
4136
- }));
4160
+ });
4161
+ const result = await withResourceBudget(maxBytes, () => deps.requests ? deps.requests.run(exec.session, exec.signal, read) : read(exec.signal));
4137
4162
  assertResourceBytes(result, maxBytes);
4138
4163
  const content = redact(readResultText(result), live.secrets);
4139
4164
  if (Buffer.byteLength(content) > maxBytes) throw Object.assign(/* @__PURE__ */ new Error("MCP resource exceeds declared budget"), { code: "read-limit" });
4140
- return { content };
4141
- } catch (error) {
4142
- if (error instanceof Error && "code" in error && error.code === "read-limit") throw error;
4143
- if (isTimeout(error)) return {
4144
- content: `调用超时(${Math.round(callTimeout / 6e4)} 分钟)`,
4145
- isError: true
4165
+ let capture;
4166
+ try {
4167
+ capture = { body: await captureTextBody(content, exec) };
4168
+ } catch {
4169
+ capture = { captureError: "source_capture_failed" };
4170
+ }
4171
+ const binaryFiles = result.contents.flatMap((part, index) => "blob" in part && typeof part.blob === "string" ? [{
4172
+ name: `resource-${index + 1}`,
4173
+ data: new Uint8Array(Buffer.from(part.blob, "base64"))
4174
+ }] : []);
4175
+ let publication = {
4176
+ refs: [],
4177
+ notes: []
4146
4178
  };
4179
+ if (binaryFiles.length) try {
4180
+ publication = await exec.publishFiles(binaryFiles, exec.signal);
4181
+ } catch {
4182
+ publication = {
4183
+ refs: [],
4184
+ notes: ["Resource binary publication failed after the remote read completed."]
4185
+ };
4186
+ }
4187
+ const missing = publication.notes.length > 0 || publication.refs.length !== binaryFiles.length;
4147
4188
  return {
4148
- content: `reading ${input.uri} from MCP server ${record.name} failed: ${redact(messageOf(error), live.secrets)}`,
4149
- isError: true
4189
+ serverId: record.id,
4190
+ uri: input.uri,
4191
+ complete: "body" in capture && !missing,
4192
+ ...binaryFiles.length ? { binary: {
4193
+ count: binaryFiles.length,
4194
+ files: [...publication.refs],
4195
+ notes: publication.notes.map((note) => redact(note, live.secrets))
4196
+ } } : {},
4197
+ ...missing ? { representationError: "binary_source_unavailable" } : {},
4198
+ ...capture
4150
4199
  };
4200
+ } catch (error) {
4201
+ if (error instanceof Error && "code" in error && error.code === "read-limit") throw error;
4202
+ if (isTimeout(error)) throw new Error(`MCP resource read timed out after ${callTimeout} ms`);
4203
+ throw new Error(`reading ${input.uri} from MCP server ${record.name} failed: ${redact(messageOf(error), live.secrets)}`);
4151
4204
  }
4152
4205
  }
4153
- /** Registers `mcp_resource_read`, visible to an agent that selects a server
4154
- * offering resources. */
4155
4206
  function registerResourceTool() {
4156
4207
  return ctx.forAgents((agentId) => store.agentServers(agentId).some((id) => (deps.connections().snapshot(id)?.resources.length ?? 0) > 0)).tools.register({
4157
4208
  name: RESOURCE_TOOL,
@@ -4161,21 +4212,36 @@ function createTools(deps) {
4161
4212
  items: z.array(ResourceInput).min(1).max(32).describe("Ordered selected-server resources, maximum 32; physical source limits are managed internally."),
4162
4213
  outputTokens: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional().describe("Desired text delivery tokens, excluding attached media. Accepted originals are retained before bounded previews.")
4163
4214
  }),
4164
- outputSchema: batchResult(z.strictObject({ content: z.string() }), z.strictObject({
4165
- server: z.string(),
4166
- uri: z.string()
4167
- })),
4215
+ outputSchema: McpResourceDataSchema,
4216
+ formatModel: async (data) => mcpResourceDocument(data),
4168
4217
  deliveryKind: "preview",
4169
4218
  async execute(input, exec) {
4170
4219
  const batch = await settle(input.items.map((item) => ({
4171
4220
  server: item.server,
4172
4221
  uri: item.uri
4173
4222
  })), async (_target, index) => {
4174
- const result = await readResource(input.items[index], exec, Math.min(1048576, Math.floor(4194304 / input.items.length)));
4175
- if (result.isError) throw new Error(result.content);
4176
- return result;
4223
+ return await readResource(input.items[index], exec, Math.min(1048576, Math.floor(4194304 / input.items.length)));
4177
4224
  });
4178
- return { content: JSON.stringify(batch) };
4225
+ const failed = batch.results.some((row) => !row.ok), successful = batch.results.some((row) => row.ok);
4226
+ const bodies = batch.results.flatMap((row) => row.ok && "body" in row.value ? [row.value.body] : []);
4227
+ return {
4228
+ data: batch,
4229
+ execution: { state: failed ? successful ? "partial" : "unknown" : "committed" },
4230
+ isError: failed,
4231
+ ...bodies.length ? { source: {
4232
+ complete: !failed && batch.results.every((row) => row.ok && row.value.complete),
4233
+ bodies
4234
+ } } : {},
4235
+ presentation: {
4236
+ type: "mcp-resources",
4237
+ schemaVersion: 1,
4238
+ summary: `${batch.results.length} MCP resources`,
4239
+ state: failed || batch.results.some((row) => row.ok && !row.value.complete) ? "partial" : "ready",
4240
+ fields: {},
4241
+ actions: [],
4242
+ bodyRefs: bodies
4243
+ }
4244
+ };
4179
4245
  }
4180
4246
  });
4181
4247
  }
@@ -4183,8 +4249,6 @@ function createTools(deps) {
4183
4249
  apply,
4184
4250
  forget,
4185
4251
  registerResourceTool,
4186
- /** The catalog `getServer` shows: every listed tool, its mapped name and
4187
- * why it was refused, if it was. */
4188
4252
  catalogTools(serverId, snapshot) {
4189
4253
  const names = mapped.get(serverId);
4190
4254
  const refusals = refused.get(serverId);
@@ -4201,7 +4265,6 @@ function createTools(deps) {
4201
4265
  }
4202
4266
  //#endregion
4203
4267
  //#region src/index.ts
4204
- /** The plugin, with its connection timing replaced where a test asks. */
4205
4268
  function createMcpPlugin(options = {}) {
4206
4269
  return {
4207
4270
  name: "@eum-agent/integration-mcp",
@@ -4217,8 +4280,10 @@ function createMcpPlugin(options = {}) {
4217
4280
  "work-lifecycle",
4218
4281
  "agent-definition",
4219
4282
  "agent-definition-management",
4220
- "agent-configuration-store"
4283
+ "agent-configuration-store",
4284
+ "session-lifecycle"
4221
4285
  ],
4286
+ recoverSessionResources: registerRequestRecovery,
4222
4287
  apply(ctx, config) {
4223
4288
  const store = createMcpStore(ctx.storage.open());
4224
4289
  const commands = ctx.services.get("host-commands");
@@ -4265,6 +4330,7 @@ function createMcpPlugin(options = {}) {
4265
4330
  connections: () => connections,
4266
4331
  approval,
4267
4332
  log: ctx.log,
4333
+ requests: createSessionRequests(ctx.services.get("session-lifecycle")),
4268
4334
  ...options.callTimeoutMs === void 0 ? {} : { callTimeoutMs: options.callTimeoutMs }
4269
4335
  });
4270
4336
  let announce = () => {};
@@ -4302,6 +4368,27 @@ function createMcpPlugin(options = {}) {
4302
4368
  };
4303
4369
  return [...credentialNames(record).map(read), ...oauth.secrets(serverId)];
4304
4370
  };
4371
+ ctx.context.contribute({
4372
+ id: "mcp-server-instructions",
4373
+ slot: "system",
4374
+ placement: {
4375
+ chapter: "capabilities",
4376
+ order: 30,
4377
+ category: "mcp"
4378
+ },
4379
+ async contribute(view) {
4380
+ const system = [];
4381
+ for (const serverId of store.agentServers(view.address.agentId)) {
4382
+ const server = store.server(serverId);
4383
+ const live = connections.live(serverId);
4384
+ if (!server?.enabled || !live) continue;
4385
+ const instructions = connections.snapshot(serverId)?.instructions;
4386
+ if (!instructions) continue;
4387
+ system.push(redact(`MCP server instructions: ${JSON.stringify(server.name)} (${server.slug}, server ID: ${serverId})\n${instructions}`, [...live.secrets, ...secretValues(secretsOf(serverId))]));
4388
+ }
4389
+ return { system };
4390
+ }
4391
+ });
4305
4392
  const methods = registerMethods({
4306
4393
  commands,
4307
4394
  ctx,
@@ -4360,7 +4447,7 @@ function createMcpPlugin(options = {}) {
4360
4447
  entries: [
4361
4448
  {
4362
4449
  tools: ["mcp_server_list"],
4363
- text: "`mcp_server_list` lists configured servers and whether this agent selects them; with `serverId` it reads one selected server’s safe configuration and credential status."
4450
+ text: "`mcp_server_list` lists configured servers and whether this agent selects them; with `serverId` it reads one selected server\u2019s safe configuration and credential status."
4364
4451
  },
4365
4452
  {
4366
4453
  tools: ["mcp_server_create"],
@@ -4372,7 +4459,7 @@ function createMcpPlugin(options = {}) {
4372
4459
  },
4373
4460
  {
4374
4461
  tools: ["mcp_server_set_selected"],
4375
- text: "`mcp_server_set_selected` changes only this agent’s selection."
4462
+ text: "`mcp_server_set_selected` changes only this agent\u2019s selection."
4376
4463
  }
4377
4464
  ]
4378
4465
  });
@@ -4409,9 +4496,12 @@ function createMcpPlugin(options = {}) {
4409
4496
  unbind();
4410
4497
  unbind = () => {};
4411
4498
  });
4412
- connections.boot();
4499
+ ctx.afterStartup(() => connections.boot());
4413
4500
  const ui = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
4414
- if (!options.withoutUi && existsSync(ui)) ctx.client.registerUi({ module: ui });
4501
+ if (!options.withoutUi && existsSync(ui)) ctx.client.registerPackageFiles({
4502
+ root: dirname(ui),
4503
+ entry: "ui.js"
4504
+ });
4415
4505
  }
4416
4506
  };
4417
4507
  }