@eum-agent/integration-mcp 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +1439 -220
  2. package/package.json +7 -5
  3. package/ui/ui.js +206 -136
package/dist/index.js CHANGED
@@ -5,12 +5,18 @@ import { isAbsolute, posix, win32 } from "node:path";
5
5
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
6
6
  import { PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
7
7
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
8
+ import { AsyncLocalStorage } from "node:async_hooks";
8
9
  import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";
9
10
  import { createHash, randomBytes, randomUUID } from "node:crypto";
10
11
  import { isDeepStrictEqual } from "node:util";
12
+ import { setImmediate } from "node:timers/promises";
11
13
  import { createServer } from "node:http";
12
14
  import { auth, discoverOAuthServerInfo, refreshAuthorization, selectResourceURL } from "@modelcontextprotocol/sdk/client/auth.js";
13
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";
14
20
  //#region src/names.ts
15
21
  /**
16
22
  * The name rules both halves apply: the gateway's zod in `config.ts` and the
@@ -26,18 +32,18 @@ const HEADER_NAME = /^[A-Za-z0-9_][A-Za-z0-9_-]{0,99}$/;
26
32
  //#endregion
27
33
  //#region src/config.ts
28
34
  const EnvEntrySchema = z.object({
29
- name: z.string().regex(ENV_NAME, "environment variable names must match ^[A-Za-z_][A-Za-z0-9_]*$").refine((name) => !name.startsWith("YAOGUANG_"), "YAOGUANG_* variables are reserved"),
35
+ name: z.string().regex(ENV_NAME, "environment variable names must match ^[A-Za-z_][A-Za-z0-9_]*$").refine((name) => !name.startsWith("YAOGUANG_"), "YAOGUANG_* variables are reserved").describe("Environment variable identifier; YAOGUANG_* is reserved."),
30
36
  /** A credential: its value lives in the credential manager as `env.<name>`. */
31
- secret: z.boolean(),
37
+ secret: z.boolean().describe("True uses an existing env.<name> credential and forbids value; false requires a plain value."),
32
38
  /** The plain value; absent for a credential. */
33
- value: z.string().max(32768).refine((value) => !value.includes("\0"), "invalid environment value").optional()
39
+ value: z.string().max(32768).refine((value) => !value.includes("\0"), "invalid environment value").optional().describe("Plain environment value, maximum 32768 UTF-16 code units and no NUL. Omit for a credential.")
34
40
  }).strict().refine((entry) => entry.secret || entry.value !== void 0, "a plain variable needs a value").refine((entry) => !entry.secret || entry.value === void 0, "a credential is not stored here");
35
41
  /** A local command. `command` is an absolute path or a bare name looked up on PATH. */
36
42
  const StdioConfigSchema = z.object({
37
- command: z.string().refine((command) => command.trim().length > 0 && !command.includes("\0"), "command is required").min(1, "command is required").max(4096).refine((command) => isAbsolute(command) || /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(command) || !/[\\/:]/.test(command), "command must be an absolute path or a bare command name"),
38
- args: z.array(z.string().max(32768).refine((value) => !value.includes("\0"), "invalid argument")).max(256).default([]),
39
- cwd: z.string().refine((cwd) => !cwd.includes("\0") && (isAbsolute(cwd) || /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(cwd)), "cwd must be an absolute path").optional(),
40
- env: z.array(EnvEntrySchema).max(256).default([])
43
+ command: z.string().refine((command) => command.trim().length > 0 && !command.includes("\0"), "command is required").min(1, "command is required").max(4096).refine((command) => isAbsolute(command) || /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(command) || !/[\\/:]/.test(command), "command must be an absolute path or a bare command name").describe("Executable absolute path or bare PATH name, maximum 4096 UTF-16 code units. Shell command text is not accepted."),
44
+ args: z.array(z.string().max(32768).refine((value) => !value.includes("\0"), "invalid argument")).max(256).default([]).describe("Direct argv array, default empty, maximum 256 arguments; each is at most 32768 UTF-16 code units and contains no NUL."),
45
+ cwd: z.string().refine((cwd) => !cwd.includes("\0") && (isAbsolute(cwd) || /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(cwd)), "cwd must be an absolute path").optional().describe("Optional absolute working directory using host path syntax; no NUL."),
46
+ env: z.array(EnvEntrySchema).max(256).default([]).describe("Environment entries, default empty, maximum 256. Duplicate names must declare equal values.")
41
47
  }).strict().refine((config) => config.env.every((entry, index) => config.env.slice(0, index).every((previous) => previous.name !== entry.name || previous.secret === entry.secret && previous.value === entry.value)), "environment variable aliases must have equal values");
42
48
  /** A remote Streamable HTTP endpoint. Header values are credentials (`header.<name>`). */
43
49
  const HttpConfigSchema = z.object({
@@ -48,13 +54,13 @@ const HttpConfigSchema = z.object({
48
54
  } catch {
49
55
  return false;
50
56
  }
51
- }, "url must be an http(s) URL"),
57
+ }, "url must be an http(s) URL").describe("HTTP or HTTPS MCP endpoint URL without embedded username or password."),
52
58
  auth: z.enum([
53
59
  "none",
54
60
  "headers",
55
61
  "oauth"
56
- ]),
57
- headers: z.array(z.string().regex(HEADER_NAME, "invalid header name")).max(64).default([])
62
+ ]).describe("Authentication mode: none, stored header credentials, or OAuth."),
63
+ headers: z.array(z.string().regex(HEADER_NAME, "invalid header name")).max(64).default([]).describe("Unique header credential names, maximum 64, default empty; allowed only with auth=headers. Values come from header.<name> credentials.")
58
64
  }).strict().refine((config) => new Set(config.headers.map((name) => name.toLowerCase())).size === config.headers.length, "header names must be unique").refine((config) => config.auth === "headers" || config.headers.length === 0, "headers are only sent when auth is \"headers\"");
59
65
  /** What a person saves; `id` absent creates a server. */
