Skip to content

Commit 1cf8ea4

Browse files
authored
fix(mcp): prevent stale catalogs and silent tool failures (#125564)
* fix(mcp): harden lifecycle and result integrity * fix(mcp): bound catalog invalidation replay * test(mcp): stabilize process cleanup proof
1 parent 0776c46 commit 1cf8ea4

26 files changed

Lines changed: 1699 additions & 305 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1683,7 +1683,7 @@ src/agents/agent-bundle-lsp-runtime.ts 4
16831683
src/agents/agent-bundle-mcp-combined.ts 2
16841684
src/agents/agent-bundle-mcp-manager-api.ts 2
16851685
src/agents/agent-bundle-mcp-manager-lifecycle.ts 1
1686-
src/agents/agent-bundle-mcp-materialize.ts 4
1686+
src/agents/agent-bundle-mcp-materialize.ts 3
16871687
src/agents/agent-bundle-mcp-runtime-shared.ts 2
16881688
src/agents/agent-bundle-mcp-runtime.ts 9
16891689
src/agents/agent-command-restart-recovery.ts 4

‎src/agents/agent-bundle-mcp-materialize.ts‎

Lines changed: 3 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import type {
2020
McpToolCatalog,
2121
SessionMcpRuntime,
2222
} from "./agent-bundle-mcp-types.js";
23-
import { projectMcpCallToolResultContent } from "./mcp-content.js";
23+
import { projectMcpCallToolResult } from "./mcp-content.js";
2424
import { isMcpToolAllowed } from "./mcp-tool-filter.js";
2525
import { buildMcpAppCanvasPayload, fetchMcpAppView } from "./mcp-ui-resource.js";
2626
import type { AgentToolResult } from "./runtime/index.js";
@@ -100,38 +100,10 @@ function toAgentToolResult(params: {
100100
toolName: string;
101101
result: CallToolResult;
102102
}): AgentToolResult<unknown> {
103-
const content = projectMcpCallToolResultContent(params.result);
104-
const normalizedContent: AgentToolResult<unknown>["content"] =
105-
content.length > 0
106-
? content
107-
: ([
108-
{
109-
type: "text",
110-
text: JSON.stringify(
111-
{
112-
status: params.result.isError === true ? "error" : "ok",
113-
server: params.serverName,
114-
tool: params.toolName,
115-
},
116-
null,
117-
2,
118-
),
119-
},
120-
] as AgentToolResult<unknown>["content"]);
121-
const details: Record<string, unknown> = {
103+
return projectMcpCallToolResult(params.result, {
122104
mcpServer: params.serverName,
123105
mcpTool: params.toolName,
124-
};
125-
if (params.result.structuredContent !== undefined) {
126-
details.structuredContent = params.result.structuredContent;
127-
}
128-
if (params.result.isError === true) {
129-
details.status = "error";
130-
}
131-
return {
132-
content: normalizedContent,
133-
details,
134-
};
106+
});
135107
}
136108

137109
function toJsonAgentToolResult(params: {

‎src/agents/agent-bundle-mcp-runtime.test.ts‎

Lines changed: 147 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,8 @@ async function writeListToolsMcpServer(params: {
9393
name: string;
9494
description?: string;
9595
inputSchema?: unknown;
96+
outputSchema?: unknown;
97+
execution?: { taskSupport?: "forbidden" | "optional" | "required" };
9698
_meta?: Record<string, unknown>;
9799
}>;
98100
capabilities?: Record<string, unknown>;
@@ -101,6 +103,7 @@ async function writeListToolsMcpServer(params: {
101103
hangToolCallsUntilRestartMarkerPath?: string;
102104
notifyListChangedOnInitialized?: boolean;
103105
notifyListChangedAfterFirstList?: boolean;
106+
notifyListChangedBeforeEveryListResponse?: boolean;
104107
exitOnListCall?: number;
105108
listToolsMethodNotFound?: boolean;
106109
listToolsJsonRpcErrorMessage?: string;
@@ -137,6 +140,7 @@ const hangToolCallsUntilRestartMarkerPath = ${JSON.stringify(
137140
)};
138141
const notifyListChangedOnInitialized = ${params.notifyListChangedOnInitialized === true};
139142
const notifyListChangedAfterFirstList = ${params.notifyListChangedAfterFirstList === true};
143+
const notifyListChangedBeforeEveryListResponse = ${params.notifyListChangedBeforeEveryListResponse === true};
140144
const exitOnListCall = ${params.exitOnListCall ?? 0};
141145
const listToolsMethodNotFound = ${params.listToolsMethodNotFound === true};
142146
const listToolsJsonRpcErrorMessage = ${JSON.stringify(params.listToolsJsonRpcErrorMessage)};
@@ -257,6 +261,10 @@ function handle(message) {
257261
const toolPageCursor = toolPageCursors?.[currentListCount - 1];
258262
log("delay tools/list " + delayMs);
259263
const sendListResponse = () => {
264+
if (notifyListChangedBeforeEveryListResponse) {
265+
log("notify tools/list_changed before response");
266+
send({ jsonrpc: "2.0", method: "notifications/tools/list_changed" });
267+
}
260268
send({
261269
jsonrpc: "2.0",
262270
id: message.id,
@@ -1180,7 +1188,7 @@ describe("session MCP runtime", () => {
11801188
const diagnostic = catalog.diagnostics?.[0];
11811189
expect(diagnostic?.serverName).toBe("diagnostic");
11821190
expect(diagnostic?.message).toContain("Authorization: Bearer ");
1183-
expect(diagnostic?.message).toContain("…");
1191+
expect(diagnostic?.message).toContain("***");
11841192
expect(diagnostic?.message).not.toContain(secret);
11851193
} finally {
11861194
await runtime.dispose();
@@ -1754,7 +1762,7 @@ process.on("SIGINT", shutdown);`,
17541762
LIST_TOOLS_SERVER_LOG_TIMEOUT_MS,
17551763
);
17561764
await expect(runtime.callTool("child", "slow_tool", {})).rejects.toThrow("is not connected");
1757-
await waitForFileTextCount(logPath, "recv tools/list", 2, LIST_TOOLS_SERVER_LOG_TIMEOUT_MS);
1765+
await waitForFileTextCount(logPath, "recv tools/list", 2, LIST_TOOLS_TEST_DEADLINE_MS);
17581766
await expect(
17591767
withTestTimeout(
17601768
runtime.callTool("healthy", "slow_tool", {}),
@@ -1772,13 +1780,9 @@ process.on("SIGINT", shutdown);`,
17721780
}
17731781
},
17741782
"child server to reconnect",
1775-
LIST_TOOLS_SERVER_LOG_TIMEOUT_MS,
1776-
);
1777-
const replacementPid = await waitForChangedPid(
1778-
pidPath,
1779-
pid,
1780-
LIST_TOOLS_SERVER_LOG_TIMEOUT_MS,
1783+
LIST_TOOLS_TEST_DEADLINE_MS,
17811784
);
1785+
const replacementPid = await waitForChangedPid(pidPath, pid, LIST_TOOLS_TEST_DEADLINE_MS);
17821786
expect(replacementPid).not.toBe(pid);
17831787
} finally {
17841788
await runtime.dispose();
@@ -1821,11 +1825,10 @@ process.on("SIGINT", shutdown);`,
18211825
);
18221826

18231827
const refreshedCatalog = await runtime.getCatalog();
1824-
expect(refreshedCatalog.tools).toEqual([]);
1825-
expect(refreshedCatalog.diagnostics?.[0]?.serverName).toBe("child");
1826-
// The refresh reports the exited server, but the runtime does not stay stuck on it:
1827-
// the closed transport invalidated the catalog, so the next request rebuilds against
1828-
// a fresh child instead of failing with "is not connected" indefinitely.
1828+
expect(refreshedCatalog.tools.map((tool) => tool.toolName)).toEqual(["slow_tool"]);
1829+
expect(refreshedCatalog.diagnostics ?? []).toEqual([]);
1830+
// The failed refresh is retired before catalog loading returns, so callers
1831+
// see only the replacement generation and never receive its stale diagnostic.
18291832
await expect(runtime.callTool("child", "slow_tool", {})).resolves.toMatchObject({
18301833
isError: false,
18311834
});
@@ -1934,9 +1937,9 @@ process.on("SIGINT", shutdown);`,
19341937

19351938
try {
19361939
const firstCatalog = await runtime.getCatalog();
1937-
expect(firstCatalog.tools.map((tool) => tool.toolName)).toEqual(["old_tool"]);
1940+
expect(firstCatalog.tools.map((tool) => tool.toolName)).toEqual(["new_tool"]);
19381941
await waitForFileText(logPath, "sent tools/list_changed", LIST_TOOLS_SERVER_LOG_TIMEOUT_MS);
1939-
expect(runtime.peekCatalog()).toBeNull();
1942+
expect(runtime.peekCatalog()?.tools.map((tool) => tool.toolName)).toEqual(["new_tool"]);
19401943

19411944
const secondCatalog = await runtime.getCatalog();
19421945
expect(secondCatalog.tools.map((tool) => tool.toolName)).toEqual(["new_tool"]);
@@ -1947,6 +1950,57 @@ process.on("SIGINT", shutdown);`,
19471950
}
19481951
});
19491952

1953+
it("bounds catalog replay when a server invalidates every tools/list response", async () => {
1954+
const tempDir = tempDirTracker.make("bundle-mcp-continuous-invalidation-");
1955+
const noisyServerPath = path.join(tempDir, "noisy-server.mjs");
1956+
const noisyLogPath = path.join(tempDir, "noisy-server.log");
1957+
const healthyServerPath = path.join(tempDir, "healthy-server.mjs");
1958+
const healthyLogPath = path.join(tempDir, "healthy-server.log");
1959+
await writeListToolsMcpServer({
1960+
filePath: noisyServerPath,
1961+
logPath: noisyLogPath,
1962+
capabilities: { tools: { listChanged: true } },
1963+
tools: [{ name: "noisy_tool", inputSchema: { type: "object", properties: {} } }],
1964+
notifyListChangedBeforeEveryListResponse: true,
1965+
});
1966+
await writeListToolsMcpServer({
1967+
filePath: healthyServerPath,
1968+
logPath: healthyLogPath,
1969+
tools: [{ name: "healthy_tool", inputSchema: { type: "object", properties: {} } }],
1970+
});
1971+
1972+
const runtime = await getOrCreateSessionMcpRuntime({
1973+
sessionId: "session-continuous-invalidation",
1974+
sessionKey: "agent:test:session-continuous-invalidation",
1975+
workspaceDir: "/workspace",
1976+
cfg: {
1977+
mcp: {
1978+
servers: {
1979+
noisy: { command: process.execPath, args: [noisyServerPath] },
1980+
healthy: { command: process.execPath, args: [healthyServerPath] },
1981+
},
1982+
},
1983+
},
1984+
});
1985+
1986+
try {
1987+
const catalog = await withTestTimeout(
1988+
runtime.getCatalog(),
1989+
LIST_TOOLS_SERVER_LOG_TIMEOUT_MS,
1990+
"continuous tools/list invalidation blocked the catalog",
1991+
);
1992+
1993+
expect(catalog.tools.map((tool) => tool.toolName).toSorted()).toEqual([
1994+
"healthy_tool",
1995+
"noisy_tool",
1996+
]);
1997+
const noisyLog = await fs.readFile(noisyLogPath, "utf8");
1998+
expect(noisyLog.match(/tools\/list cursor/g)).toHaveLength(2);
1999+
} finally {
2000+
await runtime.dispose();
2001+
}
2002+
});
2003+
19502004
it.each([
19512005
{
19522006
name: "resource-only servers reporting method not found",
@@ -2281,7 +2335,7 @@ process.on("SIGINT", shutdown);`,
22812335
hanging: {
22822336
command: process.execPath,
22832337
args: [serverPath],
2284-
requestTimeoutMs: 25,
2338+
requestTimeoutMs: 500,
22852339
},
22862340
},
22872341
},
@@ -2312,9 +2366,9 @@ process.on("SIGINT", shutdown);`,
23122366
}
23132367
},
23142368
"timed-out server to recover without stale backoff",
2315-
LIST_TOOLS_SERVER_LOG_TIMEOUT_MS,
2369+
LIST_TOOLS_TEST_DEADLINE_MS,
23162370
);
2317-
expect(await waitForChangedPid(pidPath, pid, LIST_TOOLS_SERVER_LOG_TIMEOUT_MS)).not.toBe(pid);
2371+
expect(await waitForChangedPid(pidPath, pid, LIST_TOOLS_TEST_DEADLINE_MS)).not.toBe(pid);
23182372
} finally {
23192373
await runtime.dispose();
23202374
await fs.rm(tempDir, { recursive: true, force: true });
@@ -2348,6 +2402,55 @@ process.on("SIGINT", shutdown);`,
23482402
}
23492403
});
23502404

2405+
it("retains paginated output metadata and hides required-task tools", async () => {
2406+
const tempDir = tempDirTracker.make("bundle-mcp-tool-metadata-pages-");
2407+
const serverPath = path.join(tempDir, "tool-pages.mjs");
2408+
const logPath = path.join(tempDir, "server.log");
2409+
await writeListToolsMcpServer({
2410+
filePath: serverPath,
2411+
logPath,
2412+
toolPageCursors: ["page-2", null],
2413+
tools: [
2414+
{
2415+
name: "structured",
2416+
inputSchema: { type: "object", properties: {} },
2417+
outputSchema: {
2418+
type: "object",
2419+
properties: { count: { type: "number" } },
2420+
required: ["count"],
2421+
additionalProperties: false,
2422+
},
2423+
},
2424+
{
2425+
name: "task_only",
2426+
inputSchema: { type: "object", properties: {} },
2427+
execution: { taskSupport: "required" },
2428+
},
2429+
],
2430+
callToolResult: {
2431+
content: [{ type: "text", text: "invalid" }],
2432+
structuredContent: { count: "not-a-number" },
2433+
},
2434+
});
2435+
const runtime = createSessionMcpRuntime({
2436+
sessionId: "session-tool-metadata-pages",
2437+
workspaceDir: "/workspace",
2438+
cfg: {
2439+
mcp: { servers: { paged: { command: process.execPath, args: [serverPath] } } },
2440+
},
2441+
});
2442+
2443+
try {
2444+
const catalog = await runtime.getCatalog();
2445+
expect(catalog.tools.map((tool) => tool.toolName)).toEqual(["structured-1", "structured-2"]);
2446+
await expect(runtime.callTool("paged", "structured-1", {})).rejects.toThrow(
2447+
"does not match the tool's output schema",
2448+
);
2449+
} finally {
2450+
await runtime.dispose();
2451+
}
2452+
});
2453+
23512454
it("isolates a cyclic tool catalog while a healthy bundle MCP sibling survives", async () => {
23522455
const tempDir = tempDirTracker.make("bundle-mcp-tool-cycle-");
23532456
const loopingPath = path.join(tempDir, "looping.mjs");
@@ -5669,15 +5772,15 @@ function log(line) {
56695772
function send(message) {
56705773
process.stdout.write(JSON.stringify(message) + "\\n");
56715774
}
5672-
async function isFirstConnect() {
5775+
async function claimFirstConnect() {
56735776
try {
5674-
const handle = await fs.open(markerPath, "wx");
5675-
await handle.close();
5777+
await fs.writeFile(markerPath, String(process.pid), { flag: "wx" });
56765778
return true;
56775779
} catch {
56785780
return false;
56795781
}
56805782
}
5783+
const firstConnect = await claimFirstConnect();
56815784
async function handle(message) {
56825785
if (!message || typeof message !== "object") {
56835786
return;
@@ -5693,7 +5796,7 @@ async function handle(message) {
56935796
serverInfo: { name: "timeout-slow", version: "1.0.0" },
56945797
},
56955798
};
5696-
if (await isFirstConnect()) {
5799+
if (firstConnect) {
56975800
log("slow first initialize");
56985801
return;
56995802
}
@@ -5749,7 +5852,7 @@ process.on("SIGINT", shutdown);`,
57495852
slow: {
57505853
command: process.execPath,
57515854
args: [slowServerPath],
5752-
connectionTimeoutMs: 150,
5855+
connectionTimeoutMs: 1_000,
57535856
},
57545857
},
57555858
},
@@ -5758,6 +5861,8 @@ process.on("SIGINT", shutdown);`,
57585861

57595862
try {
57605863
const firstCatalog = runtime.getCatalog();
5864+
await waitForFileText(firstConnectMarkerPath, "", LIST_TOOLS_SERVER_LOG_TIMEOUT_MS);
5865+
const firstSlowPid = Number(await fs.readFile(firstConnectMarkerPath, "utf8"));
57615866
await waitForFileText(
57625867
triggerLogPath,
57635868
"sent initial tools/list_changed",
@@ -5770,23 +5875,23 @@ process.on("SIGINT", shutdown);`,
57705875
secondCatalogPromise,
57715876
]);
57725877

5773-
const firstSlowDiagnostic = firstCatalogResult.diagnostics?.find(
5774-
(diag) => diag.serverName === "slow",
5775-
);
5776-
expect(firstSlowDiagnostic?.message).toContain("timed out");
5777-
expect(firstCatalogResult.servers.slow).toBeUndefined();
5878+
// The notification refresh is serialized after the timed-out first generation,
5879+
// so callers now receive the newest clean catalog rather than its stale diagnostic.
5880+
expect(firstCatalogResult.servers.slow).toBeDefined();
57785881
expect(secondCatalog.servers.trigger).toBeDefined();
5779-
const secondSlowDiagnostic = secondCatalog.diagnostics?.find(
5780-
(diag) => diag.serverName === "slow",
5882+
expect(secondCatalog.servers.slow).toBeDefined();
5883+
await waitForPredicate(
5884+
() => {
5885+
try {
5886+
process.kill(firstSlowPid, 0);
5887+
return false;
5888+
} catch (error) {
5889+
return (error as NodeJS.ErrnoException).code === "ESRCH";
5890+
}
5891+
},
5892+
"timed-out first MCP generation to exit",
5893+
LIST_TOOLS_SERVER_LOG_TIMEOUT_MS,
57815894
);
5782-
// A loaded runner can let generation one retire the timed-out client before
5783-
// generation two adopts it. Both the shared timeout and fast replacement are valid.
5784-
if (secondSlowDiagnostic) {
5785-
expect(secondSlowDiagnostic.message).toContain("timed out");
5786-
expect(secondCatalog.servers.slow).toBeUndefined();
5787-
} else {
5788-
expect(secondCatalog.servers.slow).toBeDefined();
5789-
}
57905895
await expect(runtime.callTool("trigger", "poke", {})).resolves.toMatchObject({
57915896
content: [{ type: "text", text: "poked" }],
57925897
isError: false,
@@ -5822,8 +5927,8 @@ process.on("SIGINT", shutdown);`,
58225927
);
58235928

58245929
it(
5825-
"does not dispose sessions shared with a newer catalog generation",
5826-
{ timeout: LIST_TOOLS_TEST_DEADLINE_MS },
5930+
"serializes invalidated catalog generations on one session",
5931+
{ timeout: LIST_TOOLS_TEST_DEADLINE_MS * 2 },
58275932
async () => {
58285933
const tempDir = makeTempDir(tempDirs, "bundle-mcp-overlap-generation-");
58295934
const serverPath = path.join(tempDir, "overlap-server.mjs");
@@ -5945,7 +6050,8 @@ process.on("SIGINT", shutdown);`,
59456050
const secondCatalog = await runtime.getCatalog();
59466051
const firstCatalogResult = await firstCatalog;
59476052

5948-
expect(firstCatalogResult.diagnostics?.[0]?.serverName).toBe("overlap");
6053+
expect(firstCatalogResult.diagnostics ?? []).toEqual([]);
6054+
expect(firstCatalogResult.tools.map((tool) => tool.toolName)).toEqual(["ok_tool"]);
59496055
expect(secondCatalog.diagnostics ?? []).toEqual([]);
59506056
expect(secondCatalog.tools.map((tool) => tool.toolName)).toEqual(["ok_tool"]);
59516057

0 commit comments

Comments
 (0)