diff --git a/common/src/mcp/client.ts b/common/src/mcp/client.ts index 1c2c986fd6..9065d15daf 100644 --- a/common/src/mcp/client.ts +++ b/common/src/mcp/client.ts @@ -144,10 +144,23 @@ export async function getMCPClient(config: MCPConfig): Promise { } } - const client = new Client({ - name: 'codebuff', - version: '1.0.0', - }) + const client = new Client( + { name: 'codebuff', version: '1.0.0' }, + { + listChanged: { + tools: { + // Invalidate immediately so the next model step need not wait for + // the SDK's debounce. Our listing handles every page; autoRefresh + // would fetch only the first. Lazy reads coalesce notification bursts. + autoRefresh: false, + debounceMs: 0, + onChanged: () => { + delete listToolsCache[key] + }, + }, + }, + }, + ) try { await client.connect(transport) @@ -181,7 +194,16 @@ export function listMCPTools( throw new Error(`listTools: client not found with id: ${clientId}`) } if (!listToolsCache[clientId]) { - const listing = listAllTools(client, ...args) + const listing: ReturnType = listAllTools( + client, + ...args, + ).then((result) => + // A notification during pagination invalidates the whole snapshot. + // Readers of the old in-flight promise must join a fresh listing too. + listToolsCache[clientId] === listing + ? result + : listMCPTools(clientId, ...args), + ) listToolsCache[clientId] = listing // A failed listing is not kept, or one slow start would hide the server's tools for the rest // of the process: the next call asks the server again. diff --git a/packages/agent-runtime/src/__tests__/list-changed-server.mjs b/packages/agent-runtime/src/__tests__/list-changed-server.mjs new file mode 100644 index 0000000000..bca554df72 --- /dev/null +++ b/packages/agent-runtime/src/__tests__/list-changed-server.mjs @@ -0,0 +1,69 @@ +// Based on the dependency-free reproducer for #1696: +// https://github.com/CodebuffAI/freebuff/issues/1696#issuecomment-7060897502 +// Adds pagination, a filtered tool, and a second change that removes/updates tools. +import { createInterface } from 'node:readline' + +let phase = 0 +const tool = (name, inputSchema = { type: 'object', properties: {} }) => ({ + name, + description: name, + inputSchema, +}) +const currentTools = () => [ + ...(phase < 2 ? [tool('ping')] : []), + tool('add_tool'), + tool('hidden'), + ...(phase > 0 + ? [ + tool( + 'third_tool', + phase < 2 + ? { type: 'object', properties: {} } + : { + type: 'object', + properties: { value: { type: 'string' } }, + required: ['value'], + }, + ), + ] + : []), +] +const send = (msg) => + process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...msg }) + '\n') +const reply = (id, result) => send({ id, result }) +const changed = () => send({ method: 'notifications/tools/list_changed' }) +createInterface({ input: process.stdin, terminal: false }).on( + 'line', + (line) => { + const msg = JSON.parse(line) + switch (msg.method) { + case 'initialize': + reply(msg.id, { + protocolVersion: '2025-06-18', + capabilities: { tools: { listChanged: true } }, + serverInfo: { name: 'progressive-fixture', version: '0.0.1' }, + }) + break + case 'tools/list': { + const start = Number(msg.params?.cursor ?? 0) + const tools = currentTools() + reply(msg.id, { + tools: tools.slice(start, start + 1), + ...(start + 1 < tools.length && { nextCursor: String(start + 1) }), + }) + break + } + case 'tools/call': + if (msg.params.name === 'add_tool') { + phase = 1 + changed() + changed() + } else if (msg.params.name === 'third_tool') { + phase = 2 + changed() + } + reply(msg.id, { content: [{ type: 'text', text: 'catalog updated' }] }) + break + } + }, +) diff --git a/packages/agent-runtime/src/__tests__/mcp-list-changed.test.ts b/packages/agent-runtime/src/__tests__/mcp-list-changed.test.ts new file mode 100644 index 0000000000..f01e40e96e --- /dev/null +++ b/packages/agent-runtime/src/__tests__/mcp-list-changed.test.ts @@ -0,0 +1,118 @@ +/** + * #1696: a progressive MCP catalog must reach the next model step in one turn. + * A real Node stdio server is necessary to cover notifications and pagination; + * process startup and the runtime loop may take over a second on Windows. + */ +import { + callMCPTool, + getMCPClient, + listMCPTools, +} from '@codebuff/common/mcp/client' +import { + createTestAgentRuntimeParams, + mockFileContext, +} from '@codebuff/common/testing/fixtures/agent-runtime' +import { getInitialSessionState } from '@codebuff/common/types/session-state' +import { promptSuccess } from '@codebuff/common/util/error' +import { asSchema } from 'ai' +import { expect, mock, test } from 'bun:test' + +import { loopAgentSteps } from '../run-agent-step' +import { createToolCallChunk } from './test-utils' + +import type { AgentTemplate } from '../templates/types' +import type { PromptAiSdkStreamFn } from '@codebuff/common/types/contracts/llm' +import type { MCPConfig } from '@codebuff/common/types/mcp' + +test('replaces a notified MCP catalog before the next model request in one turn', async () => { + const config: MCPConfig = { + type: 'stdio', + command: 'node', + args: [import.meta.dir + '/list-changed-server.mjs'], + env: {}, + } + const clientId = await getMCPClient(config) + const runtime = createTestAgentRuntimeParams() + const template = { + ...runtime.agentTemplate, + instructionsPrompt: '', + toolNames: [ + 'end_turn', + 'host_tool', + 'probe/ping', + 'probe/add_tool', + 'probe/third_tool', + ], + mcpServers: { probe: config }, + } as AgentTemplate + const fileContext = { + ...mockFileContext, + customToolDefinitions: { + host_tool: { + inputSchema: { type: 'object', properties: {} }, + description: 'Host tool', + }, + }, + } + runtime.requestMcpToolData = mock(async ({ mcpConfig, toolNames }) => { + const result = await listMCPTools(await getMCPClient(mcpConfig)) + return result.tools.filter((t) => !toolNames || toolNames.includes(t.name)) + }) + runtime.requestToolCall = mock(async ({ toolName, input }) => ({ + output: await callMCPTool(clientId, { name: toolName, arguments: input }), + })) + const seen: { names: string[]; schema?: unknown }[] = [] + const stream: PromptAiSdkStreamFn = async function* ({ tools }) { + const third = tools?.probe__third_tool + seen.push({ + names: Object.keys(tools ?? {}).sort(), + schema: third ? await asSchema(third.inputSchema).jsonSchema : undefined, + }) + yield createToolCallChunk( + ['probe__add_tool', 'probe__third_tool', 'end_turn'][seen.length - 1], + {}, + ) + return promptSuccess('fixture-response') + } + runtime.promptAiSdkStream = mock(stream) + const result = await loopAgentSteps({ + ...runtime, + fileContext, + agentType: template.id, + agentTemplate: template, + localAgentTemplates: { [template.id]: template }, + agentState: { + ...getInitialSessionState(fileContext).mainAgentState, + stepsRemaining: 4, + }, + repoId: undefined, + repoUrl: undefined, + userInputId: 'fixture-input', + clientSessionId: 'fixture-session', + fingerprintId: 'fixture-fingerprint', + userId: 'fixture-user', + prompt: 'Discover and use a tool.', + spawnParams: undefined, + ancestorRunIds: [], + signal: new AbortController().signal, + }) + expect(seen.map((s) => s.names)).toEqual([ + ['end_turn', 'host_tool', 'probe__add_tool', 'probe__ping'], + [ + 'end_turn', + 'host_tool', + 'probe__add_tool', + 'probe__ping', + 'probe__third_tool', + ], + ['end_turn', 'host_tool', 'probe__add_tool', 'probe__third_tool'], + ]) + expect(seen[1].schema).toEqual({ type: 'object', properties: {} }) + expect(seen[2].schema).toEqual({ + type: 'object', + properties: { value: { type: 'string' } }, + required: ['value'], + }) + expect(result.agentState.toolDefinitions?.probe__ping).toBeUndefined() + expect(result.output.type).not.toBe('error') +}) diff --git a/packages/agent-runtime/src/run-agent-step.ts b/packages/agent-runtime/src/run-agent-step.ts index 2369b6fbc1..f7a80d67e3 100644 --- a/packages/agent-runtime/src/run-agent-step.ts +++ b/packages/agent-runtime/src/run-agent-step.ts @@ -40,7 +40,7 @@ import { userMessage, } from '@codebuff/common/util/messages' import { type ToolSet } from 'ai' -import { cloneDeep, mapValues } from 'lodash' +import { cloneDeep, isEqual, mapValues } from 'lodash' import z from 'zod/v4' import type { CompactionTrigger } from './compact-history' @@ -1328,6 +1328,15 @@ export async function loopAgentSteps( initialAgentState.runId = runId let cachedAdditionalToolDefinitions: CustomToolDefinitions | undefined + const additionalToolDefinitionsWithCache = async () => { + if (!cachedAdditionalToolDefinitions) { + cachedAdditionalToolDefinitions = await additionalToolDefinitions({ + ...params, + agentTemplate, + }) + } + return cachedAdditionalToolDefinitions + } // Use parent's tools for prompt caching when inheritParentSystemPrompt is true const useParentTools = agentTemplate.inheritParentSystemPrompt && parentTools !== undefined @@ -1340,15 +1349,7 @@ export async function loopAgentSteps( promptType: { type: 'instructionsPrompt' }, agentTemplates: localAgentTemplates, useParentTools, - additionalToolDefinitions: async () => { - if (!cachedAdditionalToolDefinitions) { - cachedAdditionalToolDefinitions = await additionalToolDefinitions({ - ...params, - agentTemplate, - }) - } - return cachedAdditionalToolDefinitions - }, + additionalToolDefinitions: additionalToolDefinitionsWithCache, }) // Build the initial message history with user prompt and instructions @@ -1364,15 +1365,7 @@ export async function loopAgentSteps( agentTemplate, promptType: { type: 'systemPrompt' }, agentTemplates: localAgentTemplates, - additionalToolDefinitions: async () => { - if (!cachedAdditionalToolDefinitions) { - cachedAdditionalToolDefinitions = await additionalToolDefinitions({ - ...params, - agentTemplate, - }) - } - return cachedAdditionalToolDefinitions - }, + additionalToolDefinitions: additionalToolDefinitionsWithCache, }) system = systemPrompt ?? '' } @@ -1386,25 +1379,17 @@ export async function loopAgentSteps( agentTemplates: localAgentTemplates, }) - const tools = useParentTools - ? parentTools - : await getToolSet({ - toolNames: agentTemplate.toolNames, - windowedFileReads: agentTemplate.windowedFileReads === true, - suppressCommitAttribution: - agentTemplate.suppressCommitAttribution === true, - additionalToolDefinitions: async () => { - if (!cachedAdditionalToolDefinitions) { - cachedAdditionalToolDefinitions = await additionalToolDefinitions({ - ...params, - agentTemplate, - }) - } - return cachedAdditionalToolDefinitions - }, - agentTools, - skills: fileContext.skills ?? {}, - }) + const buildTools = () => + getToolSet({ + toolNames: agentTemplate.toolNames, + windowedFileReads: agentTemplate.windowedFileReads === true, + suppressCommitAttribution: + agentTemplate.suppressCommitAttribution === true, + additionalToolDefinitions: additionalToolDefinitionsWithCache, + agentTools, + skills: fileContext.skills ?? {}, + }) + let tools = useParentTools ? parentTools : await buildTools() const hasUserMessage = !manualCompaction && @@ -1461,7 +1446,7 @@ export async function loopAgentSteps( // Tool definitions live in agent state (persisted, snapshotted, shipped over // the wire), so every inputSchema must be plain JSON Schema: Zod instances // are cyclic and break any JSON.stringify over the state. - const toolDefinitions = + let toolDefinitions = manualCompaction && initialAgentState.toolDefinitions ? initialAgentState.toolDefinitions : mapValues(tools, (tool) => ({ @@ -1470,16 +1455,6 @@ export async function loopAgentSteps( inputSchema: toTokenCountInputSchema(tool.inputSchema) ?? {}, })) - const additionalToolDefinitionsWithCache = async () => { - if (!cachedAdditionalToolDefinitions) { - cachedAdditionalToolDefinitions = await additionalToolDefinitions({ - ...params, - agentTemplate, - }) - } - return cachedAdditionalToolDefinitions - } - // Mutate initialAgentState so that in-progress work propagates back to the // caller's shared reference (e.g. SDK's sessionState.mainAgentState) even if // an error is thrown before we return. @@ -1499,7 +1474,7 @@ export async function loopAgentSteps( } // Estimate the wire schemas, not Zod's internal object graph. - const toolsForTokenCount = toolsForContextEstimate(toolDefinitions) + let toolsForTokenCount = toolsForContextEstimate(toolDefinitions) // Keep the persisted/displayed count aligned after cancellation and TTL edits. // Uses the latest receipt plus cheap deltas; never re-tokenizes the history. @@ -1982,6 +1957,33 @@ export async function loopAgentSteps( assertUserContentSize([userPromptMessage], agentTemplate) } + // Transport listings are cached until a list_changed notification. Read + // through that cache at each step so discovery can change this turn's + // model schemas, execution definitions and context estimate together. + if ( + totalSteps > 1 && + !useParentTools && + Object.keys(agentTemplate.mcpServers).length > 0 + ) { + const nextDefinitions = await additionalToolDefinitions({ + ...params, + agentTemplate, + }) + if (!isEqual(nextDefinitions, cachedAdditionalToolDefinitions)) { + cachedAdditionalToolDefinitions = nextDefinitions + tools = await buildTools() + toolDefinitions = mapValues(tools, (tool) => ({ + description: + typeof tool.description === 'string' + ? tool.description + : undefined, + inputSchema: toTokenCountInputSchema(tool.inputSchema) ?? {}, + })) + currentAgentState.toolDefinitions = toolDefinitions + toolsForTokenCount = toolsForContextEstimate(toolDefinitions) + } + } + const startTime = new Date() const stepPrompt = await getAgentPrompt({