60
66
  const SaveServerSchema = z.discriminatedUnion("transport", [z.object({
@@ -205,6 +211,82 @@ function redactReason(text, secrets) {
205
211
  return containsSecret(text, secrets) ? REDACTED_REASON : text;
206
212
  }
207
213
  //#endregion
214
+ //#region src/transport/limits.ts
215
+ /** Response framing bounds applied before the SDK accumulates or decodes upstream content. */
216
+ /** The maximum complete encoded response admitted by this owner. */
217
+ const RESPONSE_BYTES = 8388608;
218
+ const resourceBudget = new AsyncLocalStorage();
219
+ /** Binds one original resource request to its conservative encoded protocol capacity. */
220
+ function withResourceBudget(maxBytes, request) {
221
+ return resourceBudget.run(maxBytes, request);
222
+ }
223
+ /** Returns the current request's bound without adding vendor fields to the protocol. */
224
+ function responseBudget() {
225
+ const raw = resourceBudget.getStore();
226
+ return raw === void 0 ? RESPONSE_BYTES : Math.min(RESPONSE_BYTES, Math.max(6 * raw, 4 * Math.ceil(raw / 3)) + 65536);
227
+ }
228
+ /** Safe limit failure without an upstream body or credentials. */
229
+ function responseLimit() {
230
+ return Object.assign(/* @__PURE__ */ new Error("MCP response exceeds declared budget"), { code: "read-limit" });
231
+ }
232
+ /** Bounds ordinary bodies and each SSE event while preserving HTTP metadata and cancellation. */
233
+ function boundedFetch(fetch, maxBytes = RESPONSE_BYTES) {
234
+ return async (input, init) => {
235
+ const capacity = Math.min(maxBytes, responseBudget());
236
+ const response = await fetch(input, init);
237
+ if (!response.body) return response;
238
+ const sse = response.headers.get("content-type")?.includes("text/event-stream") ?? false;
239
+ const length = Number(response.headers.get("content-length"));
240
+ if (!sse && Number.isFinite(length) && length > capacity) {
241
+ await response.body.cancel();
242
+ throw responseLimit();
243
+ }
244
+ const reader = response.body.getReader();
245
+ let bytes = 0, lineBytes = 0;
246
+ const body = new ReadableStream({
247
+ async pull(controller) {
248
+ try {
249
+ const next = await reader.read();
250
+ if (next.done) {
251
+ controller.close();
252
+ return;
253
+ }
254
+ if (sse) for (const byte of next.value) {
255
+ bytes++;
256
+ if (bytes > capacity) throw responseLimit();
257
+ if (byte === 10) {
258
+ if (lineBytes === 0 || lineBytes === 1 && previous === 13) bytes = 0;
259
+ lineBytes = 0;
260
+ } else lineBytes++;
261
+ previous = byte;
262
+ }
263
+ else {
264
+ bytes += next.value.byteLength;
265
+ if (bytes > capacity) throw responseLimit();
266
+ }
267
+ controller.enqueue(next.value);
268
+ } catch (error) {
269
+ await reader.cancel(error).catch(() => {});
270
+ controller.error(error);
271
+ }
272
+ },
273
+ cancel: (reason) => reader.cancel(reason)
274
+ });
275
+ let previous = -1;
276
+ const bounded = new Response(body, {
277
+ status: response.status,
278
+ statusText: response.statusText,
279
+ headers: response.headers
280
+ });
281
+ for (const key of [
282
+ "url",
283
+ "redirected",
284
+ "type"
285
+ ]) Object.defineProperty(bounded, key, { value: response[key] });
286
+ return bounded;
287
+ };
288
+ }
289
+ //#endregion
208
290
  //#region src/transport/http.ts
209
291
  /**
210
292
  * A Streamable HTTP transport whose every request goes through the gateway's
@@ -214,7 +296,7 @@ function redactReason(text, secrets) {
214
296
  */
215
297
  function httpTransport(input) {
216
298
  return new StreamableHTTPClientTransport(new URL(input.url), {
217
- fetch: input.fetch,
299
+ fetch: boundedFetch(input.fetch),
218
300
  requestInit: { headers: { ...input.headers } },
219
301
  ...input.authProvider ? { authProvider: input.authProvider } : {}
220
302
  });
@@ -360,30 +442,48 @@ var ProcessTransport = class {
360
442
  onmessage;
361
443
  process;
362
444
  buffer = new ReadBuffer();
445
+ responseBounds = /* @__PURE__ */ new Map();
446
+ bufferedBytes = 0;
363
447
  closed = false;
364
448
  stopping;
365
- constructor(process) {
449
+ maxBytes;
450
+ constructor(process, maxBytes = RESPONSE_BYTES) {
366
451
  this.process = process;
452
+ this.maxBytes = maxBytes;
367
453
  }
368
454
  async start() {
369
455
  const { stdout, stdin } = this.process;
370
456
  stdout.on("data", (chunk) => {
371
- try {
372
- this.buffer.append(chunk);
373
- } catch (error) {
374
- this.onerror?.(error);
375
- return;
376
- }
377
- while (true) {
378
- let message;
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
+ }
379
471
  try {
380
- message = this.buffer.readMessage();
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
+ }
381
481
  } catch (error) {
482
+ this.bufferedBytes = 0;
483
+ this.buffer.clear();
382
484
  this.onerror?.(error);
383
- continue;
384
485
  }
385
- if (message === null) break;
386
- this.onmessage?.(message);
486
+ offset = finish;
387
487
  }
388
488
  });
389
489
  stdout.on("error", (error) => this.onerror?.(error));
@@ -392,6 +492,14 @@ var ProcessTransport = class {
392
492
  }
393
493
  send(message) {
394
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
+ }
395
503
  return new Promise((resolve, reject) => {
396
504
  const { stdin } = this.process;
397
505
  const done = (error) => error ? reject(error) : void 0;
@@ -423,6 +531,7 @@ var ProcessTransport = class {
423
531
  if (this.closed) return;
424
532
  this.closed = true;
425
533
  this.buffer.clear();
534
+ this.responseBounds.clear();
426
535
  this.onclose?.();
427
536
  }
428
537
  };
@@ -473,6 +582,16 @@ function createConnections(deps) {
473
582
  const starting = /* @__PURE__ */ new Set();
474
583
  const receipts = /* @__PURE__ */ new Set();
475
584
  const pendingStops = /* @__PURE__ */ new Map();
585
+ const cleanupOwners = /* @__PURE__ */ new Map();
586
+ const collections = /* @__PURE__ */ new Set();
587
+ const changed = (id) => {
588
+ let held = false;
589
+ for (const batch of collections) if (batch.ids.has(id)) {
590
+ held = true;
591
+ batch.dirty.add(id);
592
+ }
593
+ if (!held) deps.onChanged(id);
594
+ };
476
595
  let shuttingDown;
477
596
  const track = (work) => {
478
597
  running.add(work);
@@ -497,6 +616,7 @@ function createConnections(deps) {
497
616
  if (!found) {
498
617
  found = {
499
618
  id,
619
+ pending: /* @__PURE__ */ new Set(),
500
620
  gen: 0,
501
621
  status: { state: "disabled" },
502
622
  attempts: 0,
@@ -510,7 +630,7 @@ function createConnections(deps) {
510
630
  };
511
631
  const setStatus = (conn, status) => {
512
632
  conn.status = status;
513
- deps.onChanged();
633
+ changed(conn.id);
514
634
  };
515
635
  const clearTimers = (conn) => {
516
636
  if (conn.retry) clearTimeout(conn.retry);
@@ -768,10 +888,14 @@ function createConnections(deps) {
768
888
  const next = await list(client, live.capabilities, { timeout: timing.handshakeMs }, kind, conn.snapshot);
769
889
  if (conn.live?.client !== client || conn.gen !== gen) return;
770
890
  publish(conn, next);
771
- deps.onChanged();
891
+ changed(conn.id);
772
892
  } catch (error) {
773
893
  if (closed || conn.gen !== gen) return;
774
- deps.log.warn(`refreshing ${kind} of MCP server ${conn.id} failed: ${redact(messageOf$1(error), secrets())}`);
894
+ deps.log.emit({
895
+ level: "warn",
896
+ event: "plugin.event",
897
+ fields: { localCode: "REFRESHING" }
898
+ });
775
899
  }
776
900
  });
777
901
  };
@@ -780,7 +904,12 @@ function createConnections(deps) {
780
904
  client.setNotificationHandler(PromptListChangedNotificationSchema, refresh("prompts"));
781
905
  };
782
906
  /** One connection attempt within generation `gen`, tracked for shutdown. */
783
- const attempt = (conn, gen) => track(attemptOnce(conn, gen));
907
+ const attempt = (conn, gen) => {
908
+ const work = track(attemptOnce(conn, gen));
909
+ conn.pending.add(work);
910
+ work.finally(() => conn.pending.delete(work)).catch(() => {});
911
+ return work;
912
+ };
784
913
  const attemptOnce = async (conn, gen) => {
785
914
  if (closed || conn.gen !== gen) return;
786
915
  const record = deps.store.server(conn.id);
@@ -867,6 +996,7 @@ function createConnections(deps) {
867
996
  const reconcile = (id, options = {}) => {
868
997
  if (closed) return;
869
998
  const conn = connection(id);
999
+ cleanupOwners.set(id, conn);
870
1000
  conn.gen += 1;
871
1001
  conn.attempts = 0;
872
1002
  conn.connected = false;
@@ -876,7 +1006,7 @@ function createConnections(deps) {
876
1006
  if (!record) {
877
1007
  withdraw(conn);
878
1008
  connections.delete(id);
879
- deps.onChanged();
1009
+ changed(conn.id);
880
1010
  return;
881
1011
  }
882
1012
  if (!record.enabled) {
@@ -946,7 +1076,7 @@ function createConnections(deps) {
946
1076
  reason: "the connection changed during testing"
947
1077
  };
948
1078
  publish(conn, snapshot);
949
- deps.onChanged();
1079
+ changed(conn.id);
950
1080
  return count(snapshot);
951
1081
  } catch (error) {
952
1082
  const reason = redactReason(messageOf$1(error), live.secrets);
@@ -1022,6 +1152,56 @@ function createConnections(deps) {
1022
1152
  for (const record of deps.store.servers()) reconcile(record.id);
1023
1153
  },
1024
1154
  reconcile,
1155
+ /** Defers only these servers' notifications, leaving other lifecycle events independent. */
1156
+ async collection(ids, work, publish = true) {
1157
+ const context = {
1158
+ ids: new Set(ids),
1159
+ dirty: /* @__PURE__ */ new Set(),
1160
+ publish
1161
+ };
1162
+ collections.add(context);
1163
+ try {
1164
+ return await work();
1165
+ } finally {
1166
+ collections.delete(context);
1167
+ if (publish && context.dirty.size) deps.onChanged(context.dirty.values().next().value);
1168
+ }
1169
+ },
1170
+ /** Joins actual superseded resources; failed handles stay owned for cleanup retry. */
1171
+ async cleanup(id) {
1172
+ const conn = cleanupOwners.get(id) ?? connections.get(id);
1173
+ if (!conn) return {
1174
+ id,
1175
+ state: "completed"
1176
+ };
1177
+ const failures = [];
1178
+ if (conn.pending.size && (!deps.store.server(id) || !deps.store.server(id).enabled) && conn.lastReceipt) try {
1179
+ await conn.lastReceipt.stop();
1180
+ } catch (error) {
1181
+ failures.push(error);
1182
+ }
1183
+ await Promise.allSettled([...conn.pending]);
1184
+ for (const [transport, owner] of [...pendingStops]) if (owner === conn) try {
1185
+ await stopTransport(transport, conn);
1186
+ } catch (error) {
1187
+ failures.push(error);
1188
+ }
1189
+ if (conn.failedStart) try {
1190
+ await conn.failedStart.stop();
1191
+ } catch (error) {
1192
+ failures.push(error);
1193
+ }
1194
+ if (failures.length) return {
1195
+ id,
1196
+ state: "failed",
1197
+ reason: "cleanup-failed"
1198
+ };
1199
+ cleanupOwners.delete(id);
1200
+ return {
1201
+ id,
1202
+ state: "completed"
1203
+ };
1204
+ },
1025
1205
  status(id) {
1026
1206
  return connections.get(id)?.status ?? { state: "disabled" };
1027
1207
  },
@@ -1096,6 +1276,122 @@ function createConnections(deps) {
1096
1276
  };
1097
1277
  }
1098
1278
  //#endregion
1279
+ //#region src/batch.ts
1280
+ /** Owner-local bounded collection schemas and safe member settlement. */
1281
+ /** Stable safe error facts; decrypted server credentials never enter this shape. */
1282
+ const MemberError = z.strictObject({
1283
+ code: z.string().max(64),
1284
+ message: z.string().max(512)
1285
+ });
1286
+ /** Declared encoded query capacities, independent of collection/page sizes. */
1287
+ const queryBudgets = {
1288
+ maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
1289
+ maxTotalBytes: z.number().int().min(1).max(8388608).default(8388608)
1290
+ };
1291
+ /** Validates complete input bytes and all declared capacities before any owner IO. */
1292
+ function batchInput(shape, key) {
1293
+ return z.strictObject(shape).superRefine((value, context) => {
1294
+ const input = value;
1295
+ if (Buffer.byteLength(JSON.stringify(value)) > 8388608) context.addIssue({
1296
+ code: "custom",
1297
+ message: "batch input exceeds 8 MiB"
1298
+ });
1299
+ const items = input[key];
1300
+ if (Array.isArray(items) && typeof input.maxItemBytes === "number" && typeof input.maxTotalBytes === "number" && items.length * input.maxItemBytes + 8192 > input.maxTotalBytes) context.addIssue({
1301
+ code: "custom",
1302
+ message: "declared member budgets exceed total budget"
1303
+ });
1304
+ });
1305
+ }
1306
+ /** Publishes an ordered result only with the explicit nonsensitive target projection. */
1307
+ function batchResult(value, target) {
1308
+ const identity = {
1309
+ index: z.number().int().nonnegative(),
1310
+ target
1311
+ };
1312
+ return z.strictObject({ results: z.array(z.discriminatedUnion("ok", [z.strictObject({
1313
+ ...identity,
1314
+ ok: z.literal(true),
1315
+ value
1316
+ }), z.strictObject({
1317
+ ...identity,
1318
+ ok: z.literal(false),
1319
+ error: MemberError
1320
+ })])) });
1321
+ }
1322
+ /** Keeps committed business facts immutable while reflecting uncertain or retained cleanup. */
1323
+ function operationResult(value) {
1324
+ return z.discriminatedUnion("operationState", [
1325
+ z.strictObject({
1326
+ operationState: z.literal("committed"),
1327
+ operationId: z.uuid(),
1328
+ value
1329
+ }),
1330
+ z.strictObject({
1331
+ operationState: z.literal("admitted"),
1332
+ operationId: z.uuid(),
1333
+ uncertain: z.literal(true)
1334
+ }),
1335
+ z.strictObject({
1336
+ operationState: z.literal("cleanup-pending"),
1337
+ operationId: z.uuid(),
1338
+ value,
1339
+ cleanup: z.array(MemberError)
1340
+ })
1341
+ ]);
1342
+ }
1343
+ /** Settles every target in order and enforces complete encoded member and aggregate sizes. */
1344
+ async function settle(targets, work, limits, failure) {
1345
+ const results = [];
1346
+ let bytes = 8192;
1347
+ for (const [index, target] of targets.entries()) try {
1348
+ const item = {
1349
+ index,
1350
+ target,
1351
+ ok: true,
1352
+ value: await work(target, index)
1353
+ };
1354
+ const size = Buffer.byteLength(JSON.stringify(item));
1355
+ if (size > (limits?.maxItemBytes ?? 8388608) || bytes + size > (limits?.maxTotalBytes ?? 8388608)) throw Object.assign(/* @__PURE__ */ new Error("encoded member exceeds declared budget"), { code: "read-limit" });
1356
+ results.push(item);
1357
+ bytes += size;
1358
+ } catch (error) {
1359
+ const item = {
1360
+ index,
1361
+ target,
1362
+ ok: false,
1363
+ error: {
1364
+ code: error instanceof Error && "code" in error && typeof error.code === "string" ? error.code.slice(0, 64) : "operation-failed",
1365
+ message: (failure?.(error, target) ?? (error instanceof Error ? error.message : "Operation failed")).slice(0, 512)
1366
+ }
1367
+ };
1368
+ results.push(item);
1369
+ bytes += Buffer.byteLength(JSON.stringify(item));
1370
+ }
1371
+ return { results };
1372
+ }
1373
+ /** Complete resource declarations reserve raw bytes and worst encoded protocol/output capacity. */
1374
+ function resourceInput(extra, member) {
1375
+ return batchInput({
1376
+ ...extra,
1377
+ items: z.array(member).min(1).max(32),
1378
+ maxTotalBytes: z.number().int().min(1).max(4194304).default(4194304)
1379
+ }, "items").superRefine((input, context) => {
1380
+ const declared = input;
1381
+ const items = declared.items;
1382
+ const raw = items.reduce((sum, item) => sum + item.maxBytes, 0);
1383
+ const encoded = items.reduce((sum, item) => sum + Math.max(6 * item.maxBytes, 4 * Math.ceil(item.maxBytes / 3)) + Math.max(65536, Buffer.byteLength(JSON.stringify(item)) + 1024), 8192);
1384
+ if (raw > Number(declared.maxTotalBytes)) context.addIssue({
1385
+ code: "custom",
1386
+ message: "declared raw member budgets exceed total budget"
1387
+ });
1388
+ if (encoded > 8388608) context.addIssue({
1389
+ code: "custom",
1390
+ message: "declared encoded resource budgets exceed 8 MiB"
1391
+ });
1392
+ });
1393
+ }
1394
+ //#endregion
1099
1395
  //#region src/management.ts
1100
1396
  /**
1101
1397
  * Validates and saves one server, optionally selecting a new one for an agent.
@@ -1148,12 +1444,578 @@ async function saveServer(deps, input, selectFor, ctx) {
1148
1444
  if (selectFor?.selected) deps.selectionChanged(selectFor.agentId);
1149
1445
  return record;
1150
1446
  }
1151
- /** Changes one agent's selection while leaving the global server state intact. */
1152
- function selectServer(deps, agentId, serverId, selected, ctx) {
1153
- if (!deps.store.server(serverId)) throw new Error("no such MCP server");
1154
- deps.agentConfig.save([agentId], () => deps.store.setServerSelected(agentId, serverId, selected), ctx);
1155
- deps.selectionChanged(agentId);
1156
- deps.announce();
1447
+ //#endregion
1448
+ //#region src/output-schema.ts
1449
+ /** Validates complete owner business results and bounded recoverable delivery failures. */
1450
+ /** Adds the standard failure envelope and bounded text refusals to an owner's result schema. */
1451
+ function toolOutputSchema(body, input, name) {
1452
+ return z.union([
1453
+ body,
1454
+ z.strictObject({
1455
+ ok: z.literal(false),
1456
+ error: z.strictObject({
1457
+ code: z.string().min(1).max(128),
1458
+ message: z.string().refine((value) => [...value].length <= 256).meta({ maxLength: 256 }),
1459
+ retryable: z.boolean(),
1460
+ field: z.string().max(256).optional(),
1461
+ maximum: z.number().finite().optional()
1462
+ }),
1463
+ next: z.strictObject({
1464
+ tool: z.literal(name),
1465
+ arguments: input
1466
+ }).nullable(),
1467
+ execution: z.strictObject({ state: z.enum([
1468
+ "not-started",
1469
+ "committed",
1470
+ "unknown"
1471
+ ]) }).optional()
1472
+ }),
1473
+ z.string().max(1024)
1474
+ ]);
1475
+ }
1476
+ //#endregion
1477
+ //#region src/cursor-cache.ts
1478
+ const bytesOf = (value) => 2048 + 2 * (value.content?.length ?? 0);
1479
+ /** Owns metadata snapshots; each query and all successor positions share one opaque host lease. */
1480
+ var QueryCursorCache = class extends Map {
1481
+ pending = /* @__PURE__ */ new Map();
1482
+ roots = /* @__PURE__ */ new Map();
1483
+ resources;
1484
+ facts;
1485
+ timer;
1486
+ /** Measures only retained metadata; source IO uses a separate bounded reservation. */
1487
+ constructor(facts, resources) {
1488
+ super();
1489
+ this.facts = facts;
1490
+ this.resources = resources;
1491
+ }
1492
+ retained(root) {
1493
+ let bytes = 0;
1494
+ for (const state of this.values()) if (this.facts(state).initial === root.initial) bytes += bytesOf(this.facts(state));
1495
+ return bytes;
1496
+ }
1497
+ total(root) {
1498
+ return 2048 + 2 * JSON.stringify(root.initial).length + this.retained(root) + root.ioBytes + root.pendingBytes;
1499
+ }
1500
+ settle(root) {
1501
+ if (root.released) return;
1502
+ if (root.active === 0 && this.retained(root) === 0) {
1503
+ root.released = true;
1504
+ root.closing = true;
1505
+ this.roots.delete(root.initial);
1506
+ root.lease.close("completed");
1507
+ if (!this.roots.size && this.timer) {
1508
+ clearInterval(this.timer);
1509
+ this.timer = void 0;
1510
+ }
1511
+ return;
1512
+ }
1513
+ const released = root.heldBytes - this.total(root);
1514
+ if (released > 0) {
1515
+ root.lease.reduce({
1516
+ bytes: released,
1517
+ scratchBytes: 0
1518
+ });
1519
+ root.heldBytes -= released;
1520
+ }
1521
+ if (root.active === 0 && this.retained(root) > 0) root.lease.retain({
1522
+ reason: "public-cursor",
1523
+ idleMs: 6e5,
1524
+ maxAgeMs: 36e5
1525
+ });
1526
+ }
1527
+ invalidate(root) {
1528
+ if (root.released) return;
1529
+ root.closing = true;
1530
+ for (const [key, state] of this) if (this.facts(state).initial === root.initial) super.delete(key);
1531
+ root.pendingBytes = 0;
1532
+ root.lease.close("abandoned");
1533
+ }
1534
+ async enter(call, initial, sourceBytes) {
1535
+ const now = performance.now();
1536
+ for (const root of this.roots.values()) if (now - root.used > 6e5 || now - root.created > 36e5) this.invalidate(root);
1537
+ let root = this.roots.get(initial);
1538
+ if (root?.closing || root?.lease.signal.aborted) throw new Error("cursor_invalid");
1539
+ if (!root) {
1540
+ const resources = this.resources;
1541
+ if (!resources) throw new Error("query_resources_unavailable");
1542
+ const initialBytes = sourceBytes + 2048 + 2 * JSON.stringify(initial).length;
1543
+ root = {
1544
+ initial,
1545
+ lease: await resources.reserve(call, {
1546
+ bytes: sourceBytes + 2048 + 2 * JSON.stringify(initial).length,
1547
+ scratchBytes: 0,
1548
+ cleanup: async () => {
1549
+ const current = this.roots.get(initial);
1550
+ for (const [id, value] of this) if (this.facts(value).initial === initial) super.delete(id);
1551
+ if (current) {
1552
+ current.released = true;
1553
+ current.closing = true;
1554
+ this.roots.delete(initial);
1555
+ }
1556
+ return { status: "complete" };
1557
+ }
1558
+ }),
1559
+ created: now,
1560
+ used: now,
1561
+ active: 0,
1562
+ ioBytes: 0,
1563
+ pendingBytes: 0,
1564
+ closing: false,
1565
+ released: false,
1566
+ heldBytes: initialBytes,
1567
+ call
1568
+ };
1569
+ this.roots.set(initial, root);
1570
+ this.timer ??= setInterval(() => {
1571
+ const current = performance.now();
1572
+ for (const candidate of this.roots.values()) if (current - candidate.used > 6e5 || current - candidate.created > 36e5) this.invalidate(candidate);
1573
+ }, 6e4);
1574
+ this.timer.unref();
1575
+ }
1576
+ root.lease.signal.throwIfAborted();
1577
+ root.call = call;
1578
+ const additional = this.total(root) + sourceBytes - root.heldBytes;
1579
+ if (additional > 0) {
1580
+ await root.lease.grow(call, {
1581
+ bytes: additional,
1582
+ scratchBytes: 0
1583
+ });
1584
+ root.heldBytes += additional;
1585
+ }
1586
+ root.active++;
1587
+ root.ioBytes += sourceBytes;
1588
+ root.used = now;
1589
+ let finished = false;
1590
+ return () => {
1591
+ if (finished) return;
1592
+ finished = true;
1593
+ root.active--;
1594
+ root.ioBytes -= sourceBytes;
1595
+ root.pendingBytes = 0;
1596
+ this.settle(root);
1597
+ };
1598
+ }
1599
+ /** Runs source acquisition under the actual authenticated call, releasing only after its cleanup. */
1600
+ async runExclusive(input, call, action, sourceBytes = 4194304) {
1601
+ const cursor = typeof input === "object" && input !== null && "cursor" in input ? input.cursor : void 0;
1602
+ const saved = cursor === void 0 ? void 0 : this.get(cursor);
1603
+ if (cursor !== void 0 && saved === void 0) return action();
1604
+ const initial = saved === void 0 ? input : this.facts(saved).initial;
1605
+ const existing = this.roots.get(initial);
1606
+ if (existing && (existing.call.sessionId !== call.sessionId || JSON.stringify(existing.call.address) !== JSON.stringify(call.address) || existing.call.historyGeneration !== call.historyGeneration)) return action();
1607
+ let finish;
1608
+ try {
1609
+ finish = await this.enter(call, initial, sourceBytes);
1610
+ return await this.roots.get(initial).lease.withUse(call, action);
1611
+ } catch (error) {
1612
+ if (this.resources?.isAdmissionFailure(error)) throw error;
1613
+ if (!(error instanceof Error) || ![
1614
+ "query_limit_exceeded",
1615
+ "query_resources_unavailable",
1616
+ "cursor_invalid"
1617
+ ].includes(error.message)) throw error;
1618
+ return {
1619
+ content: JSON.stringify({
1620
+ ok: false,
1621
+ error: {
1622
+ code: error.message,
1623
+ message: "Shared query capacity or authority is unavailable; restart after releasing older queries.",
1624
+ retryable: false
1625
+ },
1626
+ next: null
1627
+ }),
1628
+ isError: true
1629
+ };
1630
+ } finally {
1631
+ finish?.();
1632
+ }
1633
+ }
1634
+ /** Joins same-cursor preparation before revalidating and replaying its accepted exact page. */
1635
+ async run(input, call, action, sourceBytes = 4194304) {
1636
+ const cursor = typeof input === "object" && input !== null && "cursor" in input ? input.cursor : void 0;
1637
+ if (cursor === void 0) return this.runExclusive(input, call, action, sourceBytes);
1638
+ const previous = this.pending.get(cursor);
1639
+ let unlock;
1640
+ const gate = new Promise((resolve) => {
1641
+ unlock = resolve;
1642
+ });
1643
+ this.pending.set(cursor, gate);
1644
+ try {
1645
+ await previous;
1646
+ call.signal.throwIfAborted();
1647
+ return await this.runExclusive(input, call, action, sourceBytes);
1648
+ } finally {
1649
+ unlock();
1650
+ if (this.pending.get(cursor) === gate) this.pending.delete(cursor);
1651
+ }
1652
+ }
1653
+ /** Applies the same resource lifecycle to a native model-tool registration. */
1654
+ wrap(tool, sourceBytes = 4194304) {
1655
+ const execute = tool.execute;
1656
+ return {
1657
+ ...tool,
1658
+ execute: (input, call) => this.run(input, call, async () => await execute(input, call), sourceBytes)
1659
+ };
1660
+ }
1661
+ /** Accounts an exact candidate before accepting or retaining its snapshot. */
1662
+ async prepare(initial, content) {
1663
+ const root = this.roots.get(initial);
1664
+ if (!root || root.closing) throw new Error("cursor_invalid");
1665
+ root.lease.signal.throwIfAborted();
1666
+ const bytes = 2048 + 2 * content.length;
1667
+ const additional = this.total(root) - root.pendingBytes + bytes - root.heldBytes;
1668
+ if (additional > 0) {
1669
+ await root.lease.grow(root.call, {
1670
+ bytes: additional,
1671
+ scratchBytes: 0
1672
+ });
1673
+ root.heldBytes += additional;
1674
+ }
1675
+ root.pendingBytes = bytes;
1676
+ }
1677
+ /** Awaits metadata admission before installing a new cursor. */
1678
+ async save(key, value) {
1679
+ const root = this.roots.get(this.facts(value).initial);
1680
+ if (!root || root.closing) throw new Error("cursor_invalid");
1681
+ root.lease.signal.throwIfAborted();
1682
+ const old = super.get(key);
1683
+ const required = this.total(root) + bytesOf(this.facts(value)) - (old === void 0 ? 0 : bytesOf(this.facts(old)));
1684
+ if (required > root.heldBytes) {
1685
+ const bytes = required - root.heldBytes;
1686
+ await root.lease.grow(root.call, {
1687
+ bytes,
1688
+ scratchBytes: 0
1689
+ });
1690
+ root.heldBytes += bytes;
1691
+ }
1692
+ super.set(key, value);
1693
+ return this;
1694
+ }
1695
+ delete(key) {
1696
+ const value = super.get(key), deleted = super.delete(key);
1697
+ if (value !== void 0) {
1698
+ const root = this.roots.get(this.facts(value).initial);
1699
+ if (root) this.settle(root);
1700
+ }
1701
+ return deleted;
1702
+ }
1703
+ /** Drops retained metadata before releasing its shared reservation. */
1704
+ clear() {
1705
+ for (const root of [...this.roots.values()]) this.invalidate(root);
1706
+ }
1707
+ };
1708
+ /** Applies a tighter owner-local memory ceiling while preserving shared resident accounting. */
1709
+ function trimCursorCache(entries, retained) {
1710
+ let bytes = 0;
1711
+ for (const entry of entries.values()) bytes += bytesOf(retained(entry));
1712
+ while (bytes > 8388608 || entries.size > 1024) {
1713
+ const oldest = entries.entries().next().value;
1714
+ if (!oldest) break;
1715
+ bytes -= bytesOf(retained(oldest[1]));
1716
+ entries.delete(oldest[0]);
1717
+ }
1718
+ }
1719
+ //#endregion
1720
+ //#region src/server-pages.ts
1721
+ /** Header-only server pages and explicit bounded safe-detail fragments. */
1722
+ const Tokens = z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional().describe("Desired delivery tokens; the host may allocate fewer.");
1723
+ const Query = z.union([z.strictObject({ all: z.literal(true).describe("List configured server headers without configuration bodies.") }), z.strictObject({ serverIds: z.array(z.uuid().describe("Exact selected MCP server id.")).min(1).max(64).describe("Selected server ids whose summaries are needed; unknown or unselected members refuse this query.") })]);
1724
+ const Start = z.union([z.strictObject({
1725
+ queries: z.array(Query).min(1).max(64).describe("Ordered directory queries; limit and tokens are shared by the whole page."),
1726
+ view: z.literal("summary").default("summary").describe("Header summaries only; default summary, no configuration bodies."),
1727
+ limit: z.number().int().min(1).max(100).default(50).describe("Maximum total server headers on this page; default 50, hard maximum 100."),
1728
+ outputTokens: Tokens
1729
+ }), z.strictObject({
1730
+ queries: z.tuple([z.strictObject({ serverIds: z.tuple([z.uuid()]).describe("Exactly one selected server id for safe configuration details.") })]).describe("Exactly one query containing exactly one selected server id."),
1731
+ view: z.literal("details").describe("Safe configuration fragments for exactly one selected server."),
1732
+ outputTokens: Tokens
1733
+ })]);
1734
+ const Continue = z.strictObject({
1735
+ cursor: z.string().min(1).max(512).regex(/^[\x21-\x7e]+$/).describe("Opaque continuation; copy next.arguments without changing queries or view."),
1736
+ outputTokens: Tokens
1737
+ });
1738
+ const Input = z.union([Start, Continue]);
1739
+ const Header = z.strictObject({
1740
+ id: z.string(),
1741
+ slug: z.string(),
1742
+ name: z.string(),
1743
+ transport: z.enum(["stdio", "http"]),
1744
+ enabled: z.boolean(),
1745
+ selected: z.boolean(),
1746
+ connectionState: z.string()
1747
+ });
1748
+ const Next = z.strictObject({
1749
+ tool: z.literal("mcp_server_list"),
1750
+ arguments: Continue
1751
+ });
1752
+ const Output = z.strictObject({
1753
+ ok: z.literal(true),
1754
+ complete: z.boolean(),
1755
+ results: z.array(z.union([z.strictObject({
1756
+ index: z.number().int().nonnegative(),
1757
+ ok: z.literal(true),
1758
+ complete: z.boolean(),
1759
+ value: z.union([z.array(Header), z.strictObject({
1760
+ serverId: z.string(),
1761
+ field: z.literal("details"),
1762
+ text: z.string(),
1763
+ range: z.strictObject({
1764
+ offset: z.number(),
1765
+ length: z.number(),
1766
+ complete: z.boolean()
1767
+ })
1768
+ })])
1769
+ }), z.strictObject({
1770
+ index: z.number().int().nonnegative(),
1771
+ ok: z.literal(false),
1772
+ complete: z.literal(true),
1773
+ error: z.strictObject({
1774
+ code: z.string(),
1775
+ message: z.string().refine((value) => [...value].length <= 256).meta({ maxLength: 256 })
1776
+ })
1777
+ })])),
1778
+ next: Next.nullable(),
1779
+ effective: z.strictObject({
1780
+ limit: z.number(),
1781
+ outputTokens: z.number()
1782
+ })
1783
+ });
1784
+ /** Builds exact pages over native headers; a details call opens only one selected configuration. */
1785
+ function serverPages(deps) {
1786
+ const cursors = new QueryCursorCache((state) => ({
1787
+ initial: state.position.initial,
1788
+ content: state.result && "content" in state.result ? state.result.content : void 0
1789
+ }), deps.resources);
1790
+ const sourceVersion = () => {
1791
+ const hash = createHash("sha256").update(String(deps.store.directoryVersion()));
1792
+ for (const secret of [...deps.secrets()].sort()) hash.update(JSON.stringify(secret));
1793
+ return hash.digest("hex");
1794
+ };
1795
+ const failure = (code, message, next = null) => ({
1796
+ content: JSON.stringify({
1797
+ ok: false,
1798
+ error: {
1799
+ code,
1800
+ message,
1801
+ retryable: next !== null
1802
+ },
1803
+ next
1804
+ }),
1805
+ isError: true
1806
+ });
1807
+ return cursors.wrap({
1808
+ name: "mcp_server_list",
1809
+ preload: false,
1810
+ description: "Read bounded MCP server summaries by default. view=details accepts exactly one selected server id and pages its safe configuration. Follow next.arguments; complete tool definitions use tool_search.",
1811
+ inputSchema: Input,
1812
+ outputSchema: toolOutputSchema(Output, Input, "mcp_server_list"),
1813
+ deliveryKind: "exact-page",
1814
+ async execute(input, call) {
1815
+ call.signal.throwIfAborted();
1816
+ const now = performance.now(), address = JSON.stringify(call.address), saved = "cursor" in input ? cursors.get(input.cursor) : void 0;
1817
+ if ("cursor" in input && !saved) return failure("cursor_invalid", "Unknown server cursor.");
1818
+ if (saved && (saved.session !== call.sessionId || saved.address !== address || saved.generation !== call.historyGeneration)) return failure("cursor_invalid", "Cursor does not belong to this effective session.");
1819
+ if (saved && (now - saved.used > 6e5 || now - saved.created > 36e5)) return failure("cursor_expired", "Start the server query again.", {
1820
+ tool: "mcp_server_list",
1821
+ arguments: saved.position.initial
1822
+ });
1823
+ const p = saved?.position ?? {
1824
+ initial: input,
1825
+ index: 0,
1826
+ offset: 0,
1827
+ version: sourceVersion()
1828
+ };
1829
+ if (p.version !== sourceVersion()) return failure("source_changed", "Server catalogue changed; start again.", {
1830
+ tool: "mcp_server_list",
1831
+ arguments: p.initial
1832
+ });
1833
+ if (saved?.result) {
1834
+ const cost = call.output.measure(saved.result);
1835
+ if (cost > call.output.outputTokens) return failure("page_too_small", "The saved exact server page needs a larger independent allocation.", cost <= call.output.maximumTokens ? {
1836
+ tool: "mcp_server_list",
1837
+ arguments: {
1838
+ ...input,
1839
+ outputTokens: cost
1840
+ }
1841
+ } : null);
1842
+ call.output.acceptExact(saved.result);
1843
+ saved.used = now;
1844
+ return saved.result;
1845
+ }
1846
+ const limit = p.initial.view === "summary" ? p.initial.limit : 1, cursor = randomUUID(), query = p.initial.queries[p.index], last = p.index === p.initial.queries.length - 1;
1847
+ let following, result;
1848
+ const build = (row, complete) => ({ content: JSON.stringify({
1849
+ ok: true,
1850
+ complete: complete && last,
1851
+ results: [row],
1852
+ next: complete && last ? null : {
1853
+ tool: "mcp_server_list",
1854
+ arguments: { cursor }
1855
+ },
1856
+ effective: {
1857
+ limit,
1858
+ outputTokens: call.output.outputTokens
1859
+ }
1860
+ }) });
1861
+ try {
1862
+ if (p.initial.view === "details") {
1863
+ const id = p.initial.queries[0].serverIds[0], window = unicodeWindow(JSON.stringify(deps.details(id, call)), p.offset, Math.min(32768, Math.max(1, call.output.outputTokens * 4))), remaining = window.points;
1864
+ let length = Math.min(remaining.length, call.output.outputTokens * 4);
1865
+ const make = (n) => build({
1866
+ index: 0,
1867
+ ok: true,
1868
+ complete: window.complete && n === remaining.length,
1869
+ value: {
1870
+ serverId: id,
1871
+ field: "details",
1872
+ text: remaining.slice(0, n).join(""),
1873
+ range: {
1874
+ offset: p.offset,
1875
+ length: n,
1876
+ complete: window.complete && n === remaining.length
1877
+ }
1878
+ }
1879
+ }, window.complete && n === remaining.length);
1880
+ result = make(length);
1881
+ if (call.output.measure(result) > call.output.outputTokens) {
1882
+ let low = 0, high = length;
1883
+ while (low < high) {
1884
+ const mid = Math.ceil((low + high) / 2);
1885
+ if (call.output.measure(make(mid)) <= call.output.outputTokens) low = mid;
1886
+ else high = mid - 1;
1887
+ }
1888
+ length = low;
1889
+ result = make(length);
1890
+ }
1891
+ if (length === 0 && remaining.length > 0) return failure("page_too_small", "Detail metadata does not fit this allowance.");
1892
+ if (!window.complete || length < remaining.length) following = {
1893
+ ...p,
1894
+ offset: p.offset + length
1895
+ };
1896
+ } else {
1897
+ const ids = "serverIds" in query ? query.serverIds : void 0;
1898
+ if (ids && !p.after && deps.store.headerPage(call.address.agentId, void 0, 100, ids).items.length !== new Set(ids).size) throw Object.assign(/* @__PURE__ */ new Error("One or more servers are unavailable to this agent."), { code: "not-found" });
1899
+ const page = deps.store.headerPage(call.address.agentId, p.after, limit, ids), secrets = deps.secrets(), items = page.items.map((item) => ({
1900
+ ...item,
1901
+ name: redact(item.name, secrets),
1902
+ slug: redact(item.slug, secrets),
1903
+ connectionState: deps.state(item.id)
1904
+ }));
1905
+ let count = items.length;
1906
+ const make = (n) => build({
1907
+ index: p.index,
1908
+ ok: true,
1909
+ complete: page.complete && n === items.length,
1910
+ value: items.slice(0, n)
1911
+ }, page.complete && n === items.length);
1912
+ result = make(count);
1913
+ if (count > 0 && call.output.measure(result) > call.output.outputTokens) {
1914
+ let low = 1;
1915
+ let high = count - 1;
1916
+ count = 0;
1917
+ while (low + 4 <= high) {
1918
+ await setImmediate();
1919
+ call.signal.throwIfAborted();
1920
+ const candidateCount = Math.floor((low + high) / 2);
1921
+ const candidate = make(candidateCount);
1922
+ if (call.output.measure(candidate) <= call.output.outputTokens) {
1923
+ count = candidateCount;
1924
+ result = candidate;
1925
+ low = candidateCount + 1;
1926
+ } else high = candidateCount - 1;
1927
+ }
1928
+ for (let candidateCount = high; candidateCount >= low; candidateCount -= 1) {
1929
+ await setImmediate();
1930
+ call.signal.throwIfAborted();
1931
+ const candidate = make(candidateCount);
1932
+ if (call.output.measure(candidate) <= call.output.outputTokens) {
1933
+ count = candidateCount;
1934
+ result = candidate;
1935
+ break;
1936
+ }
1937
+ }
1938
+ }
1939
+ if (count === 0 && items.length > 0) return failure("page_too_small", "One server summary does not fit this allowance.");
1940
+ if (!(page.complete && count === items.length)) following = {
1941
+ ...p,
1942
+ after: items[count - 1].id
1943
+ };
1944
+ else if (!last) following = {
1945
+ ...p,
1946
+ index: p.index + 1,
1947
+ after: void 0
1948
+ };
1949
+ }
1950
+ } catch (error) {
1951
+ call.signal.throwIfAborted();
1952
+ result = build({
1953
+ index: p.index,
1954
+ ok: false,
1955
+ complete: true,
1956
+ error: {
1957
+ code: error.code ?? "source_unavailable",
1958
+ message: "Server query is unavailable to this agent."
1959
+ }
1960
+ }, true);
1961
+ if (!last) following = {
1962
+ ...p,
1963
+ index: p.index + 1,
1964
+ after: void 0,
1965
+ offset: 0
1966
+ };
1967
+ }
1968
+ if (call.output.measure(result) > call.output.outputTokens) return failure("page_too_small", "Server page metadata does not fit this allowance.");
1969
+ await cursors.prepare(p.initial, result.content);
1970
+ call.output.acceptExact(result);
1971
+ if (following) {
1972
+ for (const [key, state] of cursors) if (now - state.created > 36e5 || state.session === call.sessionId && state.generation !== call.historyGeneration) cursors.delete(key);
1973
+ while (cursors.size >= 4096) {
1974
+ const oldest = cursors.keys().next().value;
1975
+ if (oldest) cursors.delete(oldest);
1976
+ }
1977
+ await cursors.save(cursor, {
1978
+ position: following,
1979
+ session: call.sessionId,
1980
+ address,
1981
+ generation: call.historyGeneration,
1982
+ created: saved?.created ?? now,
1983
+ used: now
1984
+ });
1985
+ }
1986
+ if (saved) {
1987
+ saved.result = result;
1988
+ trimCursorCache(cursors, (state) => ({
1989
+ initial: state.position.initial,
1990
+ content: state.result && "content" in state.result ? state.result.content : void 0
1991
+ }));
1992
+ saved.used = now;
1993
+ }
1994
+ trimCursorCache(cursors, (state) => ({
1995
+ initial: state.position.initial,
1996
+ content: state.result && "content" in state.result ? state.result.content : void 0
1997
+ }));
1998
+ return result;
1999
+ }
2000
+ });
2001
+ }
2002
+ /** Builds a bounded Unicode window without allocating an array for the complete source. */
2003
+ function unicodeWindow(text, offset, maximum) {
2004
+ let unit = 0, skipped = 0;
2005
+ while (unit < text.length && skipped < offset) {
2006
+ unit += text.codePointAt(unit) > 65535 ? 2 : 1;
2007
+ skipped++;
2008
+ }
2009
+ const points = [];
2010
+ while (unit < text.length && points.length < maximum) {
2011
+ const size = text.codePointAt(unit) > 65535 ? 2 : 1;
2012
+ points.push(text.slice(unit, unit + size));
2013
+ unit += size;
2014
+ }
2015
+ return {
2016
+ points,
2017
+ complete: unit === text.length
2018
+ };
1157
2019
  }
1158
2020
  //#endregion
1159
2021
  //#region src/tool-names.ts
@@ -1168,30 +2030,29 @@ const TOOL_NAMES = [
1168
2030
  //#region src/management-tools.ts
1169
2031
  /** Strict plugin configuration for individually disabling management tools. */
1170
2032
  const McpConfig = z.object({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).strict().default({ disabled: [] });
1171
- const ListInput = z.object({ serverId: z.string().uuid().optional() }).strict();
1172
2033
  /** One server's creation, `transport` paired with its own `config`. */
1173
2034
  const CreatePaired = z.discriminatedUnion("transport", [z.object({
1174
- slug: z.string(),
1175
- name: z.string().trim().min(1).max(80),
2035
+ slug: z.string().describe("Unique mapped-name prefix matching ^[a-z0-9][a-z0-9-]{0,23}$; cannot be changed after creation."),
2036
+ name: z.string().trim().min(1).max(80).describe("Server display name, 1–80 UTF-16 code units after trimming."),
1176
2037
  transport: z.literal("stdio"),
1177
2038
  config: StdioConfigSchema,
1178
- select: z.boolean().default(true)
2039
+ select: z.boolean().default(true).describe("Select the new server for this Agent after approval; default true.")
1179
2040
  }).strict(), z.object({
1180
- slug: z.string(),
1181
- name: z.string().trim().min(1).max(80),
2041
+ slug: z.string().describe("Unique mapped-name prefix matching ^[a-z0-9][a-z0-9-]{0,23}$; cannot be changed after creation."),
2042
+ name: z.string().trim().min(1).max(80).describe("Server display name, 1–80 UTF-16 code units after trimming."),
1182
2043
  transport: z.literal("http"),
1183
2044
  config: HttpConfigSchema,
1184
- select: z.boolean().default(true)
2045
+ select: z.boolean().default(true).describe("Select the new server for this Agent after approval; default true.")
1185
2046
  }).strict()]);
1186
2047
  /** The parameters as the model sees them: one object, because an
1187
2048
  * OpenAI-compatible endpoint refuses a tool whose top level is not
1188
2049
  * `type: "object"`. The pairing `CreatePaired` states is checked here. */
1189
2050
  const Create = z.object({
1190
- slug: z.string(),
1191
- name: z.string().trim().min(1).max(80),
1192
- transport: z.enum(["stdio", "http"]),
1193
- config: z.union([StdioConfigSchema, HttpConfigSchema]),
1194
- select: z.boolean().default(true)
2051
+ slug: z.string().describe("Unique mapped-name prefix matching ^[a-z0-9][a-z0-9-]{0,23}$; cannot be changed after creation."),
2052
+ name: z.string().trim().min(1).max(80).describe("Server display name, 1–80 UTF-16 code units after trimming."),
2053
+ transport: z.enum(["stdio", "http"]).describe("Transport paired with its matching config: local stdio command or remote HTTP endpoint."),
2054
+ config: z.union([StdioConfigSchema, HttpConfigSchema]).describe("Complete configuration matching transport; credentials are referenced by names, never included as plain values."),
2055
+ select: z.boolean().default(true).describe("Select the new server for this Agent after approval; default true.")
1195
2056
  }).strict().superRefine((value, ctx) => {
1196
2057
  if (!CreatePaired.safeParse(value).success) ctx.addIssue({
1197
2058
  code: "custom",
@@ -1200,15 +2061,46 @@ const Create = z.object({
1200
2061
  });
1201
2062
  });
1202
2063
  const Update = z.object({
1203
- serverId: z.string().uuid(),
1204
- name: z.string().trim().min(1).max(80).optional(),
1205
- config: z.union([StdioConfigSchema, HttpConfigSchema]).optional(),
1206
- expectedRevision: z.string().optional()
2064
+ serverId: z.string().uuid().describe("Exact configured MCP server UUID from mcp_server_list."),
2065
+ name: z.string().trim().min(1).max(80).optional().describe("Replacement display name, 1–80 UTF-16 code units after trimming; omit to retain."),
2066
+ config: z.union([StdioConfigSchema, HttpConfigSchema]).optional().describe("Complete replacement configuration matching the existing transport; omit to retain."),
2067
+ expectedRevision: z.string().optional().describe("Observed configuration revision; a mismatch refuses the update before writing.")
1207
2068
  }).strict().refine((value) => value.name !== void 0 || value.config !== void 0, "a change is required");
1208
2069
  const Select = z.object({
1209
- serverId: z.string().uuid(),
1210
- selected: z.boolean()
2070
+ serverId: z.string().uuid().describe("Exact configured MCP server UUID from mcp_server_list."),
2071
+ selected: z.boolean().describe("Whether this Agent selects the server after the approved change.")
1211
2072
  }).strict();
2073
+ const SelectInput = batchInput({
2074
+ operationId: z.uuid().describe("New UUID for this selection operation; reuse only when retrying the identical operation."),
2075
+ changes: z.array(Select).min(1).max(64).describe("Selection changes, 1–64 members under one approval and transaction.")
2076
+ }, "changes");
2077
+ const MutationOutput = z.strictObject({
2078
+ ok: z.literal(true),
2079
+ committed: z.literal(true),
2080
+ status: z.literal("ok"),
2081
+ data: z.union([
2082
+ z.strictObject({
2083
+ serverId: z.string(),
2084
+ selected: z.boolean(),
2085
+ summary: z.string().max(256)
2086
+ }),
2087
+ z.strictObject({
2088
+ serverId: z.string(),
2089
+ revision: z.string(),
2090
+ summary: z.string().max(256)
2091
+ }),
2092
+ z.strictObject({ summary: z.string().max(256) }),
2093
+ z.strictObject({
2094
+ operationId: z.uuid(),
2095
+ operationState: z.enum(["admitted", "committed"]),
2096
+ value: z.strictObject({
2097
+ serverIds: z.array(z.string()),
2098
+ revision: z.number(),
2099
+ contentHash: z.string()
2100
+ })
2101
+ })
2102
+ ])
2103
+ });
1212
2104
  const revisionOf = (record) => createHash("sha256").update(JSON.stringify(record)).digest("hex");
1213
2105
  const fail = (code, message) => {
1214
2106
  throw Object.assign(new Error(message), { code });
@@ -1229,7 +2121,17 @@ function registerMcpManagementTools(deps) {
1229
2121
  const secretsOf = (serverId) => {
1230
2122
  return secretValues([...credentials.list(serverId).filter((status) => status.set).map((status) => credentials.get(serverId, status.name)), ...oauth.secrets(serverId)]);
1231
2123
  };
1232
- const allSecrets = () => secretValues(store.servers().flatMap((record) => secretsOf(record.id)));
2124
+ const allSecrets = () => {
2125
+ const values = [];
2126
+ let after;
2127
+ while (true) {
2128
+ const page = store.headerPage("", after, 100);
2129
+ for (const row of page.items) values.push(...secretsOf(row.id));
2130
+ if (page.complete) break;
2131
+ after = page.items.at(-1).id;
2132
+ }
2133
+ return secretValues(values);
2134
+ };
1233
2135
  const sanitize = (value, secrets) => {
1234
2136
  if (typeof value === "string") return redact(value, secrets);
1235
2137
  if (Array.isArray(value)) return value.map((item) => sanitize(item, secrets));
@@ -1256,25 +2158,15 @@ function registerMcpManagementTools(deps) {
1256
2158
  return value !== null && typeof value === "object" && Object.values(value).some((item) => containsKnownSecret(item, secrets));
1257
2159
  };
1258
2160
  const readResult = (data) => ({ content: JSON.stringify({
2161
+ ok: true,
2162
+ committed: true,
1259
2163
  status: "ok",
1260
2164
  data
1261
2165
  }) });
1262
- const listServers = (agentId) => {
1263
- const knownSecrets = allSecrets();
1264
- return readResult({ servers: store.servers().map((record) => sanitize({
1265
- id: record.id,
1266
- slug: record.slug,
1267
- name: record.name,
1268
- transport: record.transport,
1269
- enabled: record.enabled,
1270
- selected: store.isSelected(agentId, record.id),
1271
- connectionState: connections.status(record.id).state
1272
- }, knownSecrets)) });
1273
- };
1274
2166
  const serverDetail = (serverId, agentId) => {
1275
2167
  try {
1276
2168
  const record = requireSelected(serverId, agentId);
1277
- return readResult(sanitize({
2169
+ return sanitize({
1278
2170
  id: record.id,
1279
2171
  slug: record.slug,
1280
2172
  name: record.name,
@@ -1289,31 +2181,25 @@ function registerMcpManagementTools(deps) {
1289
2181
  })),
1290
2182
  connectionState: connections.status(serverId).state,
1291
2183
  ...record.transport === "http" && record.config.auth === "oauth" ? { oauthAuthorized: oauth.status(serverId).authorized } : {}
1292
- }, allSecrets()));
2184
+ }, allSecrets());
1293
2185
  } catch (cause) {
1294
- return {
1295
- content: JSON.stringify({
1296
- status: "failed",
1297
- code: cause?.name === "CredentialUnavailableError" ? "credential-unavailable" : "not-found",
1298
- summary: "MCP server details are unavailable."
1299
- }),
1300
- isError: true
1301
- };
2186
+ throw Object.assign(/* @__PURE__ */ new Error("MCP server details are unavailable."), { code: cause?.name === "CredentialUnavailableError" ? "credential-unavailable" : "not-found" });
1302
2187
  }
1303
2188
  };
1304
- deps.register({
1305
- name: "mcp_server_list",
1306
- description: "List configured MCP servers and whether this agent selects each one. With `serverId`, read the safe configuration and credential status of one server this agent selects instead.",
1307
- inputSchema: ListInput,
1308
- async execute({ serverId }, ctx) {
1309
- const agentId = deps.definitions.read(ctx).agentId;
1310
- return serverId === void 0 ? listServers(agentId) : serverDetail(serverId, agentId);
1311
- }
1312
- });
2189
+ deps.register(serverPages({
2190
+ resources: deps.resources,
2191
+ store,
2192
+ secrets: allSecrets,
2193
+ state: (id) => connections.status(id).state,
2194
+ details: (id, call) => serverDetail(id, deps.definitions.read(call).agentId)
2195
+ }));
1313
2196
  deps.register({
1314
2197
  name: "mcp_server_create",
2198
+ preload: false,
1315
2199
  description: "Create an MCP server and optionally select it for this agent after approval.",
1316
2200
  inputSchema: Create,
2201
+ outputSchema: toolOutputSchema(MutationOutput, Create, "mcp_server_create"),
2202
+ deliveryKind: "receipt",
1317
2203
  async execute(fields, ctx) {
1318
2204
  let input = CreatePaired.parse(fields);
1319
2205
  const agentId = deps.definitions.read(ctx).agentId;
@@ -1363,8 +2249,11 @@ function registerMcpManagementTools(deps) {
1363
2249
  });
1364
2250
  deps.register({
1365
2251
  name: "mcp_server_update",
2252
+ preload: false,
1366
2253
  description: "Update a selected shared MCP server after approval.",
1367
2254
  inputSchema: Update,
2255
+ outputSchema: toolOutputSchema(MutationOutput, Update, "mcp_server_update"),
2256
+ deliveryKind: "receipt",
1368
2257
  async execute(input, ctx) {
1369
2258
  const agentId = deps.definitions.read(ctx).agentId;
1370
2259
  const previous = requireSelected(input.serverId, agentId);
@@ -1427,48 +2316,86 @@ function registerMcpManagementTools(deps) {
1427
2316
  });
1428
2317
  deps.register({
1429
2318
  name: "mcp_server_set_selected",
1430
- description: "Select or unselect an MCP server for this agent after approval.",
1431
- inputSchema: Select,
2319
+ preload: false,
2320
+ description: "Apply one complete Agent MCP selection intent atomically after one approval binds its original revision/hash and every change.",
2321
+ inputSchema: SelectInput,
2322
+ outputSchema: toolOutputSchema(MutationOutput, SelectInput, "mcp_server_set_selected"),
2323
+ deliveryKind: "receipt",
1432
2324
  async execute(input, ctx) {
1433
2325
  const agentId = deps.definitions.read(ctx).agentId;
1434
- const record = requireServer(input.serverId);
1435
- const selected = store.isSelected(agentId, record.id);
1436
- if (selected === input.selected) return readResult({
1437
- serverId: record.id,
1438
- selected
1439
- });
1440
- const id = `select-${createHash("sha256").update(JSON.stringify([
1441
- revisionOf(record),
1442
- store.agentServers(agentId),
1443
- input
1444
- ])).digest("hex")}`;
1445
- if (ctx.answer && !ctx.answer.answers.some((answer) => answer.questionId === deps.approval.questionId(id))) fail("conflict", "MCP selection changed since approval");
1446
- const decision = deps.approval.decide(ctx, {
1447
- id,
1448
- subject: `${input.selected ? "Select" : "Unselect"} MCP server ${redact(record.name, allSecrets())}`,
1449
- reason: "Change this agent’s MCP tools for subsequent steps.",
1450
- accepts: [
1451
- "allowed-once",
1452
- "allowed-session",
1453
- "allowed-always",
1454
- "rejected"
1455
- ],
1456
- remember: {
1457
- key: "mcp-server-select",
1458
- label: "Select MCP servers"
1459
- }
1460
- });
1461
- if (decision.kind === "ask") return decision.result;
1462
- if (!decision.result.kind.startsWith("allowed-")) return {
1463
- content: "MCP selection was not approved.",
1464
- isError: true
2326
+ const intent = {
2327
+ scope: `agent:${agentId}`,
2328
+ method: "mcp_server_set_selected",
2329
+ operationId: input.operationId,
2330
+ params: input
1465
2331
  };
1466
- selectServer(deps.management, agentId, record.id, input.selected, ctx);
1467
- return readResult({
1468
- serverId: record.id,
1469
- selected: input.selected,
1470
- summary: "Selection saved; tools change at the next model step."
1471
- });
2332
+ const replay = deps.management.operations.lookup(intent);
2333
+ if (replay) return readResult(replay);
2334
+ const changes = /* @__PURE__ */ new Map();
2335
+ for (const change of input.changes) {
2336
+ requireServer(change.serverId);
2337
+ if (changes.has(change.serverId) && changes.get(change.serverId) !== change.selected) throw new Error("conflicting selection changes");
2338
+ changes.set(change.serverId, change.selected);
2339
+ }
2340
+ const state = deps.management.agentConfig.state(agentId);
2341
+ const before = store.agentServers(agentId);
2342
+ const final = new Set(before);
2343
+ for (const [id, selected] of changes) if (selected) final.add(id);
2344
+ else final.delete(id);
2345
+ const serverIds = [...final].sort();
2346
+ if (JSON.stringify(before) !== JSON.stringify(serverIds)) {
2347
+ const key = `select-${createHash("sha256").update(JSON.stringify({
2348
+ state,
2349
+ changes: input.changes,
2350
+ servers: [...changes.keys()].map((id) => revisionOf(requireServer(id)))
2351
+ })).digest("hex")}`;
2352
+ if (ctx.answer && !ctx.answer.answers.some((answer) => answer.questionId === deps.approval.questionId(key))) fail("conflict", "MCP selection changed since approval");
2353
+ const decision = deps.approval.decide(ctx, {
2354
+ id: key,
2355
+ subject: `Change ${changes.size} MCP selections`,
2356
+ reason: "Apply this complete Agent selection for subsequent steps.",
2357
+ accepts: [
2358
+ "allowed-once",
2359
+ "allowed-session",
2360
+ "allowed-always",
2361
+ "rejected"
2362
+ ],
2363
+ remember: {
2364
+ key,
2365
+ label: "Select MCP servers"
2366
+ }
2367
+ });
2368
+ if (decision.kind === "ask") return decision.result;
2369
+ if (!decision.result.kind.startsWith("allowed-")) return {
2370
+ content: "MCP selection was not approved.",
2371
+ isError: true
2372
+ };
2373
+ }
2374
+ deps.management.agentConfig.check(agentId, state.revision, state.contentHash);
2375
+ const changed = JSON.stringify(before) !== JSON.stringify(serverIds);
2376
+ const prepared = changed ? deps.management.agentConfig.prepare(agentId, { extensionData: { "@eum-agent/integration-mcp": { mcpServerIds: serverIds } } }, ctx) : void 0;
2377
+ let committed = false;
2378
+ try {
2379
+ const receipt = deps.management.operations.atomic(intent, (scope) => {
2380
+ if (prepared) {
2381
+ if (prepared.connectionIdentity !== scope.connectionIdentity) throw new Error("foreign Agent transaction participant");
2382
+ prepared.assertCurrent();
2383
+ scope.afterRollback(() => prepared.abort());
2384
+ scope.afterCommit(() => prepared.settle());
2385
+ prepared.apply();
2386
+ }
2387
+ return {
2388
+ serverIds: store.agentServers(agentId),
2389
+ ...deps.management.agentConfig.state(agentId)
2390
+ };
2391
+ });
2392
+ committed = receipt.operationState !== "admitted";
2393
+ if (changed) deps.management.announce();
2394
+ return readResult(receipt);
2395
+ } catch (error) {
2396
+ if (!committed) prepared?.abort();
2397
+ throw error;
2398
+ }
1472
2399
  }
1473
2400
  });
1474
2401
  }
@@ -1506,6 +2433,7 @@ const StatusSchema = z.object({
1506
2433
  ]),
1507
2434
  reason: z.string().optional()
1508
2435
  }).strict();
2436
+ /** Credential-free catalogue row used by owner frames and complete mutation receipts. */
1509
2437
  const ServerSummarySchema = z.object({
1510
2438
  id: z.string(),
1511
2439
  slug: z.string(),
@@ -1583,6 +2511,23 @@ const TestResultSchema = z.union([z.object({
1583
2511
  ok: z.literal(false),
1584
2512
  reason: z.string()
1585
2513
  }).strict()]);
2514
+ const Reconciliation = z.strictObject({
2515
+ id: z.string(),
2516
+ state: z.enum([
2517
+ "pending",
2518
+ "completed",
2519
+ "failed"
2520
+ ]),
2521
+ reason: z.string().optional()
2522
+ });
2523
+ const ReconciledServers = ServerList.extend({ reconciliation: z.array(Reconciliation) });
2524
+ const RemovedServers = ServerList.extend({ cleanup: z.array(Reconciliation) });
2525
+ z.union([operationResult(ReconciledServers), operationResult(RemovedServers)]);
2526
+ z.strictObject({
2527
+ serverIds: z.array(z.string()),
2528
+ revision: z.number(),
2529
+ contentHash: z.string()
2530
+ });
1586
2531
  /** The longest server-written description a page is sent. */
1587
2532
  const DESCRIPTION_LIMIT = 2048;
1588
2533
  /** The most inputs listed for one tool or prompt. */
@@ -1703,6 +2648,7 @@ function registerMethods(deps) {
1703
2648
  const management = {
1704
2649
  commands: deps.commands,
1705
2650
  agentConfig: deps.agentConfig,
2651
+ operations: ctx.services.get("owner-operations"),
1706
2652
  store,
1707
2653
  connections,
1708
2654
  tools,
@@ -1727,10 +2673,13 @@ function registerMethods(deps) {
1727
2673
  handle: () => ({ servers: summaries() })
1728
2674
  });
1729
2675
  ctx.client.registerMethod({
1730
- name: "getServer",
1731
- params: Id,
1732
- result: ServerDetailSchema,
1733
- handle: ({ id }) => detail(require(id))
2676
+ name: "getServers",
2677
+ params: batchInput({
2678
+ ids: z.array(z.string().min(1)).min(1).max(64),
2679
+ ...queryBudgets
2680
+ }, "ids"),
2681
+ result: batchResult(ServerDetailSchema, z.string()),
2682
+ handle: (input) => settle(input.ids, (id) => detail(require(id)), input, (error, id) => redactReason(error instanceof Error ? error.message : "Operation failed", secretValues(deps.secretsOf(id))))
1734
2683
  });
1735
2684
  ctx.client.registerMethod({
1736
2685
  name: "saveServer",
@@ -1740,55 +2689,161 @@ function registerMethods(deps) {
1740
2689
  return detail(await saveServer(management, input));
1741
2690
  }
1742
2691
  });
2692
+ const identity = z.string().min(1);
2693
+ const ids = (max = 64) => z.array(identity).min(1).max(max);
2694
+ const reconciled = ReconciledServers;
2695
+ const removed = RemovedServers;
2696
+ const operation = (method, input) => ({
2697
+ scope: "settings",
2698
+ method,
2699
+ operationId: input.operationId,
2700
+ params: input
2701
+ });
2702
+ const operations = management.operations;
2703
+ const effects = async (intent, receipt, serverIds, remove = false) => {
2704
+ if (receipt.operationState === "admitted") return receipt;
2705
+ const cleanup = (await connections.collection(serverIds, () => settle(serverIds, async (id) => {
2706
+ if (remove) {
2707
+ oauth.invalidate(id);
2708
+ tools.forget(id);
2709
+ }
2710
+ await connections.reconcile(id);
2711
+ return await connections.cleanup(id);
2712
+ }), false)).results.flatMap((item) => item.ok ? item.value.state === "failed" ? [{
2713
+ code: item.target,
2714
+ message: item.value.reason ?? "cleanup-failed"
2715
+ }] : [] : [{
2716
+ code: item.target,
2717
+ message: item.error.message
2718
+ }]);
2719
+ announce();
2720
+ return cleanup.length ? operations.markCleanupPending(intent, cleanup) : receipt;
2721
+ };
2722
+ const replayCleanup = async (intent, receipt) => {
2723
+ if (receipt.operationState !== "cleanup-pending") return receipt;
2724
+ const ids = [...new Set(receipt.cleanup.map((item) => item.code))];
2725
+ const failed = (await connections.collection(ids, () => settle(ids, (id) => connections.cleanup(id)), false)).results.flatMap((item) => item.ok ? item.value.state === "failed" ? [{
2726
+ code: item.target,
2727
+ message: item.value.reason ?? "cleanup-failed"
2728
+ }] : [] : [{
2729
+ code: item.target,
2730
+ message: item.error.message
2731
+ }]);
2732
+ return failed.length ? operations.markCleanupPending(intent, failed) : operations.settleCleanup(intent);
2733
+ };
1743
2734
  ctx.client.registerMethod({
1744
- name: "removeServer",
1745
- params: Id,
1746
- result: ServerList,
1747
- async handle({ id }) {
1748
- require(id);
1749
- deps.agentConfig.save(store.agentsOf(id), () => store.removeServer(id));
1750
- deps.clearCredentials(id);
1751
- oauth.invalidate(id);
1752
- tools.forget(id);
1753
- connections.reconcile(id);
1754
- announce();
1755
- return { servers: summaries() };
2735
+ name: "removeServers",
2736
+ params: batchInput({
2737
+ operationId: z.uuid(),
2738
+ ids: ids()
2739
+ }, "ids"),
2740
+ result: operationResult(removed),
2741
+ async handle(input) {
2742
+ input = {
2743
+ ...input,
2744
+ ids: [...new Set(input.ids)]
2745
+ };
2746
+ const intent = operation("removeServers", input);
2747
+ const replay = operations.lookup(intent);
2748
+ if (replay) return replayCleanup(intent, replay);
2749
+ input.ids.forEach(require);
2750
+ const agents = [...new Set(input.ids.flatMap((id) => store.agentsOf(id)))];
2751
+ const prepared = [];
2752
+ let committed = false;
2753
+ try {
2754
+ for (const agent of agents) prepared.push(deps.agentConfig.prepare(agent, { extensionData: { [ctx.pluginName]: { mcpServerIds: store.agentServers(agent).filter((id) => !input.ids.includes(id)) } } }));
2755
+ const receipt = deps.selfWrite(() => operations.atomic(intent, (scope) => {
2756
+ for (const row of prepared) {
2757
+ if (row.connectionIdentity !== scope.connectionIdentity) throw new Error("foreign Agent transaction participant");
2758
+ row.assertCurrent();
2759
+ }
2760
+ scope.afterRollback(() => {
2761
+ for (const row of prepared.slice().reverse()) row.abort();
2762
+ });
2763
+ scope.afterCommit(() => {
2764
+ for (const row of prepared) row.settle();
2765
+ });
2766
+ for (const row of prepared) row.apply();
2767
+ for (const id of input.ids) store.removeServer(id);
2768
+ deps.credentials.clearMany(input.ids.map((id) => ({
2769
+ scope: id,
2770
+ mode: "all"
2771
+ })), scope);
2772
+ return {
2773
+ servers: summaries(),
2774
+ cleanup: input.ids.map((id) => ({
2775
+ id,
2776
+ state: "pending"
2777
+ }))
2778
+ };
2779
+ }));
2780
+ committed = receipt.operationState !== "admitted";
2781
+ return await effects(intent, receipt, input.ids, true);
2782
+ } catch (error) {
2783
+ if (!committed) for (const row of prepared.slice().reverse()) try {
2784
+ row.abort();
2785
+ } catch {}
2786
+ throw error;
2787
+ }
1756
2788
  }
1757
2789
  });
1758
2790
  ctx.client.registerMethod({
1759
- name: "setEnabled",
1760
- params: z.object({
1761
- id: z.string(),
2791
+ name: "setServersEnabled",
2792
+ params: batchInput({
2793
+ operationId: z.uuid(),
2794
+ ids: ids(),
1762
2795
  enabled: z.boolean()
1763
- }).strict(),
1764
- result: ServerSummarySchema,
1765
- async handle({ id, enabled }) {
1766
- require(id);
1767
- store.setEnabled(id, enabled);
1768
- connections.reconcile(id);
1769
- announce();
1770
- return summary(require(id));
2796
+ }, "ids"),
2797
+ result: operationResult(reconciled),
2798
+ async handle(input) {
2799
+ input = {
2800
+ ...input,
2801
+ ids: [...new Set(input.ids)]
2802
+ };
2803
+ const intent = operation("setServersEnabled", input);
2804
+ const replay = operations.lookup(intent);
2805
+ if (replay) return replayCleanup(intent, replay);
2806
+ const receipt = operations.atomic(intent, () => {
2807
+ input.ids.forEach(require);
2808
+ for (const id of input.ids) store.setEnabled(id, input.enabled);
2809
+ return {
2810
+ servers: summaries(),
2811
+ reconciliation: input.ids.map((id) => ({
2812
+ id,
2813
+ state: "pending"
2814
+ }))
2815
+ };
2816
+ });
2817
+ return effects(intent, receipt, input.ids);
1771
2818
  }
1772
2819
  });
1773
2820
  ctx.client.registerMethod({
1774
- name: "retryServer",
1775
- params: Id,
1776
- result: ServerSummarySchema,
1777
- handle({ id }) {
1778
- require(id);
1779
- connections.reconcile(id, { keepSnapshot: true });
2821
+ name: "retryServers",
2822
+ params: batchInput({ ids: ids(32) }, "ids"),
2823
+ result: batchResult(ServerSummarySchema, z.string()),
2824
+ async handle(input) {
2825
+ const result = await connections.collection(input.ids, () => settle(input.ids, async (id) => {
2826
+ require(id);
2827
+ await connections.reconcile(id, { keepSnapshot: true });
2828
+ const cleanup = await connections.cleanup(id);
2829
+ if (cleanup.state === "failed") throw new Error(cleanup.reason);
2830
+ return summary(require(id));
2831
+ }), false);
1780
2832
  announce();
1781
- return summary(require(id));
2833
+ return result;
1782
2834
  }
1783
2835
  });
1784
2836
  ctx.client.registerMethod({
1785
- name: "testServer",
1786
- params: Id,
1787
- result: TestResultSchema,
1788
- handle: async ({ id }) => {
2837
+ name: "testServers",
2838
+ params: batchInput({
2839
+ ids: ids(32),
2840
+ ...queryBudgets
2841
+ }, "ids"),
2842
+ result: batchResult(TestResultSchema, z.string()),
2843
+ handle: (input) => connections.collection(input.ids, () => settle(input.ids, async (id) => {
1789
2844
  require(id);
1790
2845
  return await connections.test(id);
1791
- }
2846
+ }, input), false)
1792
2847
  });
1793
2848
  ctx.client.registerMethod({
1794
2849
  name: "authorize",
@@ -1814,29 +2869,54 @@ function registerMethods(deps) {
1814
2869
  }
1815
2870
  });
1816
2871
  ctx.client.registerMethod({
1817
- name: "signOut",
1818
- params: Id,
1819
- result: ServerSummarySchema,
1820
- handle({ id }) {
1821
- require(id);
1822
- oauth.signOut(id);
1823
- connections.reconcile(id);
1824
- announce();
1825
- return summary(require(id));
2872
+ name: "signOutServers",
2873
+ params: batchInput({
2874
+ operationId: z.uuid(),
2875
+ ids: ids()
2876
+ }, "ids"),
2877
+ result: operationResult(reconciled),
2878
+ async handle(input) {
2879
+ input = {
2880
+ ...input,
2881
+ ids: [...new Set(input.ids)]
2882
+ };
2883
+ const intent = operation("signOutServers", input);
2884
+ const replay = operations.lookup(intent);
2885
+ if (replay) return replayCleanup(intent, replay);
2886
+ const receipt = deps.selfWrite(() => operations.atomic(intent, (scope) => {
2887
+ input.ids.forEach(require);
2888
+ deps.credentials.clearMany(input.ids.map((id) => ({
2889
+ scope: id,
2890
+ mode: "names",
2891
+ names: ["oauth.tokens", "oauth.client"]
2892
+ })), scope);
2893
+ return {
2894
+ servers: summaries(),
2895
+ reconciliation: input.ids.map((id) => ({
2896
+ id,
2897
+ state: "pending"
2898
+ }))
2899
+ };
2900
+ }));
2901
+ for (const id of input.ids) oauth.invalidate(id);
2902
+ return effects(intent, receipt, input.ids);
1826
2903
  }
1827
2904
  });
1828
2905
  ctx.client.registerMethod({
1829
- name: "agentServers",
1830
- params: Agent,
1831
- result: z.object({
2906
+ name: "agentServerSets",
2907
+ params: batchInput({
2908
+ agentIds: ids(),
2909
+ ...queryBudgets
2910
+ }, "agentIds"),
2911
+ result: batchResult(z.strictObject({
1832
2912
  serverIds: z.array(z.string()),
1833
2913
  revision: z.number(),
1834
2914
  contentHash: z.string()
1835
- }).strict(),
1836
- handle: ({ agentId }) => ({
2915
+ }), z.string()),
2916
+ handle: (input) => settle(input.agentIds, (agentId) => ({
1837
2917
  serverIds: store.agentServers(agentId),
1838
2918
  ...deps.agentConfig.state(agentId)
1839
- })
2919
+ }), input)
1840
2920
  });
1841
2921
  ctx.client.registerMethod({
1842
2922
  name: "setAgentServers",
@@ -1889,15 +2969,25 @@ function registerMethods(deps) {
1889
2969
  result: z.object({ resources: z.array(ResourceEntrySchema) }).strict(),
1890
2970
  handle: ({ agentId, query }) => ({ resources: prompts.resources(agentId, query) })
1891
2971
  });
2972
+ const resourceMember = z.strictObject({
2973
+ serverId: z.string().min(1),
2974
+ uri: z.string().min(1),
2975
+ maxBytes: z.number().int().min(1).max(1048576)
2976
+ });
1892
2977
  ctx.client.registerMethod({
1893
- name: "readResource",
1894
- params: z.object({
1895
- agentId: z.string().min(1),
2978
+ name: "readResources",
2979
+ params: resourceInput({ agentId: z.string().min(1) }, resourceMember),
2980
+ result: batchResult(Text, z.strictObject({
1896
2981
  serverId: z.string(),
1897
2982
  uri: z.string()
1898
- }).strict(),
1899
- result: Text,
1900
- handle: (input, call) => prompts.read(input, call.signal)
2983
+ })),
2984
+ handle: (input, call) => settle(input.items.map((item) => ({
2985
+ serverId: item.serverId,
2986
+ uri: item.uri
2987
+ })), (_target, index) => prompts.read({
2988
+ agentId: input.agentId,
2989
+ ...input.items[index]
2990
+ }, call.signal), void 0, (error, target) => redactReason(error instanceof Error ? error.message : "Operation failed", secretValues(deps.secretsOf(target.serverId))))
1901
2991
  });
1902
2992
  return {
1903
2993
  announce,
@@ -2003,17 +3093,27 @@ function createOAuth(deps) {
2003
3093
  ...tokens,
2004
3094
  ...tokens.expires_in === void 0 ? {} : { expires_at: now() + tokens.expires_in * 1e3 }
2005
3095
  };
2006
- deps.selfWrite(() => deps.credentials.set(serverId, OAUTH_TOKENS, JSON.stringify(stored)));
3096
+ deps.selfWrite(() => deps.credentials.setMany(serverId, [{
3097
+ name: OAUTH_TOKENS,
3098
+ value: JSON.stringify(stored)
3099
+ }]));
2007
3100
  return stored;
2008
3101
  };
2009
3102
  const writeClient = (serverId, generation, info) => {
2010
3103
  if (generation !== gen(serverId)) throw new Error("authorization was superseded");
2011
- deps.selfWrite(() => deps.credentials.set(serverId, OAUTH_CLIENT, JSON.stringify(info)));
3104
+ deps.selfWrite(() => deps.credentials.setMany(serverId, [{
3105
+ name: OAUTH_CLIENT,
3106
+ value: JSON.stringify(info)
3107
+ }]));
2012
3108
  };
2013
3109
  const clear = (serverId, name) => {
2014
3110
  const names = name === void 0 ? [OAUTH_TOKENS, OAUTH_CLIENT] : [name];
2015
3111
  if (names.includes("oauth.tokens")) replaced.delete(serverId);
2016
- for (const item of names) deps.selfWrite(() => deps.credentials.clear(serverId, item));
3112
+ deps.selfWrite(() => deps.credentials.clearMany([{
3113
+ scope: serverId,
3114
+ mode: "names",
3115
+ names
3116
+ }]));
2017
3117
  };
2018
3118
  const invalidateScope = (serverId, scope, flow) => {
2019
3119
  if (scope === "all" || scope === "tokens") clear(serverId, OAUTH_TOKENS);
@@ -2139,7 +3239,11 @@ function createOAuth(deps) {
2139
3239
  } catch (error) {
2140
3240
  if (error instanceof NeedsAuthorizationError) throw error;
2141
3241
  if (error instanceof OAuthError && !(error instanceof ServerError)) throw new NeedsAuthorizationError(`token refresh was refused: ${error.errorCode}`);
2142
- deps.log.warn(`token refresh for server ${serverId} failed; using the stored token`);
3242
+ deps.log.emit({
3243
+ level: "warn",
3244
+ event: "plugin.event",
3245
+ fields: { localCode: "TOKEN_REFRESH_FOR_SERVER" }
3246
+ });
2143
3247
  return strip(stored);
2144
3248
  }
2145
3249
  },
@@ -2302,10 +3406,6 @@ function createOAuth(deps) {
2302
3406
  }
2303
3407
  //#endregion
2304
3408
  //#region src/content.ts
2305
- /** A tool result's ceiling: 48 KiB of head and 16 KiB of tail at most. */
2306
- const TOOL_RESULT_LIMIT = 65536;
2307
- /** A resource read's ceiling. */
2308
- const RESOURCE_LIMIT = 102400;
2309
3409
  const notice = (omitted) => `\n\n[… ${omitted} bytes omitted …]\n\n`;
2310
3410
  /**
2311
3411
  * `text` when it fits in `limit` UTF-8 bytes; otherwise its head and tail
@@ -2422,6 +3522,14 @@ function promptText(result) {
2422
3522
  function readResultText(result) {
2423
3523
  return result.contents.map((content) => resourceText(content)).join("\n\n");
2424
3524
  }
3525
+ /** Counts original resource contents without allocating decoded binary blobs or a combined body. */
3526
+ function assertResourceBytes(result, maxBytes) {
3527
+ let bytes = 0;
3528
+ for (const item of result.contents) {
3529
+ bytes += typeof item.text === "string" ? Buffer.byteLength(item.text) : typeof item.blob === "string" ? blobBytes(item.blob) : 0;
3530
+ if (bytes > maxBytes) throw Object.assign(/* @__PURE__ */ new Error("MCP resource exceeds declared budget"), { code: "read-limit" });
3531
+ }
3532
+ }
2425
3533
  /** A host composer command argument name. */
2426
3534
  const ARGUMENT_NAME = /^[A-Za-z0-9_][A-Za-z0-9_-]{0,63}$/;
2427
3535
  /** The first twelve hex characters of `sha256(slug + "\0" + name)`. */
@@ -2465,7 +3573,9 @@ async function guarded(secrets, request) {
2465
3573
  try {
2466
3574
  return await request();
2467
3575
  } catch (error) {
2468
- throw new Error(redact(error instanceof Error ? error.message : String(error), secrets));
3576
+ const safe = new Error(redact(error instanceof Error ? error.message : String(error), secrets));
3577
+ if (error instanceof Error && "code" in error && error.code === "read-limit") Object.assign(safe, { code: "read-limit" });
3578
+ throw safe;
2469
3579
  }
2470
3580
  }
2471
3581
  /**
@@ -2589,7 +3699,11 @@ function createPrompts(deps) {
2589
3699
  },
2590
3700
  async read(input, signal) {
2591
3701
  const { live } = selected(input.agentId, input.serverId);
2592
- return { text: truncate(redact(readResultText(await guarded(live.secrets, () => live.client.readResource({ uri: input.uri }, signal ? { signal } : void 0))), live.secrets), RESOURCE_LIMIT) };
3702
+ const result = await guarded(live.secrets, () => withResourceBudget(input.maxBytes, () => live.client.readResource({ uri: input.uri }, signal ? { signal } : void 0)));
3703
+ assertResourceBytes(result, input.maxBytes);
3704
+ const text = redact(readResultText(result), live.secrets);
3705
+ if (Buffer.byteLength(text) > input.maxBytes) throw Object.assign(/* @__PURE__ */ new Error("MCP resource exceeds declared budget"), { code: "read-limit" });
3706
+ return { text };
2593
3707
  }
2594
3708
  };
2595
3709
  }
@@ -2650,7 +3764,9 @@ CREATE INDEX IF NOT EXISTS ${tableName("agent_server_by_server")} ON ${selection
2650
3764
  throw error;
2651
3765
  }
2652
3766
  };
3767
+ let directoryVersion = 0;
2653
3768
  const saveServer = (record) => {
3769
+ directoryVersion++;
2654
3770
  db.prepare(`INSERT INTO ${servers} (id, slug, name, transport, config, enabled, acknowledged_at, created_at)
2655
3771
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
2656
3772
  ON CONFLICT(id) DO UPDATE SET slug = excluded.slug, name = excluded.name,
@@ -2658,11 +3774,34 @@ CREATE INDEX IF NOT EXISTS ${tableName("agent_server_by_server")} ON ${selection
2658
3774
  acknowledged_at = excluded.acknowledged_at`).run(record.id, record.slug, record.name, record.transport, JSON.stringify(record.config), record.enabled ? 1 : 0, record.acknowledgedAt, record.createdAt);
2659
3775
  };
2660
3776
  const setServerSelected = (agentId, serverId, selected) => {
3777
+ directoryVersion++;
2661
3778
  if (selected) db.prepare(`INSERT OR IGNORE INTO ${selections} (agent_id, server_id) VALUES (?, ?)`).run(agentId, serverId);
2662
3779
  else db.prepare(`DELETE FROM ${selections} WHERE agent_id = ? AND server_id = ?`).run(agentId, serverId);
2663
3780
  };
2664
3781
  return {
2665
3782
  transaction,
3783
+ /** Header-only keyset query; selected-id filtering precedes LIMIT and never parses config. */
3784
+ headerPage(agentId, after, limit, ids) {
3785
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new Error("invalid header page limit");
3786
+ const filter = ids ? `AND s.id IN (${ids.map(() => "?").join(",")}) AND EXISTS (SELECT 1 FROM ${selections} a WHERE a.agent_id=? AND a.server_id=s.id)` : "";
3787
+ const rows = db.prepare(`SELECT s.id,s.slug,s.name,s.transport,s.enabled,
3788
+ EXISTS(SELECT 1 FROM ${selections} a WHERE a.agent_id=? AND a.server_id=s.id) AS selected
3789
+ FROM ${servers} s WHERE s.id>? ${filter} ORDER BY s.id LIMIT ?`).all(agentId, after ?? "", ...ids ? [...ids, agentId] : [], limit + 1);
3790
+ return {
3791
+ items: rows.slice(0, limit).map((row) => ({
3792
+ id: String(row.id),
3793
+ slug: String(row.slug),
3794
+ name: String(row.name),
3795
+ transport: row.transport,
3796
+ enabled: Number(row.enabled) === 1,
3797
+ selected: Number(row.selected) === 1
3798
+ })),
3799
+ complete: rows.length <= limit,
3800
+ queryVersion: directoryVersion
3801
+ };
3802
+ },
3803
+ /** Advances for every owner catalogue mutation; process restart invalidates owner cursor state. */
3804
+ directoryVersion: () => directoryVersion,
2666
3805
  servers() {
2667
3806
  return db.prepare(`SELECT * FROM ${servers} ORDER BY created_at, id`).all().map((row) => parse(row));
2668
3807
  },
@@ -2686,12 +3825,14 @@ CREATE INDEX IF NOT EXISTS ${tableName("agent_server_by_server")} ON ${selection
2686
3825
  /** Adds or removes one agent's selection without replacing other selections. */
2687
3826
  setServerSelected,
2688
3827
  setEnabled(id, enabled) {
3828
+ directoryVersion++;
2689
3829
  db.prepare(`UPDATE ${servers} SET enabled = ? WHERE id = ?`).run(enabled ? 1 : 0, id);
2690
3830
  },
2691
3831
  /** Deletes a server with its selections, in one transaction. Its tools'
2692
3832
  * remembered approvals are the host's grants, keyed by this server's id,
2693
3833
  * and a person revokes them in the access list. */
2694
3834
  removeServer(id) {
3835
+ directoryVersion++;
2695
3836
  transaction(() => {
2696
3837
  db.prepare(`DELETE FROM ${servers} WHERE id = ?`).run(id);
2697
3838
  db.prepare(`DELETE FROM ${selections} WHERE server_id = ?`).run(id);
@@ -2708,6 +3849,7 @@ CREATE INDEX IF NOT EXISTS ${tableName("agent_server_by_server")} ON ${selection
2708
3849
  },
2709
3850
  /** Replaces an agent's selection whole. */
2710
3851
  setAgentServers(agentId, serverIds) {
3852
+ directoryVersion++;
2711
3853
  transaction(() => {
2712
3854
  db.prepare(`DELETE FROM ${selections} WHERE agent_id = ?`).run(agentId);
2713
3855
  const insert = db.prepare(`INSERT INTO ${selections} (agent_id, server_id) VALUES (?, ?)`);
@@ -2716,8 +3858,32 @@ CREATE INDEX IF NOT EXISTS ${tableName("agent_server_by_server")} ON ${selection
2716
3858
  }
2717
3859
  };
2718
3860
  }
2719
- /** The longest description a model is shown. */
2720
- const DESCRIPTION_MAX = 2048;
3861
+ //#endregion
3862
+ //#region src/input-schema.ts
3863
+ /** Compiles a remote input contract before a tool becomes callable. */
3864
+ /** Enforces complete remote schemas locally; absent dialect declarations use MCP's 2020-12 default. */
3865
+ function inputValidator(schema) {
3866
+ const version = schema.$schema;
3867
+ const options = {
3868
+ strict: false,
3869
+ strictSchema: true,
3870
+ strictNumbers: true,
3871
+ validateSchema: true,
3872
+ allErrors: false,
3873
+ validateFormats: true
3874
+ };
3875
+ const compiler = version === void 0 || version === "https://json-schema.org/draft/2020-12/schema" ? new Ajv2020(options) : version === "https://json-schema.org/draft/2019-09/schema" ? new Ajv2019(options) : version === "http://json-schema.org/draft-07/schema#" || version === "http://json-schema.org/draft-07/schema" ? new Ajv(options) : void 0;
3876
+ if (!compiler) throw new Error("unsupported_tool_schema: unsupported JSON Schema dialect");
3877
+ addFormats.default(compiler);
3878
+ const validate = compiler.compile(schema);
3879
+ if ("$async" in validate && validate.$async) throw new Error("unsupported_tool_schema: asynchronous validation is unsupported");
3880
+ return z.record(z.string(), z.unknown()).superRefine((input, ctx) => {
3881
+ if (!validate(input)) ctx.addIssue({
3882
+ code: "custom",
3883
+ message: compiler.errorsText(validate.errors).slice(0, 512)
3884
+ });
3885
+ });
3886
+ }
2721
3887
  const RESOURCE_TOOL = "mcp_resource_read";
2722
3888
  const REFUSED_TAKEN = "name already taken";
2723
3889
  const REFUSED_COLLISION = "maps to the same name as another tool of this server";
@@ -2726,10 +3892,9 @@ const RESERVED_TOOL_NAMES = /* @__PURE__ */ new Set([RESOURCE_TOOL, ...TOOL_NAME
2726
3892
  function reservedToolName(name) {
2727
3893
  return RESERVED_TOOL_NAMES.has(name);
2728
3894
  }
2729
- const AnyObject = z.record(z.string(), z.unknown());
2730
3895
  const ResourceInput = z.object({
2731
- server: z.string().describe("The slug of an MCP server this agent selects."),
2732
- uri: z.string().describe("The resource URI the server listed.")
3896
+ server: z.string().min(1).max(200).describe("The slug of an MCP server this agent selects."),
3897
+ uri: z.string().min(1).max(8192).describe("The resource URI the server listed.")
2733
3898
  }).strict();
2734
3899
  const messageOf = (error) => error instanceof Error ? error.message : String(error);
2735
3900
  const isTimeout = (error) => error?.code === -32001;
@@ -2811,6 +3976,11 @@ function createTools(deps) {
2811
3976
  content: "this MCP server is not selected by this agent",
2812
3977
  isError: true
2813
3978
  };
3979
+ const current = deps.connections().snapshot(serverId)?.tools.find((candidate) => candidate.name === tool.name);
3980
+ if (!current || definitionKey(record.name, current) !== definitionKey(record.name, tool)) return {
3981
+ content: "MCP tool definition changed; search for the current definition again.",
3982
+ isError: true
3983
+ };
2814
3984
  const down = notConnected(serverId, record.name);
2815
3985
  if (down) return down;
2816
3986
  const gate = await approve(serverId, record, tool.name, input, exec);
@@ -2829,8 +3999,12 @@ function createTools(deps) {
2829
3999
  timeout: callTimeout
2830
4000
  });
2831
4001
  const { text: raw, files } = toolResultContent(result);
4002
+ const text = redact(raw, live.secrets);
2832
4003
  return {
2833
- content: truncate(redact(raw, live.secrets), TOOL_RESULT_LIMIT),
4004
+ content: JSON.stringify({
4005
+ text,
4006
+ sourceComplete: true
4007
+ }),
2834
4008
  ...result.isError === true ? { isError: true } : {},
2835
4009
  ...files.length === 0 ? {} : { files }
2836
4010
  };
@@ -2856,12 +4030,12 @@ function createTools(deps) {
2856
4030
  };
2857
4031
  }
2858
4032
  }
2859
- const definitionKey = (serverName, tool) => JSON.stringify([
4033
+ const definitionKey = (serverName, tool) => createHash("sha256").update(JSON.stringify([
2860
4034
  serverName,
2861
4035
  tool.name,
2862
4036
  tool.description ?? "",
2863
4037
  tool.inputSchema
2864
- ]);
4038
+ ])).digest("hex");
2865
4039
  /**
2866
4040
  * Replaces a server's registrations with what `snapshot` lists, in one
2867
4041
  * synchronous pass: withdraws what disappeared, registers what is new and
@@ -2880,10 +4054,15 @@ function createTools(deps) {
2880
4054
  nextMapped.set(tool.name, name);
2881
4055
  if (reservedToolName(name)) nextRefused.set(tool.name, REFUSED_TAKEN);
2882
4056
  else if (clashes.has(name)) nextRefused.set(tool.name, REFUSED_COLLISION);
2883
- else wanted.set(name, {
2884
- tool,
2885
- key: definitionKey(record.name, tool)
2886
- });
4057
+ else try {
4058
+ wanted.set(name, {
4059
+ tool,
4060
+ key: definitionKey(record.name, tool),
4061
+ input: inputValidator(tool.inputSchema)
4062
+ });
4063
+ } catch {
4064
+ nextRefused.set(tool.name, "unsupported_tool_schema");
4065
+ }
2887
4066
  }
2888
4067
  }
2889
4068
  for (const [name, entry] of current) {
@@ -2891,14 +4070,22 @@ function createTools(deps) {
2891
4070
  entry.dispose();
2892
4071
  current.delete(name);
2893
4072
  }
2894
- for (const [name, { tool, key }] of wanted) {
4073
+ for (const [name, { tool, key, input }] of wanted) {
2895
4074
  if (current.has(name) || !record) continue;
2896
- const description = `[MCP · ${record.name}] ${tool.description ?? ""}`.slice(0, DESCRIPTION_MAX);
4075
+ const description = `[MCP · ${record.name}] ${tool.description ?? ""}`;
2897
4076
  try {
2898
4077
  const dispose = handleFor(serverId).tools.register({
2899
4078
  name,
2900
4079
  description,
2901
- inputSchema: AnyObject,
4080
+ inputSchema: input,
4081
+ preload: false,
4082
+ catalogKind: "dynamic",
4083
+ deliveryKind: "preview",
4084
+ outputSchema: z.union([z.strictObject({
4085
+ text: z.string(),
4086
+ sourceComplete: z.boolean()
4087
+ }), z.string().max(1024)]),
4088
+ available: () => deps.connections().status(serverId).state === "connected",
2902
4089
  jsonSchema: tool.inputSchema,
2903
4090
  execute: (input, exec) => call(serverId, tool, input, exec)
2904
4091
  });
@@ -2908,7 +4095,11 @@ function createTools(deps) {
2908
4095
  });
2909
4096
  } catch (error) {
2910
4097
  nextRefused.set(tool.name, REFUSED_TAKEN);
2911
- deps.log.warn(`MCP tool ${name} was not registered: ${messageOf(error)}`);
4098
+ deps.log.emit({
4099
+ level: "warn",
4100
+ event: "plugin.event",
4101
+ fields: { localCode: "MCP_TOOL" }
4102
+ });
2912
4103
  }
2913
4104
  }
2914
4105
  registered.set(serverId, current);
@@ -2925,7 +4116,7 @@ function createTools(deps) {
2925
4116
  apply(serverId, void 0);
2926
4117
  scoped.delete(serverId);
2927
4118
  }
2928
- async function readResource(input, exec) {
4119
+ async function readResource(input, exec, maxBytes) {
2929
4120
  const record = store.serverBySlug(input.server);
2930
4121
  if (!record || !store.isSelected(exec.address.agentId, record.id)) return {
2931
4122
  content: `server "${input.server}" is not selected by this agent`,
@@ -2939,11 +4130,16 @@ function createTools(deps) {
2939
4130
  isError: true
2940
4131
  };
2941
4132
  try {
2942
- return { content: truncate(redact(readResultText(await live.client.readResource({ uri: input.uri }, {
4133
+ const result = await withResourceBudget(maxBytes, () => live.client.readResource({ uri: input.uri }, {
2943
4134
  signal: exec.signal,
2944
4135
  timeout: callTimeout
2945
- })), live.secrets), RESOURCE_LIMIT) };
4136
+ }));
4137
+ assertResourceBytes(result, maxBytes);
4138
+ const content = redact(readResultText(result), live.secrets);
4139
+ if (Buffer.byteLength(content) > maxBytes) throw Object.assign(/* @__PURE__ */ new Error("MCP resource exceeds declared budget"), { code: "read-limit" });
4140
+ return { content };
2946
4141
  } catch (error) {
4142
+ if (error instanceof Error && "code" in error && error.code === "read-limit") throw error;
2947
4143
  if (isTimeout(error)) return {
2948
4144
  content: `调用超时(${Math.round(callTimeout / 6e4)} 分钟)`,
2949
4145
  isError: true
@@ -2959,9 +4155,28 @@ function createTools(deps) {
2959
4155
  function registerResourceTool() {
2960
4156
  return ctx.forAgents((agentId) => store.agentServers(agentId).some((id) => (deps.connections().snapshot(id)?.resources.length ?? 0) > 0)).tools.register({
2961
4157
  name: RESOURCE_TOOL,
4158
+ preload: false,
2962
4159
  description: "Read a resource from an MCP server this agent selects, by the server slug and the resource URI.",
2963
- inputSchema: ResourceInput,
2964
- execute: readResource
4160
+ inputSchema: z.strictObject({
4161
+ items: z.array(ResourceInput).min(1).max(32).describe("Ordered selected-server resources, maximum 32; physical source limits are managed internally."),
4162
+ outputTokens: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional().describe("Desired model delivery tokens. Accepted originals are retained before bounded previews.")
4163
+ }),
4164
+ outputSchema: batchResult(z.strictObject({ content: z.string() }), z.strictObject({
4165
+ server: z.string(),
4166
+ uri: z.string()
4167
+ })),
4168
+ deliveryKind: "preview",
4169
+ async execute(input, exec) {
4170
+ const batch = await settle(input.items.map((item) => ({
4171
+ server: item.server,
4172
+ uri: item.uri
4173
+ })), async (_target, index) => {
4174
+ const result = await readResource(input.items[index], exec, Math.min(1048576, Math.floor(4194304 / input.items.length)));
4175
+ if (result.isError) throw new Error(result.content);
4176
+ return result;
4177
+ });
4178
+ return { content: JSON.stringify(batch) };
4179
+ }
2965
4180
  });
2966
4181
  }
2967
4182
  return {
@@ -2992,7 +4207,9 @@ function createMcpPlugin(options = {}) {
2992
4207
  name: "@eum-agent/integration-mcp",
2993
4208
  configSchema: McpConfig,
2994
4209
  requires: [
4210
+ "query-resources",
2995
4211
  "credentials",
4212
+ "owner-operations",
2996
4213
  "host-commands",
2997
4214
  "protocol-processes",
2998
4215
  "network",
@@ -3093,7 +4310,8 @@ function createMcpPlugin(options = {}) {
3093
4310
  tools,
3094
4311
  prompts,
3095
4312
  oauth,
3096
- clearCredentials: (serverId) => selfWrite(() => credentials.clear(serverId)),
4313
+ credentials,
4314
+ selfWrite,
3097
4315
  secretsOf,
3098
4316
  agentConfig
3099
4317
  });
@@ -3124,6 +4342,7 @@ function createMcpPlugin(options = {}) {
3124
4342
  announce = methods.announce;
3125
4343
  const disabled = new Set(config.disabled);
3126
4344
  registerMcpManagementTools({
4345
+ resources: ctx.services.get("query-resources"),
3127
4346
  definitions,
3128
4347
  approval,
3129
4348
  store,
@@ -3158,9 +4377,9 @@ function createMcpPlugin(options = {}) {
3158
4377
  ]
3159
4378
  });
3160
4379
  tools.registerResourceTool();
3161
- const offCredentials = credentials.onChanged((scope) => {
3162
- if (ctx.signal.aborted || selfWriting > 0 || !store.server(scope)) return;
3163
- connections.reconcile(scope, { keepSnapshot: true });
4380
+ const offCredentials = credentials.onChanged((scopes) => {
4381
+ if (ctx.signal.aborted || selfWriting > 0) return;
4382
+ for (const scope of scopes) if (store.server(scope)) connections.reconcile(scope, { keepSnapshot: true });
3164
4383
  });
3165
4384
  let withdrawn = false;
3166
4385
  let unbind = () => {};