Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions src/mcp/mcpClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import {
withDeadline,
withMcpSessionScope,
sanitizeInputSchema,
MAX_DISCOVERED_TOOLS,
MAX_DISCOVERED_TOOLS_PER_SERVER,
} from './mcpClient.js';
import type { ToolDefinition } from '../adapters/tools.js';

Expand Down Expand Up @@ -566,3 +568,60 @@ describe('session: scope servers (AGT-4663)', () => {
expect(registryFromConfigServers({ b: { command: 'ssh', session: 'forever' } })).toEqual({});
});
});

// AGT-4873 — a remote server's tool list is capped and de-duplicated before it
// is cached or exposed.
describe('discovery tool-count bounds', () => {
it('keeps the first of each duplicate name and caps each server', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const many = Array.from({ length: MAX_DISCOVERED_TOOLS_PER_SERVER + 50 }, (_, i) => ({
name: `t${i}`,
description: `tool ${i}`,
inputSchema: { type: 'object', properties: {} },
}));
clientMock.listTools.mockResolvedValue({
tools: [
{ name: 't0', description: 'first t0', inputSchema: { type: 'object', properties: {} } },
{ name: 't0', description: 'second t0', inputSchema: { type: 'object', properties: {} } },
...many,
],
});

const defs = await initMcpTools({ big: { transport: 'stdio', command: 'mock-mcp' } });
const names = defs.map((d) => d.function.name);

expect(defs.length).toBe(MAX_DISCOVERED_TOOLS_PER_SERVER);
expect(new Set(names).size).toBe(names.length);
expect(defs.find((d) => d.function.name === 'big__t0')?.function.description).toBe('first t0');
expect(warn.mock.calls.some(([msg]) => String(msg).includes("2 duplicate"))).toBe(true);
expect(warn.mock.calls.some(([msg]) => String(msg).includes("dropped 50"))).toBe(true);
warn.mockRestore();
});

it('caps the total across servers, trimming in registry order', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const full = Array.from({ length: MAX_DISCOVERED_TOOLS_PER_SERVER }, (_, i) => ({
name: `t${i}`,
inputSchema: { type: 'object', properties: {} },
}));
clientMock.listTools.mockResolvedValue({ tools: full });
const serverCount = Math.ceil(MAX_DISCOVERED_TOOLS / MAX_DISCOVERED_TOOLS_PER_SERVER) + 2;
const registry = Object.fromEntries(
Array.from({ length: serverCount }, (_, i) => [`s${i}`, { transport: 'stdio' as const, command: 'mock-mcp' }]),
);

const defs = await initMcpTools(registry);
const names = defs.map((d) => d.function.name);

expect(defs.length).toBe(MAX_DISCOVERED_TOOLS);
expect(new Set(names).size).toBe(names.length);
// The last server is the one trimmed, regardless of response order.
expect(names.some((n) => n.startsWith(`s${serverCount - 1}__`))).toBe(false);
expect(await callMcpTool(`s${serverCount - 1}__t0`, {})).toEqual({
content: `MCP tool not registered: s${serverCount - 1}__t0`,
isError: true,
});
expect(warn.mock.calls.some(([msg]) => String(msg).includes(`exceeded ${MAX_DISCOVERED_TOOLS}`))).toBe(true);
warn.mockRestore();
});
});
69 changes: 57 additions & 12 deletions src/mcp/mcpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ const MCP_OPERATION_TIMEOUT_MS = 30_000;
const MAX_INPUT_SCHEMA_BYTES = 16_384;
const MAX_INPUT_SCHEMA_PROPERTIES = 64;
const EMPTY_INPUT_SCHEMA: Record<string, unknown> = { type: 'object', properties: {} };
/**
* Bound how many remote tools discovery may cache (AGT-4873). One server that
* lists thousands of tools would otherwise be cached and exposed whole.
*/
export const MAX_DISCOVERED_TOOLS_PER_SERVER = 256;
export const MAX_DISCOVERED_TOOLS = 1024;

interface ServerConfig {
transport: 'stdio' | 'http' | 'sse';
Expand Down Expand Up @@ -430,23 +436,38 @@ interface DiscoveryResult {
* earlier, for as long as rediscovery took.
*/
async function discoverMcpTools(registry: Record<string, ServerConfig>): Promise<DiscoveryResult> {
const defs: ToolDefinition[] = [];
const routing: Record<string, McpToolRoute> = {};
const unreachable: string[] = [];
const entries = Object.entries(registry);
// Per-server results kept in registry order so the global cap below trims
// deterministically, whichever server answers first.
const perServer: Array<Array<{ definition: ToolDefinition; route: McpToolRoute }>> = entries.map(() => []);
let next = 0;
const worker = async (): Promise<void> => {
while (next < entries.length) {
const [server, cfg] = entries[next++];
const index = next++;
const [server, cfg] = entries[index];
try {
const listed = (await withClient(cfg, (c) => c.listTools())) as { tools?: McpTool[] };
for (const tool of listed.tools ?? []) {
if (typeof tool.name !== 'string') continue;
const seen = new Set<string>();
let duplicates = 0;
let overCap = 0;
for (const tool of Array.isArray(listed.tools) ? listed.tools : []) {
if (typeof tool?.name !== 'string') continue;
const qualified = `${server}${SEP}${tool.name}`;
if (!isMcpTool(qualified)) {
console.warn(`[MCP] server "${server}" returned invalid tool name "${tool.name}" — skipped`);
continue;
}
// Same name twice: keep the first, drop the rest.
if (seen.has(qualified)) {
duplicates++;
continue;
}
if (seen.size >= MAX_DISCOVERED_TOOLS_PER_SERVER) {
overCap++;
continue;
}
seen.add(qualified);
const definition: ToolDefinition = {
type: 'function',
function: {
Expand All @@ -463,13 +484,18 @@ async function discoverMcpTools(registry: Record<string, ServerConfig>): Promise
serverIdentityHints: [cfg.url ?? '', cfg.command ?? '', ...(cfg.args ?? [])].filter(Boolean),
annotations: tool.annotations,
});
routing[qualified] = {
cfg,
toolName: tool.name,
policy,
inputSchema: definition.function.parameters,
};
defs.push(definition);
perServer[index].push({
definition,
route: { cfg, toolName: tool.name, policy, inputSchema: definition.function.parameters },
});
}
if (duplicates > 0) {
console.warn(`[MCP] server "${server}" returned ${duplicates} duplicate tool name(s) — kept the first of each`);
}
if (overCap > 0) {
console.warn(
`[MCP] server "${server}" returned more than ${MAX_DISCOVERED_TOOLS_PER_SERVER} tools — dropped ${overCap}`,
);
}
} catch (err) {
unreachable.push(server);
Expand All @@ -478,6 +504,25 @@ async function discoverMcpTools(registry: Record<string, ServerConfig>): Promise
}
};
await Promise.all(Array.from({ length: Math.min(4, entries.length) }, () => worker()));

const defs: ToolDefinition[] = [];
const routing: Record<string, McpToolRoute> = {};
let droppedTotal = 0;
for (const tools of perServer) {
for (const { definition, route } of tools) {
const name = definition.function.name;
if (routing[name]) continue;
if (defs.length >= MAX_DISCOVERED_TOOLS) {
droppedTotal++;
continue;
}
routing[name] = route;
defs.push(definition);
}
}
if (droppedTotal > 0) {
console.warn(`[MCP] discovery exceeded ${MAX_DISCOVERED_TOOLS} tools in total — dropped ${droppedTotal}`);
}
return { defs, routing, unreachable };
}

Expand Down
Loading