Skip to content

Commit e051a7b

Browse files
authored
fix(mcp): bound catalog pagination (#116845)
* fix(node-host): bound MCP tool pagination * fix(node-host): bound MCP catalog duration * style(node-host): format MCP pagination test * fix(mcp): share bounded pagination * fix(mcp): keep pagination types private * test(mcp): normalize abort rejection * fix(mcp): enforce pagination deadline after loading * fix(mcp): stabilize pagination deadline ownership
1 parent b2b62b2 commit e051a7b

6 files changed

Lines changed: 859 additions & 81 deletions

File tree

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

Lines changed: 157 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -75,14 +75,18 @@ async function writeListToolsMcpServer(params: {
7575
exitOnListCall?: number;
7676
listToolsMethodNotFound?: boolean;
7777
listToolsJsonRpcErrorMessage?: string;
78+
toolPageCursors?: Array<string | null>;
7879
callToolIsError?: boolean;
7980
callToolJsonRpcError?: boolean;
8081
callToolJsonRpcErrorCode?: number;
8182
callToolResult?: CallToolResult;
8283
resourcePageDelayMs?: number;
8384
resourcePageCount?: number;
85+
resourcePageCursors?: Array<string | null>;
8486
resourceListJsonRpcError?: boolean;
8587
resourceReadJsonRpcError?: boolean;
88+
promptPageDelayMs?: number;
89+
promptPageCursors?: Array<string | null>;
8690
}): Promise<void> {
8791
await writeExecutable(
8892
params.filePath,
@@ -104,6 +108,7 @@ const notifyListChangedAfterFirstList = ${params.notifyListChangedAfterFirstList
104108
const exitOnListCall = ${params.exitOnListCall ?? 0};
105109
const listToolsMethodNotFound = ${params.listToolsMethodNotFound === true};
106110
const listToolsJsonRpcErrorMessage = ${JSON.stringify(params.listToolsJsonRpcErrorMessage)};
111+
const toolPageCursors = ${JSON.stringify(params.toolPageCursors)};
107112
const tools = ${JSON.stringify(
108113
params.tools ?? [
109114
{
@@ -119,12 +124,16 @@ const callToolJsonRpcErrorCode = ${params.callToolJsonRpcErrorCode ?? -32000};
119124
const callToolResult = ${JSON.stringify(params.callToolResult)};
120125
const resourcePageDelayMs = ${params.resourcePageDelayMs ?? 0};
121126
const resourcePageCount = ${params.resourcePageCount ?? 1};
127+
const resourcePageCursors = ${JSON.stringify(params.resourcePageCursors)};
122128
const resourceListJsonRpcError = ${params.resourceListJsonRpcError === true};
123129
const resourceReadJsonRpcError = ${params.resourceReadJsonRpcError === true};
130+
const promptPageDelayMs = ${params.promptPageDelayMs ?? 0};
131+
const promptPageCursors = ${JSON.stringify(params.promptPageCursors)};
124132
125133
let buffer = "";
126134
let listCount = 0;
127135
let resourceListCount = 0;
136+
let promptListCount = 0;
128137
let pendingTimer;
129138
let keepAlive;
130139
let database;
@@ -183,6 +192,7 @@ function handle(message) {
183192
}
184193
if (message.method === "tools/list") {
185194
listCount += 1;
195+
log("tools/list cursor " + JSON.stringify(message.params?.cursor));
186196
if (listCount === exitOnListCall) {
187197
log("exit tools/list " + listCount);
188198
process.exit(1);
@@ -211,13 +221,19 @@ function handle(message) {
211221
return;
212222
}
213223
const currentListCount = listCount;
224+
const toolPageCursor = toolPageCursors?.[currentListCount - 1];
214225
log("delay tools/list " + delayMs);
215226
pendingTimer = setTimeout(() => {
216227
send({
217228
jsonrpc: "2.0",
218229
id: message.id,
219230
result: {
220-
tools,
231+
tools: toolPageCursors
232+
? tools.map((tool) => ({ ...tool, name: tool.name + "-" + currentListCount }))
233+
: tools,
234+
...(toolPageCursor !== undefined && toolPageCursor !== null
235+
? { nextCursor: toolPageCursor }
236+
: {}),
221237
},
222238
});
223239
if (notifyListChangedAfterFirstList && currentListCount === 1) {
@@ -253,6 +269,7 @@ function handle(message) {
253269
}
254270
if (message.method === "resources/list") {
255271
resourceListCount += 1;
272+
log("resources/list cursor " + JSON.stringify(message.params?.cursor));
256273
if (resourceListJsonRpcError) {
257274
send({
258275
jsonrpc: "2.0",
@@ -262,19 +279,42 @@ function handle(message) {
262279
return;
263280
}
264281
setTimeout(() => {
282+
const resourcePageCursor = resourcePageCursors?.[resourceListCount - 1];
265283
send({
266284
jsonrpc: "2.0",
267285
id: message.id,
268286
result: {
269-
resources: [],
270-
...(resourceListCount < resourcePageCount
271-
? { nextCursor: String(resourceListCount) }
272-
: {}),
287+
resources: resourcePageCursors
288+
? [{ uri: "memo://page-" + resourceListCount, name: "page-" + resourceListCount }]
289+
: [],
290+
...(resourcePageCursor !== undefined && resourcePageCursor !== null
291+
? { nextCursor: resourcePageCursor }
292+
: resourceListCount < resourcePageCount
293+
? { nextCursor: String(resourceListCount) }
294+
: {}),
273295
},
274296
});
275297
}, resourcePageDelayMs);
276298
return;
277299
}
300+
if (message.method === "prompts/list") {
301+
promptListCount += 1;
302+
log("prompts/list cursor " + JSON.stringify(message.params?.cursor));
303+
setTimeout(() => {
304+
const promptPageCursor = promptPageCursors?.[promptListCount - 1];
305+
send({
306+
jsonrpc: "2.0",
307+
id: message.id,
308+
result: {
309+
prompts: [{ name: "prompt-" + promptListCount }],
310+
...(promptPageCursor !== undefined && promptPageCursor !== null
311+
? { nextCursor: promptPageCursor }
312+
: {}),
313+
},
314+
});
315+
}, promptPageDelayMs);
316+
return;
317+
}
278318
if (message.method === "resources/read") {
279319
if (resourceReadJsonRpcError) {
280320
send({
@@ -2172,7 +2212,115 @@ process.on("SIGINT", shutdown);`,
21722212
}
21732213
});
21742214

2175-
it("gives each paginated resource request its own timeout", async () => {
2215+
it("loads tool pages after an empty opaque cursor", async () => {
2216+
const tempDir = tempDirTracker.make("bundle-mcp-tool-empty-cursor-");
2217+
const serverPath = path.join(tempDir, "tool-pages.mjs");
2218+
const logPath = path.join(tempDir, "server.log");
2219+
await writeListToolsMcpServer({
2220+
filePath: serverPath,
2221+
logPath,
2222+
toolPageCursors: ["", null],
2223+
});
2224+
const runtime = createSessionMcpRuntime({
2225+
sessionId: "session-tool-empty-cursor",
2226+
workspaceDir: "/workspace",
2227+
cfg: {
2228+
mcp: { servers: { paged: { command: process.execPath, args: [serverPath] } } },
2229+
},
2230+
});
2231+
2232+
try {
2233+
await expect(runtime.getCatalog()).resolves.toMatchObject({
2234+
tools: [{ toolName: "slow_tool-1" }, { toolName: "slow_tool-2" }],
2235+
});
2236+
await waitForFileText(logPath, 'tools/list cursor ""', LIST_TOOLS_SERVER_LOG_TIMEOUT_MS);
2237+
} finally {
2238+
await runtime.dispose();
2239+
}
2240+
});
2241+
2242+
it("isolates a cyclic tool catalog while a healthy bundle MCP sibling survives", async () => {
2243+
const tempDir = tempDirTracker.make("bundle-mcp-tool-cycle-");
2244+
const loopingPath = path.join(tempDir, "looping.mjs");
2245+
const loopingLogPath = path.join(tempDir, "looping.log");
2246+
const healthyPath = path.join(tempDir, "healthy.mjs");
2247+
const healthyLogPath = path.join(tempDir, "healthy.log");
2248+
await writeListToolsMcpServer({
2249+
filePath: loopingPath,
2250+
logPath: loopingLogPath,
2251+
toolPageCursors: ["same", "same"],
2252+
});
2253+
await writeListToolsMcpServer({ filePath: healthyPath, logPath: healthyLogPath });
2254+
const runtime = createSessionMcpRuntime({
2255+
sessionId: "session-tool-cycle",
2256+
workspaceDir: "/workspace",
2257+
cfg: {
2258+
mcp: {
2259+
servers: {
2260+
looping: { command: process.execPath, args: [loopingPath] },
2261+
healthy: { command: process.execPath, args: [healthyPath] },
2262+
},
2263+
},
2264+
},
2265+
});
2266+
2267+
try {
2268+
const catalog = await runtime.getCatalog();
2269+
expect(catalog.tools.map((tool) => `${tool.serverName}:${tool.toolName}`)).toEqual([
2270+
"healthy:slow_tool",
2271+
]);
2272+
expect(
2273+
catalog.diagnostics?.find((entry) => entry.serverName === "looping")?.message,
2274+
).toContain("repeated pagination cursor");
2275+
await waitForFileText(healthyLogPath, "recv tools/list", LIST_TOOLS_SERVER_LOG_TIMEOUT_MS);
2276+
} finally {
2277+
await runtime.dispose();
2278+
}
2279+
});
2280+
2281+
it("loads resource and prompt pages after empty opaque cursors", async () => {
2282+
const tempDir = tempDirTracker.make("bundle-mcp-utility-empty-cursor-");
2283+
const serverPath = path.join(tempDir, "utility-pages.mjs");
2284+
const logPath = path.join(tempDir, "server.log");
2285+
await writeListToolsMcpServer({
2286+
filePath: serverPath,
2287+
logPath,
2288+
capabilities: { resources: {}, prompts: {} },
2289+
listToolsMethodNotFound: true,
2290+
resourcePageCursors: ["", null],
2291+
promptPageCursors: ["", null],
2292+
});
2293+
const runtime = createSessionMcpRuntime({
2294+
sessionId: "session-utility-empty-cursor",
2295+
workspaceDir: "/workspace",
2296+
cfg: {
2297+
mcp: { servers: { paged: { command: process.execPath, args: [serverPath] } } },
2298+
},
2299+
});
2300+
2301+
try {
2302+
await runtime.getCatalog();
2303+
const listResources = runtime.listResources;
2304+
const listPrompts = runtime.listPrompts;
2305+
if (!listResources || !listPrompts) {
2306+
throw new Error("Expected test runtime to expose resource and prompt utilities");
2307+
}
2308+
await expect(listResources("paged")).resolves.toMatchObject([
2309+
{ uri: "memo://page-1" },
2310+
{ uri: "memo://page-2" },
2311+
]);
2312+
await expect(listPrompts("paged")).resolves.toMatchObject([
2313+
{ name: "prompt-1" },
2314+
{ name: "prompt-2" },
2315+
]);
2316+
await waitForFileText(logPath, 'resources/list cursor ""', LIST_TOOLS_SERVER_LOG_TIMEOUT_MS);
2317+
await waitForFileText(logPath, 'prompts/list cursor ""', LIST_TOOLS_SERVER_LOG_TIMEOUT_MS);
2318+
} finally {
2319+
await runtime.dispose();
2320+
}
2321+
});
2322+
2323+
it("bounds the complete paginated resource listing by one absolute timeout", async () => {
21762324
const tempDir = tempDirTracker.make("bundle-mcp-resource-pages-");
21772325
const serverPath = path.join(tempDir, "resource-pages.mjs");
21782326
const logPath = path.join(tempDir, "server.log");
@@ -2206,7 +2354,9 @@ process.on("SIGINT", shutdown);`,
22062354
if (!runtime.listResources) {
22072355
throw new Error("Expected test runtime to expose resource utilities");
22082356
}
2209-
await expect(runtime.listResources("paged")).resolves.toEqual([]);
2357+
await expect(runtime.listResources("paged")).rejects.toThrow(
2358+
"MCP resource listing timed out after 150ms",
2359+
);
22102360
} finally {
22112361
await runtime.dispose();
22122362
await fs.rm(tempDir, { recursive: true, force: true });

0 commit comments

Comments
 (0)