Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(plugins): discover MCP catalogs whole instead of truncating at 64

vastsa3946041653f6
diff --git a/apps/desktop/electron/main/plugin-mcp.ts b/apps/desktop/electron/main/plugin-mcp.ts
index 774cc1fd3..e773ae22f 100644
--- a/apps/desktop/electron/main/plugin-mcp.ts
+++ b/apps/desktop/electron/main/plugin-mcp.ts
@@ -8,12 +8,19 @@ export const MCP_PROTOCOL_VERSION = "2025-06-18";
export const MCP_CONNECT_TIMEOUT_MS = 10_000;
/** Kept under the plugin tool budget so the MCP error wins the race. */
export const MCP_CALL_TIMEOUT_MS = 100_000;
-/** A chatty server must not flood the model's tool list. */
-export const MAX_MCP_TOOLS_PER_SERVER = 64;
+/**
+ * Protocol bound, not a prompt budget: MCP tools reach the model as on-demand
+ * entries behind `ToolSearch` rather than as an always-present list, so the
+ * only thing that needs a ceiling is a server streaming forever. Sized like
+ * Codex's per-server MCP catalog bound; a real catalog never approaches it.
+ */
+export const MAX_MCP_TOOLS_PER_SERVER = 2_048;
/** Keep an MCP endpoint from bouncing requests through an unbounded chain. */
const MAX_MCP_REDIRECTS = 5;
-/** `tools/list` pages to follow before giving up on a cursor loop. */
-const MAX_TOOL_PAGES = 8;
+/** `tools/list` pages one server may span before its handshake is refused. */
+const MAX_TOOL_PAGES = 100;
+/** A whole `tools/list` traversal must finish inside this budget. */
+export const MCP_TOOL_DISCOVERY_TIMEOUT_MS = 30_000;
/** Guard against a server streaming an unbounded line at us. */
const MAX_STDIO_LINE_BYTES = 4 * 1024 * 1024;
/** Guard against a remote MCP server streaming an unbounded response body. */
@@ -382,6 +389,8 @@ export type McpServerClientOptions = {
auditScope?: string;
connectTimeoutMs?: number;
callTimeoutMs?: number;
+ /** Budget for the whole `tools/list` traversal, however many pages it spans. */
+ discoveryTimeoutMs?: number;
/** Test seams. */
spawnImpl?: typeof nodeSpawn;
fetchImpl?: typeof fetch;
@@ -542,30 +551,50 @@ export class McpServerClient {
);
}
+ /**
+ * Read the server's whole catalog.
+ *
+ * The tool count is bounded only by the protocol guards below, because the
+ * model never receives this as a list: MCP tools land in the on-demand
+ * catalog behind `ToolSearch`, and the prompt block that advertises them is
+ * what truncates. What has to stay bounded is the traversal itself — pages,
+ * items, cursors, and total time — and a server that exceeds any of those is
+ * refused rather than silently contributing a prefix of its catalog.
+ */
private async listTools(timeoutMs: number): Promise<McpTool[]> {
const collected: McpTool[] = [];
+ const seenCursors = new Set<string>();
+ const deadline =
+ Date.now() + (this.opts.discoveryTimeoutMs ?? MCP_TOOL_DISCOVERY_TIMEOUT_MS);
let cursor: string | undefined;
- for (let page = 0; page < MAX_TOOL_PAGES; page += 1) {
+ for (let page = 0; ; page += 1) {
+ if (page >= MAX_TOOL_PAGES) {
+ throw mcpError(
+ "LIMIT_EXCEEDED",
+ `mcp tools/list exceeded ${MAX_TOOL_PAGES} pages (${collected.length} tools so far)`,
+ );
+ }
+ const remaining = deadline - Date.now();
+ if (remaining <= 0) {
+ throw mcpError(
+ "TIMEOUT",
+ `mcp tools/list did not finish inside its budget (${collected.length} tools so far)`,
+ );
+ }
const result = (await this.request(
"tools/list",
cursor ? { cursor } : {},
- timeoutMs,
+ Math.min(timeoutMs, remaining),
)) as { tools?: unknown; nextCursor?: unknown } | null;
const tools = Array.isArray(result?.tools) ? result?.tools : [];
for (const raw of tools as Array<Record<string, unknown>>) {
const name = typeof raw?.name === "string" ? raw.name.trim() : "";
if (!name) continue;
if (collected.length >= MAX_MCP_TOOLS_PER_SERVER) {
- this.opts.audit?.({
- pluginId: this.opts.pluginId,
- api: this.auditApi("tools.truncated"),
- ok: false,
- errorCode: "LIMIT_EXCEEDED",
- serverId: this.serverId,
- limit: MAX_MCP_TOOLS_PER_SERVER,
- ts: Date.now(),
- });
- return collected;
+ throw mcpError(
+ "LIMIT_EXCEEDED",
+ `mcp server advertises more than ${MAX_MCP_TOOLS_PER_SERVER} tools`,
+ );
}
collected.push({
name,
@@ -573,11 +602,20 @@ export class McpServerClient {
inputSchema: raw.inputSchema,
});
}
- const next = typeof result?.nextCursor === "string" ? result.nextCursor : "";
- if (!next || next === cursor) return collected;
+ const next = result?.nextCursor;
+ // Absent and empty both mean "that was the last page"; anything else has
+ // to be a cursor this client can follow, so a malformed one is refused
+ // rather than mistaken for the end of a catalog.
+ if (next === undefined || next === null || next === "") return collected;
+ if (typeof next !== "string") {
+ throw mcpError("INVALID_RESPONSE", "mcp server returned a non-string tools/list cursor");
+ }
+ if (seenCursors.has(next)) {
+ throw mcpError("INVALID_RESPONSE", "mcp server repeated a tools/list cursor");
+ }
+ seenCursors.add(next);
cursor = next;
}
- return collected;
}
private request(method: string, params: unknown, timeoutMs: number): Promise<unknown> {
diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.ts
index fa5af2eef..44bbd0652 100644
--- a/apps/desktop/electron/main/plugin-runtime.ts
+++ b/apps/desktop/electron/main/plugin-runtime.ts
@@ -374,7 +374,7 @@ export type PluginHostServices = {
/** Transport overrides for plugin-declared MCP servers; tests inject stubs. */
mcp?: Pick<
McpServerClientOptions,
- "spawnImpl" | "fetchImpl" | "connectTimeoutMs" | "callTimeoutMs"
+ "spawnImpl" | "fetchImpl" | "connectTimeoutMs" | "callTimeoutMs" | "discoveryTimeoutMs"
>;
/**
* System-wide accelerators for plugins. The registry owns the platform's
diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.ts
index 229db1f3f..9b3e41ae0 100644
--- a/apps/desktop/electron/main/services/plugin-services.ts
+++ b/apps/desktop/electron/main/services/plugin-services.ts
@@ -41,6 +41,7 @@ import { UserMcpRuntime } from "../user-mcp";
import {
MCP_CALL_TIMEOUT_MS,
MCP_CONNECT_TIMEOUT_MS,
+ MCP_TOOL_DISCOVERY_TIMEOUT_MS,
McpServerClient,
} from "../plugin-mcp";
import { McpOAuthManager } from "../mcp-oauth";
@@ -484,6 +485,7 @@ export function createPluginServices({
oauth: mcpOAuth,
connectTimeoutMs: MCP_CONNECT_TIMEOUT_MS,
callTimeoutMs: MCP_CALL_TIMEOUT_MS,
+ discoveryTimeoutMs: MCP_TOOL_DISCOVERY_TIMEOUT_MS,
audit: (entry) => logger.app("plugin", "info", "mcp.api", entry),
log: (level, message, data) => logger.app("plugin", level, message, { data }),
});
diff --git a/apps/desktop/electron/main/user-mcp.ts b/apps/desktop/electron/main/user-mcp.ts
index f6ac9660a..6aaf08fdf 100644
--- a/apps/desktop/electron/main/user-mcp.ts
+++ b/apps/desktop/electron/main/user-mcp.ts
@@ -55,6 +55,7 @@ export type UserMcpRuntimeOptions = {
log?: (level: "info" | "warn" | "error", message: string, data?: unknown) => void;
connectTimeoutMs?: number;
callTimeoutMs?: number;
+ discoveryTimeoutMs?: number;
};
type Entry = {
@@ -388,6 +389,7 @@ export class UserMcpRuntime {
auditScope: "mcp",
connectTimeoutMs: this.options.connectTimeoutMs,
callTimeoutMs: this.options.callTimeoutMs,
+ discoveryTimeoutMs: this.options.discoveryTimeoutMs,
});
const entry: Entry = {
record,
diff --git a/apps/desktop/src/components/extensions/McpEditorSheet.tsx b/apps/desktop/src/components/extensions/McpEditorSheet.tsx
index cb9ffbccf..c663fe420 100644
--- a/apps/desktop/src/components/extensions/McpEditorSheet.tsx
+++ b/apps/desktop/src/components/extensions/McpEditorSheet.tsx
@@ -17,6 +17,15 @@ import { IconPlay, IconServer, IconTerminal, IconX } from "../icons";
import { ScopeControl } from "./ScopeControl";
import { KeyValueRows, pairsToRecord, recordToPairs, type KeyValuePair } from "./KeyValueRows";
+/**
+ * Tool names shown beside a test result.
+ *
+ * A server may advertise thousands of tools, and the joined list is one line of
+ * muted text under a count that already carries the total, so only the head of
+ * the list is worth rendering.
+ */
+const MCP_TEST_TOOL_NAME_LIMIT = 24;
+
/**
* Create/edit sheet for one user-owned MCP server.
*
@@ -471,7 +480,10 @@ export function McpEditorSheet({
: status.message || t("extensions.mcp.testFailed")}
</span>
{status.state === "ready" && status.toolNames?.length ? (
- <span className="ext-test-tools">{status.toolNames.join(" · ")}</span>
+ <span className="ext-test-tools">
+ {status.toolNames.slice(0, MCP_TEST_TOOL_NAME_LIMIT).join(" · ")}
+ {status.toolNames.length > MCP_TEST_TOOL_NAME_LIMIT ? " …" : ""}
+ </span>
) : null}
</div>
) : null}
diff --git a/apps/desktop/test/extensions-page.test.mjs b/apps/desktop/test/extensions-page.test.mjs
index 664c05bc1..574478423 100644
--- a/apps/desktop/test/extensions-page.test.mjs
+++ b/apps/desktop/test/extensions-page.test.mjs
@@ -186,6 +186,10 @@ test("MCP management reuses the modal and validates its locked id and transport
assert.match(sheet, /command\.includes\("\.\."\)/);
assert.match(sheet, /isNonLoopbackHttpMcpUrl/);
assert.match(sheet, /role="dialog" aria-modal/);
+ // A server may advertise thousands of tools, so the name row renders a bounded
+ // prefix and leaves the total to the count beside it.
+ assert.match(sheet, /MCP_TEST_TOOL_NAME_LIMIT = 24/);
+ assert.match(sheet, /slice\(0, MCP_TEST_TOOL_NAME_LIMIT\)/);
});
test("project records shadow global records before disabled records are filtered", () => {
diff --git a/apps/desktop/test/plugin-mcp.test.mjs b/apps/desktop/test/plugin-mcp.test.mjs
index da4596e25..6a868721b 100644
--- a/apps/desktop/test/plugin-mcp.test.mjs
+++ b/apps/desktop/test/plugin-mcp.test.mjs
@@ -526,3 +526,205 @@ test("mcp clients are closed when the plugin goes away", () => {
assert.match(clear, /client\.close\(\)/);
assert.match(clear, /this\.mcpClients\.delete\(pluginId\)/);
});
+
+/**
+ * A catalog stub whose size, page shape, cursor behaviour, and per-page delay
+ * come from the test, so the client's catalog guards run through real stdio
+ * framing rather than a hand-built result object.
+ */
+const CATALOG_SERVER = `
+import { writeFileSync } from "node:fs";
+if (process.env.STUB_PID_FILE) writeFileSync(process.env.STUB_PID_FILE, String(process.pid));
+const NL = String.fromCharCode(10);
+const total = Number(process.env.STUB_TOOL_COUNT ?? "0");
+const pageSize = Number(process.env.STUB_PAGE_SIZE ?? "100");
+const cursorMode = process.env.STUB_CURSOR_MODE ?? "advance";
+const pageDelayMs = Number(process.env.STUB_PAGE_DELAY_MS ?? "0");
+const send = (msg) => process.stdout.write(JSON.stringify(msg) + NL);
+let buffer = "";
+process.stdin.setEncoding("utf8");
+process.stdin.on("data", (chunk) => {
+ buffer += chunk;
+ let index = buffer.indexOf(NL);
+ while (index >= 0) {
+ const line = buffer.slice(0, index).trim();
+ buffer = buffer.slice(index + 1);
+ if (line) handle(JSON.parse(line));
+ index = buffer.indexOf(NL);
+ }
+});
+function nextCursorFor(page, start) {
+ if (cursorMode === "repeat") return "page-1";
+ if (cursorMode === "loop") return page === 1 ? "page-2" : "page-1";
+ if (cursorMode === "bogus") return 7;
+ if (cursorMode === "always") return "page-" + (page + 1);
+ return start + pageSize < total ? "page-" + (page + 1) : undefined;
+}
+function handle(msg) {
+ if (msg.method === "initialize") {
+ send({ jsonrpc: "2.0", id: msg.id, result: { protocolVersion: msg.params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "catalog", version: "1" } } });
+ return;
+ }
+ if (msg.method === "notifications/initialized") return;
+ if (msg.method === "tools/list") {
+ const cursor = msg.params && msg.params.cursor ? String(msg.params.cursor) : "";
+ const page = cursor ? Number(cursor.replace("page-", "")) : 0;
+ const start = page * pageSize;
+ const reply = () => {
+ const tools = [];
+ for (let i = start; i < Math.min(start + pageSize, total); i += 1) {
+ tools.push({ name: "tool_" + i, description: "Tool " + i, inputSchema: { type: "object", properties: {} } });
+ }
+ const nextCursor = nextCursorFor(page, start);
+ send({ jsonrpc: "2.0", id: msg.id, result: { tools, ...(nextCursor ? { nextCursor } : {}) } });
+ };
+ if (pageDelayMs > 0) setTimeout(reply, pageDelayMs);
+ else reply();
+ return;
+ }
+ if (msg.id !== undefined) send({ jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: "unknown method" } });
+}
+`;
+
+function catalogClient(t, values, extra = {}) {
+ const dir = mkdtempSync(join(tmpdir(), "pi-mcp-catalog-"));
+ writeFileSync(join(dir, "server.mjs"), CATALOG_SERVER);
+ const pidFile = join(dir, "pid");
+ const audits = [];
+ const client = new McpServerClient({
+ pluginId: "com.example.mcp",
+ rootPath: dir,
+ server: { id: "catalog", label: "Catalog", transport: "stdio", command: "node", args: ["./server.mjs"] },
+ values: { STUB_PID_FILE: pidFile, ...values },
+ audit: (entry) => audits.push(entry),
+ connectTimeoutMs: 5_000,
+ callTimeoutMs: 5_000,
+ ...extra,
+ });
+ t.after(() => client.close());
+ return { client, audits, pidFile };
+}
+
+test("a catalog larger than the old per-server cap is discovered whole", async (t) => {
+ const { client, audits } = catalogClient(t, {
+ STUB_TOOL_COUNT: "300",
+ STUB_PAGE_SIZE: "100",
+ });
+ const tools = await client.connect();
+ // The old cap dropped everything past the 64th tool of the first pages.
+ assert.equal(tools.length, 300);
+ assert.equal(tools[0].name, "tool_0");
+ assert.equal(tools[64].name, "tool_64");
+ assert.equal(tools[299].name, "tool_299");
+ assert.equal(tools[299].description, "Tool 299");
+ assert.equal(client.getTools().length, 300);
+ const connect = audits.find((entry) => entry.api === "plugin.mcp.connect");
+ assert.equal(connect.ok, true);
+ assert.equal(connect.toolCount, 300);
+ assert.equal(
+ audits.some((entry) => entry.api === "plugin.mcp.tools.truncated"),
+ false,
+ );
+});
+
+test("a catalog over the protocol ceiling refuses the server instead of truncating", async (t) => {
+ const { client, audits } = catalogClient(t, {
+ STUB_TOOL_COUNT: "2049",
+ STUB_PAGE_SIZE: "2048",
+ });
+ await assert.rejects(client.connect(), { code: "LIMIT_EXCEEDED" });
+ // A refused handshake contributes no tools at all, never a prefix.
+ assert.equal(client.isConnected(), false);
+ assert.deepEqual(client.getTools(), []);
+ const connect = audits.filter((entry) => entry.api === "plugin.mcp.connect").pop();
+ assert.equal(connect.ok, false);
+ assert.equal(connect.errorCode, "LIMIT_EXCEEDED");
+ assert.match(connect.message, /2048 tools/);
+});
+
+test("a repeated tools/list cursor refuses the server", async (t) => {
+ const { client, audits } = catalogClient(t, {
+ STUB_TOOL_COUNT: "10",
+ STUB_PAGE_SIZE: "5",
+ STUB_CURSOR_MODE: "repeat",
+ });
+ await assert.rejects(client.connect(), { code: "INVALID_RESPONSE" });
+ assert.equal(client.isConnected(), false);
+ const connect = audits.filter((entry) => entry.api === "plugin.mcp.connect").pop();
+ assert.equal(connect.ok, false);
+ assert.match(connect.message, /repeated a tools\/list cursor/);
+});
+
+test("a tools/list cursor that loops back to an earlier page refuses the server", async (t) => {
+ const { client, audits } = catalogClient(t, {
+ STUB_TOOL_COUNT: "30",
+ STUB_PAGE_SIZE: "5",
+ STUB_CURSOR_MODE: "loop",
+ });
+ await assert.rejects(client.connect(), { code: "INVALID_RESPONSE" });
+ assert.equal(client.isConnected(), false);
+ const connect = audits.filter((entry) => entry.api === "plugin.mcp.connect").pop();
+ assert.match(connect.message, /repeated a tools\/list cursor/);
+});
+
+test("a server that never stops paginating is refused at the page ceiling", async (t) => {
+ const { client, audits } = catalogClient(t, {
+ STUB_TOOL_COUNT: "1",
+ STUB_PAGE_SIZE: "1",
+ STUB_CURSOR_MODE: "always",
+ });
+ await assert.rejects(client.connect(), { code: "LIMIT_EXCEEDED" });
+ const connect = audits.filter((entry) => entry.api === "plugin.mcp.connect").pop();
+ assert.match(connect.message, /100 pages/);
+});
+
+test("a catalog that cannot be listed inside its discovery budget is refused", async (t) => {
+ // Budget already spent before the first page: the guard trips immediately.
+ const spent = catalogClient(t, { STUB_TOOL_COUNT: "10", STUB_PAGE_SIZE: "5" }, {
+ discoveryTimeoutMs: 0,
+ });
+ await assert.rejects(spent.client.connect(), { code: "TIMEOUT" });
+ assert.equal(spent.client.isConnected(), false);
+
+ // A slow catalog crosses the budget mid-traversal instead.
+ const slow = catalogClient(
+ t,
+ { STUB_TOOL_COUNT: "100", STUB_PAGE_SIZE: "10", STUB_PAGE_DELAY_MS: "40" },
+ { discoveryTimeoutMs: 45 },
+ );
+ await assert.rejects(slow.client.connect(), { code: "TIMEOUT" });
+ assert.equal(slow.client.isConnected(), false);
+});
+
+test("a catalog cursor that is not a string refuses the server", async (t) => {
+ const { client, audits } = catalogClient(t, {
+ STUB_TOOL_COUNT: "10",
+ STUB_PAGE_SIZE: "5",
+ STUB_CURSOR_MODE: "bogus",
+ });
+ // A malformed cursor must not read as "that was the last page".
+ await assert.rejects(client.connect(), { code: "INVALID_RESPONSE" });
+ assert.deepEqual(client.getTools(), []);
+ const connect = audits.filter((entry) => entry.api === "plugin.mcp.connect").pop();
+ assert.match(connect.message, /non-string tools\/list cursor/);
+});
+
+test("a refused catalog kills the stdio child instead of leaving it behind", async (t) => {
+ const { client, pidFile } = catalogClient(t, {
+ STUB_TOOL_COUNT: "10",
+ STUB_PAGE_SIZE: "5",
+ STUB_CURSOR_MODE: "repeat",
+ });
+ await assert.rejects(client.connect(), { code: "INVALID_RESPONSE" });
+ const pid = Number(readFileSync(pidFile, "utf8"));
+ assert.ok(Number.isInteger(pid) && pid > 0, "stub did not report its pid");
+ for (let attempt = 0; attempt < 100; attempt += 1) {
+ try {
+ process.kill(pid, 0);
+ } catch {
+ return;
+ }
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ assert.fail("stdio mcp child survived a refused handshake");
+});
diff --git a/apps/desktop/test/user-mcp.test.mjs b/apps/desktop/test/user-mcp.test.mjs
index bfeaa0f50..a8585023b 100644
--- a/apps/desktop/test/user-mcp.test.mjs
+++ b/apps/desktop/test/user-mcp.test.mjs
@@ -38,7 +38,12 @@ function handle(msg) {
send({
jsonrpc: "2.0",
id: msg.id,
- result: { tools: [{ name: "lookup", description: "Look something up" }, { name: "ping" }] },
+ result: {
+ tools: [{ name: "lookup", description: "Look something up" }, { name: "ping" }],
+ // A server that keeps handing back the same cursor can never be listed
+ // to its last page, so the client has to refuse it.
+ ...(process.env.STUB_REPEAT_CURSOR ? { nextCursor: "more" } : {}),
+ },
});
return;
}
@@ -446,3 +451,21 @@ test("configurationChanged separates what a server is from who may use it", () =
// Re-enabling does not invalidate anything: nothing was running.
assert.equal(configurationChanged({ ...base, enabled: false }, base), false);
});
+
+test("a server whose catalog cannot be listed lands as failed with the reason", async (t) => {
+ const dir = stubDir();
+ const rt = runtime(t);
+ rt.setRecords([stubRecord(dir, { env: { STUB_REPEAT_CURSOR: "1" } })]);
+
+ // The guard trips inside the handshake, so the server contributes nothing
+ // rather than a prefix of its catalog.
+ assert.deepEqual(await rt.toolsForProject("/repo"), []);
+ const status = rt.statusFor("stub");
+ assert.equal(status.state, "failed");
+ assert.equal(status.toolCount, 0);
+ assert.match(status.message, /repeated a tools\/list cursor/);
+
+ // A server that already failed this run is not handshaken again per session.
+ assert.deepEqual(await rt.toolsForProject("/repo"), []);
+ assert.equal(rt.statusFor("stub").state, "failed");
+});
diff --git a/docs/adr/0038-plugin-mcp-bridge.md b/docs/adr/0038-plugin-mcp-bridge.md
index de3b70ce8..ad9a11781 100644
--- a/docs/adr/0038-plugin-mcp-bridge.md
+++ b/docs/adr/0038-plugin-mcp-bridge.md
@@ -38,9 +38,12 @@ differently.
protocol `2025-06-18`: `initialize`, `tools/list`, `tools/call`. Framing is
NDJSON over stdio pipes, or streamable HTTP with SSE responses. Budgets: 10s
to complete the handshake, 100s per call (under the 110s plugin tool budget,
- itself under host-core's 120s), 8 `tools/list` pages, 4MB per stdio line, 64
- tools per server, 8 servers per plugin. Connection is lazy — declaring a
- server costs nothing until a tool is called — and teardown follows unload.
+ itself under host-core's 120s), 4MB per stdio line, 8 servers per plugin.
+ 2048 tools, 100 `tools/list` pages, 30s for the whole traversal, and a cursor
+ that repeats or is malformed — a server that breaks any bound is refused
+ instead of truncated. Connection is lazy — declaring a server costs nothing
+ until a tool is called — and teardown follows unload.
+ is called — and teardown follows unload.
4. Discovered tools register into the **existing** plugin tool map as
`plugin_<pluginIdSafe>_<serverId>_<toolName>`, so no new routing exists
anywhere between the model and the server.
@@ -60,8 +63,12 @@ differently.
agent with correct namespacing, auditing, and timeouts.
- Reviewing what a plugin can reach means reading its manifest: every endpoint
and executable is declared text, not a runtime decision.
-- The tool cap and the page cap are silent truncations by design — a server with
- 200 tools contributes 64 and logs the drop rather than flooding the prompt.
+- Catalog size is a protocol guard, not a prompt budget: a server with 300 tools
+ contributes all 300, because MCP tools reach the model as deferred on-demand
+ entries behind `ToolSearch` and only the prompt block that advertises them is
+ capped. A server that breaks a guard (count, pages, cursor, time) is refused
+ and contributes nothing, rather than flooding the prompt with a prefix of its
+ catalog.
- Because MCP tools sit in the same map as hand-written plugin tools, disabling
the plugin removes both, and a crashed plugin loses both.
- A remote server sees tool arguments. No amount of host-side care changes that;
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 96f82e04d..59646e22b 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -2502,9 +2502,9 @@ identify the platform validation still needed.
#### E2E-024K: Plugin MCP server tools reach the agent
- **Preconditions**: A plugin declaring one `stdio` and one non-loopback HTTP MCP server against trusted local-network stubs; `mcp.server.local` and `mcp.server.remote` granted; the HTTP host is listed in `net.domains`; a settings key holding the stub credential.
-- **Steps**: 1) Enable the plugin and confirm no server process starts yet. 2) Ask the agent to call a discovered tool. 3) Inspect the stub's received environment/headers. 4) Make the stub fail a call and time one out. 5) Disable the plugin.
-- **Expected**: Servers connect lazily on first use; tools appear as `plugin_demo_*_<serverId>_<tool>` at `risk: "medium"` with per-call audit; the stdio child receives only the declared `env` values plus PATH/temp/locale, never host provider keys; the non-loopback HTTP endpoint is accepted only because its host is declared, and its unencrypted transport is visible in review; a redirect to an undeclared host is blocked before the second request; failures and timeouts return tool errors without crashing the plugin or the host; disable disconnects both servers.
-- **Specs linked**: `07-plugins/02-plugin-manifest-schema.md`, `07-plugins/04-plugin-security.md` §8.1, ADR 0038, ADR 0142, D176, D281
+- **Steps**: 1) Enable the plugin and confirm no server process starts yet. 2) Ask the agent to call a discovered tool. 3) Inspect the stub's received environment/headers. 4) Make the stub fail a call and time one out. 5) Grow the stdio stub's catalog past the old 64-tool cap and re-discover it. 6) Disable the plugin.
+- **Expected**: Servers connect lazily on first use; tools appear as `plugin_demo_*_<serverId>_<tool>` at `risk: "medium"` with per-call audit; the stdio child receives only the declared `env` values plus PATH/temp/locale, never host provider keys; the non-loopback HTTP endpoint is accepted only because its host is declared, and its unencrypted transport is visible in review; a redirect to an undeclared host is blocked before the second request; failures and timeouts return tool errors without crashing the plugin or the host; a catalog larger than the old 64-tool cap arrives whole, while a server that breaks a per-server guard (count, pages, cursor, traversal time) is refused instead of contributing a prefix of its catalog; disable disconnects both servers.
+- **Specs linked**: `07-plugins/02-plugin-manifest-schema.md`, `07-plugins/04-plugin-security.md` §8.1, ADR 0038, ADR 0142, D176, D281, D452
- **Acceptance**: G (MCP bridge) + E (tools & permissions) + Security
- **Status**: Unit-covered (`plugin-mcp.test.mjs` stdio + HTTP stubs); agent-facing scenario Draft
diff --git a/docs/spec/07-plugins/04-plugin-security.md b/docs/spec/07-plugins/04-plugin-security.md
index 234bdd044..23a28de4d 100644
--- a/docs/spec/07-plugins/04-plugin-security.md
+++ b/docs/spec/07-plugins/04-plugin-security.md
@@ -270,7 +270,9 @@ registered under the same `plugin_*` namespace as hand-written plugin tools and
therefore inherit the tool timeout, the audit trail, and the per-plugin disable
switch. They are always registered at `risk: "medium"`: their schema and
description come from a third-party server, so the host cannot trust a
-self-declared risk level. At most 64 tools per server and 8 servers per plugin.
+self-declared risk level. A server's catalog is registered whole — the count is
+bounded only by the protocol guards in §8.1 — while at most 8 servers per plugin
+are admitted.
Plan is an additional host policy boundary for agent tools:
@@ -356,9 +358,14 @@ manifest did not name:
`{ "setting": "<key>" }`. The host environment is never passed through, and a
literal secret in the manifest is a review smell, not a supported pattern
(D018).
-- Connection budget: 10s to complete `initialize`, 100s per `tools/call`, 8
- `tools/list` pages, 4MB per stdio line. Servers are connected lazily and torn
- down when the plugin unloads or is disabled.
+- Connection budget: 10s to complete `initialize`, 100s per `tools/call`, 4MB
+ per stdio line. `tools/list` is followed to its last page under the per-server
+ guards of §8.1 — 2048 tools, 100 pages, a cursor that repeats or is malformed,
+ and 30s for the whole traversal — and a server that breaks one is refused
+ rather than contributing a prefix of its catalog, because MCP tools reach the
+ deferred on-demand entries behind `ToolSearch`, not as an always-present list.
+ Servers are connected lazily and torn down when the plugin unloads or is
+ disabled.
## 8.2 Desktop control and device access
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index 5daefa366..faea33eae 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -6078,3 +6078,21 @@ that was sitting at the bottom — including after the turn had finished.
the expanded sidebar at that threshold.
- Renderer only: existing `pi.desktop.sidebarWidth` preference, no IPC or native
window change. See ADR 0290 and E2E-168.
+
+## 2026-09-19 — MCP catalogs are bounded by protocol guards, not truncated (D452)
+
+- Amend D176 / ADR 0038: the per-server `tools/list` bound stops being a silent
+ truncation at 64 tools and 8 pages. The client now follows pagination to the
+ last page under Codex-parity protocol guards — 2048 tools, 100 pages, a cursor
+ that repeats or is malformed, and 30s for the whole traversal — and a server
+ that breaks one loses its handshake instead of contributing a prefix of its
+ catalog.
+- The cap was never the prompt's protection: MCP tools reach the model as
+ deferred on-demand entries behind `ToolSearch`, and the prompt block that
+ advertises them is capped independently, so a 300-tool server costs nothing
+ until one of its tools is activated.
+- `plugin.mcp.tools.truncated` is gone. A refusal is audited as
+ `plugin.mcp.connect` / `mcp.connect` with the guard's error code and message,
+ and reaches the user as the status message of a user-configured server.
+- See ADR 0038 and E2E-024K; `apps/desktop/test/plugin-mcp.test.mjs` covers the
+ whole catalog, each guard, and the old truncation as a failing baseline.
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 6050ad411..479d3ab43 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -1315,9 +1315,9 @@ unit/integration 测试;代码 pull request 使用有选择且高价值的 E2E
#### E2E-024K:插件 MCP 服务器工具到达代理
- **先决条件**:针对可信局域网存根声明一个 `stdio` 和一个非回环 HTTP MCP 服务器的插件;已授予 `mcp.server.local` 和 `mcp.server.remote`;HTTP 主机已列入 `net.domains`;保存存根凭证的设置密钥。
-- **步骤**: 1) 启用插件并确认尚未启动服务器进程。 2) 要求代理调用已发现的工具。 3) 检查存根收到的 environment/headers。 4) 使存根调用失败并超时。 5)禁用插件。
-- **预期**:服务器在首次使用时延迟连接;工具在 `risk: "medium"` 上显示为 `plugin_demo_*_<serverId>_<tool>`,并进行每次调用审核;stdio 子级仅接收声明的 `env` 值加上 PATH/temp/locale,从不接收主机提供程序密钥;非回环 HTTP 端点只有在主机列入白名单后才会接受,未加密传输会在审查中显示;跳转到未声明主机时会在第二次请求前阻止;失败和超时会返回工具错误,而不会导致插件或主机崩溃;禁用会断开两个服务器的连接。
-- **链接规格**:`07-plugins/02-plugin-manifest-schema.md`、`07-plugins/04-plugin-security.md` §8.1、ADR 0038、ADR 0142、D176、D281
+- **步骤**: 1) 启用插件并确认尚未启动服务器进程。 2) 要求代理调用已发现的工具。 3) 检查存根收到的 environment/headers。 4) 使存根调用失败并超时。 5) 让 stdio 存根的目录超过旧的 64 个工具上限并重新发现。 6) 禁用插件。
+- **预期**:服务器在首次使用时延迟连接;工具在 `risk: "medium"` 上显示为 `plugin_demo_*_<serverId>_<tool>`,并进行每次调用审核;stdio 子级仅接收声明的 `env` 值加上 PATH/temp/locale,从不接收主机提供程序密钥;非回环 HTTP 端点只有在主机列入白名单后才会接受,未加密传输会在审查中显示;跳转到未声明主机时会在第二次请求前阻止;失败和超时会返回工具错误,而不会导致插件或主机崩溃;大于旧的 64 个工具上限的目录会完整到达,而突破某项每服务器护栏(数量、页数、游标、遍历时间)的服务器会被拒绝,而不是贡献其目录的一个前缀;禁用会断开两个服务器的连接。
+- **链接规格**:`07-plugins/02-plugin-manifest-schema.md`、`07-plugins/04-plugin-security.md` §8.1、ADR 0038、ADR 0142、D176、D281、D452
- **接受**:G(MCP 桥)+ E(工具和权限)+ 安全
- **状态**:单位覆盖(`plugin-mcp.test.mjs` stdio + HTTP 存根);面向代理的场景草稿
diff --git a/docs/zh-CN/spec/07-plugins/04-plugin-security.md b/docs/zh-CN/spec/07-plugins/04-plugin-security.md
index f8f6a38bb..98b6fda66 100644
--- a/docs/zh-CN/spec/07-plugins/04-plugin-security.md
+++ b/docs/zh-CN/spec/07-plugins/04-plugin-security.md
@@ -202,7 +202,8 @@ CSS 无法脚本化,但它可能会产生误导:主题仍然是第三方代
因此继承工具超时、审计跟踪和每个插件禁用
转变。它们始终在 `risk: "medium"` 处注册:它们的架构和
描述来自第三方服务器,因此主机无法信任
-自我声明的风险水平。每个服务器最多 64 个工具,每个插件最多 8 个服务器。
+自我声明的风险水平。服务器的目录被完整注册——数量只受 §8.1 中的
+协议护栏约束——而每个插件最多接入 8 个服务器。
Plan 是代理工具的附加主机策略边界:
@@ -279,9 +280,12 @@ MCP 服务器是 `net.fetch` 旁边的第二个出口路径,因此它是声明
`{ "setting": "<key>" }`。宿主环境永远不会被穿越,并且
清单中的字面秘密是审查气味,而不是受支持的模式
(D018)。
-- 连接预算:完成 `initialize` 需要 10 秒,每个 `tools/call` 需要 100 秒,8
- `tools/list` 页,每条 stdio 线 4MB。服务器连接缓慢且撕裂
- 当插件卸载或禁用时关闭。
+- 连接预算:完成 `initialize` 需要 10 秒,每个 `tools/call` 需要 100 秒,每条
+ stdio 线 4MB。`tools/list` 在 §8.1 的每服务器护栏下跟进到最后一页
+ ——2048 个工具、100 页、重复或畸形游标、整轮遍历 30 秒——突破任一护栏的服务器会被
+ 拒绝,而不是贡献其目录的一个前缀,因为 MCP 工具是以延迟加载的按需条目
+ (`ToolSearch` 之后)而非常驻列表的形式到达模型的。服务器按需连接,
+ 并在插件卸载或禁用时关闭。
## 8.2 桌面控制与设备访问
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index 69e6ca762..a07d322f2 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -4426,3 +4426,10 @@ that amendment are retired by ADR 0268; the upstream work-panel lifecycle stays.
- 插件浮层从刻度外的 `80` 与 `60` 归回到 `z-dialog`(40)(`plugins.css`,发行说明浮层一并处理):路由表面不再困住它们之后,它们就在根堆叠上下文中参与比较,而在 80 上会盖住对话框自身弹出的叶子级弹出层(60)与 toast(50)—— 其中包括安装对话框的「已复制」提示。现在有源测试钉住这一关系。
- 仅渲染层:无 IPC、存储、schema、协议或插件 SDK 改动,也没有新增默认值。见 `04-ux/07-ui-design-system.md` §9、`apps/desktop/test/settings-dialog-overlay.test.mjs`,以及 `06-delivery/04-e2e-test-plan.md` 的 E2E-LAYOUT-three-column-width-priority(其四条浮层断言位于 `scripts/e2e-three-column-layout.mjs`)。
- 未做、留作后续的事项:真正的模态 —— 不可交互化、焦点收束、快捷键让位 —— 需要这些浮层进入浏览器顶层(`<dialog>.showModal()`)。在它们打开的弹出菜单、工具提示与 toast(portal 到 `document.body`)同样迁入顶层之前,这一步无法进行,因为顶层内容会绘制在它们之上并使其不可用;此前的一次尝试正因此被撤回。
+
+## 2026-09-19 —— MCP 目录由协议护栏约束,而不是被截断 (D452)
+
+- 修订 D176 / ADR 0038:每服务器的 `tools/list` 上限不再是「64 个工具、8 页」的静默截断。客户端现在在 Codex 同级的协议护栏下跟进分页直到最后一页 —— 2048 个工具、100 页、重复或畸形游标、整轮遍历 30 秒 —— 突破任一护栏的服务器会失去它的握手,而不是贡献其目录的一个前缀。
+- 该上限从来不是对提示词的保护:MCP 工具以 `ToolSearch` 之后的延迟按需条目到达模型,宣传它们的提示词区块另有独立上限,因此一个 300 个工具的服务器在被激活之前不产生任何成本。
+- `plugin.mcp.tools.truncated` 已移除。拒绝会以 `plugin.mcp.connect` / `mcp.connect` 记入审计并带上护栏的错误码与消息,对用户自建的服务器则显示为其状态消息。
+- 见 ADR 0038 与 E2E-024K;`apps/desktop/test/plugin-mcp.test.mjs` 覆盖完整目录、各项护栏,以及把旧的截断行为作为失败基线。