diff --git a/apps/vscode-e2e/src/fixtures/mcp-dynamic-load.ts b/apps/vscode-e2e/src/fixtures/mcp-dynamic-load.ts new file mode 100644 index 00000000000..39c2105ce91 --- /dev/null +++ b/apps/vscode-e2e/src/fixtures/mcp-dynamic-load.ts @@ -0,0 +1,38 @@ +import { LLMock } from "@copilotkit/aimock" + +import { + DYNAMIC_LOAD_CALL_IDS as ids, + DYNAMIC_LOAD_MARKERS as markers, + DYNAMIC_LOAD_QUERY, +} from "../suite/tools/fixtures/mcp-catalog" +import { toolResultContains } from "./tool-result" + +const complete = (id: string, result: string) => ({ + toolCalls: [{ name: "attempt_completion", arguments: JSON.stringify({ result }), id }], +}) + +// The resumed request still holds the load result, so its fixture comes before the load-result fixture. +export function addMcpDynamicLoadFixtures(mock: InstanceType) { + mock.addFixture({ + match: { userMessage: markers.resumed }, + response: complete(ids.resumedDone, "Listed the tickets again."), + }) + mock.addFixture({ + match: { userMessage: markers.ungated }, + response: complete(ids.ungatedDone, "Listed the tickets without dynamic loading."), + }) + mock.addFixture({ + match: { userMessage: markers.gated }, + response: { + toolCalls: [{ name: "mcp_load", arguments: JSON.stringify({ query: DYNAMIC_LOAD_QUERY }), id: ids.load }], + }, + }) + mock.addFixture({ + match: { + predicate: (req) => + toolResultContains(req, ids.load, []) && + req.messages.filter((message) => message.role === "tool").at(-1)?.tool_call_id === ids.load, + }, + response: complete(ids.loadDone, "Loaded the Jira search tool."), + }) +} diff --git a/apps/vscode-e2e/src/runTest.ts b/apps/vscode-e2e/src/runTest.ts index b9f49f48b3c..007fc5c1b4e 100644 --- a/apps/vscode-e2e/src/runTest.ts +++ b/apps/vscode-e2e/src/runTest.ts @@ -21,6 +21,7 @@ import { addReadFileResultFixtures } from "./fixtures/read-file" import { addSearchFilesResultFixtures } from "./fixtures/search-files" import { addSubtaskFixtures } from "./fixtures/subtasks" import { addUseMcpToolResultFixtures } from "./fixtures/use-mcp-tool" +import { addMcpDynamicLoadFixtures } from "./fixtures/mcp-dynamic-load" import { addWriteToFileResultFixtures } from "./fixtures/write-to-file" import { createScenarioWorkspace, @@ -155,6 +156,7 @@ async function main() { addSearchFilesResultFixtures(mock) addSubtaskFixtures(mock) addUseMcpToolResultFixtures(mock) + addMcpDynamicLoadFixtures(mock) addWriteToFileResultFixtures(mock) addDeepSeekV4Fixtures(mock) diff --git a/apps/vscode-e2e/src/suite/tools/fixtures/catalog-mcp-server.ts b/apps/vscode-e2e/src/suite/tools/fixtures/catalog-mcp-server.ts new file mode 100644 index 00000000000..897d313ae19 --- /dev/null +++ b/apps/vscode-e2e/src/suite/tools/fixtures/catalog-mcp-server.ts @@ -0,0 +1,58 @@ +import * as fs from "fs/promises" +import * as path from "path" +import { stdin, stdout, stderr } from "process" + +import { catalogTools } from "./mcp-catalog" + +type JsonRpcMessage = { jsonrpc: "2.0"; id?: string | number; method?: string; params?: { name?: string } } + +const readyFile = process.env.MCP_TEST_READY_FILE +let buffer = "" + +stdin.setEncoding("utf8") +stdin.on("data", (chunk) => { + buffer += chunk + let newlineIndex = buffer.indexOf("\n") + while (newlineIndex !== -1) { + const line = buffer.slice(0, newlineIndex).trim() + buffer = buffer.slice(newlineIndex + 1) + if (line) handleMessage(JSON.parse(line) as JsonRpcMessage).catch((error) => stderr.write(`${error}\n`)) + newlineIndex = buffer.indexOf("\n") + } +}) + +async function handleMessage(message: JsonRpcMessage) { + if (message.id === undefined) return + switch (message.method) { + case "initialize": + return send(message.id, { + protocolVersion: "2024-11-05", + capabilities: { tools: {} }, + serverInfo: { name: "test-catalog-server", version: "1.0.0" }, + }) + case "tools/list": + if (readyFile) { + await fs.mkdir(path.dirname(readyFile), { recursive: true }) + await fs.writeFile(readyFile, "ready") + } + return send(message.id, { + tools: catalogTools.map(({ name, description }) => ({ + name, + description, + inputSchema: { type: "object", properties: {} }, + })), + }) + case "resources/list": + return send(message.id, { resources: [] }) + case "resources/templates/list": + return send(message.id, { resourceTemplates: [] }) + case "tools/call": + return send(message.id, { content: [{ type: "text", text: `called ${message.params?.name}` }] }) + default: + return send(message.id, {}) + } +} + +function send(id: string | number, result: unknown) { + stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id, result })}\n`) +} diff --git a/apps/vscode-e2e/src/suite/tools/fixtures/mcp-catalog.ts b/apps/vscode-e2e/src/suite/tools/fixtures/mcp-catalog.ts new file mode 100644 index 00000000000..51900599428 --- /dev/null +++ b/apps/vscode-e2e/src/suite/tools/fixtures/mcp-catalog.ts @@ -0,0 +1,42 @@ +export const CATALOG_SERVER_NAME = "catalog" + +// Two topics. As in the production catalog, short Jira tools mention jira_search_tickets, whose own +// description is long. Without a name weight, they outrank it. +export const catalogTools = [ + { + name: "jira_search_tickets", + description: + "Run a JQL query and return the matching issues with the requested fields. Page with next_page_token until is_last is true, and keep the query, the fields and max_results the same between pages. Restricted projects are left out and named in a note. An unknown project, status or issue type comes back as an error.", + }, + { name: "jira_count_tickets", description: "Count Jira tickets on a board instead of paging jira_search_tickets." }, + { + name: "jira_get_board", + description: "Get a Jira board with ticket counts. To list tickets, use jira_search_tickets.", + }, + { name: "jira_find_users", description: "Find Jira users for jira_search_tickets assignee filters." }, + { name: "slack_send_message", description: "Send a Slack message to a channel." }, + { name: "slack_add_reaction", description: "Add an emoji reaction to a Slack message." }, +] + +export const catalogToolName = (name: string) => `mcp--${CATALOG_SERVER_NAME}--${name}` + +export const DYNAMIC_LOAD_MARKERS = { + gated: "MCP_DYNAMIC_LOAD_GATED", + ungated: "MCP_DYNAMIC_LOAD_UNGATED", + resumed: "MCP_DYNAMIC_LOAD_RESUMED", +} + +export const DYNAMIC_LOAD_PROMPTS = { + gated: `${DYNAMIC_LOAD_MARKERS.gated}: count the jira tickets on the board`, + ungated: `${DYNAMIC_LOAD_MARKERS.ungated}: list my jira tickets`, + resumed: `${DYNAMIC_LOAD_MARKERS.resumed}: list them again`, +} + +export const DYNAMIC_LOAD_CALL_IDS = { + load: "call_mcp_dynamic_load_load_001", + loadDone: "call_mcp_dynamic_load_load_002", + ungatedDone: "call_mcp_dynamic_load_ungated_001", + resumedDone: "call_mcp_dynamic_load_resumed_001", +} + +export const DYNAMIC_LOAD_QUERY = "jira_search_tickets" diff --git a/apps/vscode-e2e/src/suite/tools/mcp-dynamic-load.test.ts b/apps/vscode-e2e/src/suite/tools/mcp-dynamic-load.test.ts new file mode 100644 index 00000000000..59e4845c486 --- /dev/null +++ b/apps/vscode-e2e/src/suite/tools/mcp-dynamic-load.test.ts @@ -0,0 +1,195 @@ +import * as assert from "assert" +import * as fs from "fs/promises" +import * as path from "path" +import * as vscode from "vscode" + +import { + DEFAULT_MCP_DYNAMIC_LOAD_INITIAL_K, + DEFAULT_MCP_DYNAMIC_LOAD_SEARCH_K, + DEFAULT_MCP_DYNAMIC_LOAD_SEARCH_TURNS, + DEFAULT_MCP_DYNAMIC_LOAD_THRESHOLD, + RooCodeEventName, + type ClineMessage, + type RooCodeSettings, +} from "@roo-code/types" + +import { waitFor, waitUntilCompleted } from "../utils" +import { setDefaultSuiteTimeout } from "../test-utils" +import { + CATALOG_SERVER_NAME, + DYNAMIC_LOAD_CALL_IDS, + DYNAMIC_LOAD_PROMPTS, + catalogToolName, + catalogTools, +} from "./fixtures/mcp-catalog" + +type JournalEntry = { + timestamp?: number + body?: { + messages?: Array<{ role?: string; content?: unknown; tool_call_id?: string }> + tools?: Array<{ function?: { name?: string } }> + } +} + +const allCatalogNames = catalogTools.map(({ name }) => catalogToolName(name)).sort() +const defaults: RooCodeSettings = { + "mcp.dynamicLoad.threshold": DEFAULT_MCP_DYNAMIC_LOAD_THRESHOLD, + "mcp.dynamicLoad.initialK": DEFAULT_MCP_DYNAMIC_LOAD_INITIAL_K, + "mcp.dynamicLoad.searchTurns": DEFAULT_MCP_DYNAMIC_LOAD_SEARCH_TURNS, + "mcp.dynamicLoad.searchK": DEFAULT_MCP_DYNAMIC_LOAD_SEARCH_K, +} + +const text = (content: unknown) => + typeof content === "string" + ? content + : Array.isArray(content) + ? content.map((part: { text?: string }) => part?.text ?? "").join("") + : "" + +const toolNames = (entry: JournalEntry) => (entry.body?.tools ?? []).map((tool) => tool.function?.name ?? "") +const mcpToolNames = (entry: JournalEntry) => + toolNames(entry) + .filter((name) => name.startsWith("mcp--")) + .sort() + +async function journal(): Promise { + const response = await fetch(`${process.env.AIMOCK_URL}/__aimock/journal`) + return (await response.json()) as JournalEntry[] +} + +async function findRequest(matches: (entry: JournalEntry) => boolean): Promise { + let found: JournalEntry | undefined + await waitFor(async () => { + found = (await journal()).find(matches) + return found !== undefined + }) + return found! +} + +const lastUserTextIncludes = (marker: string) => (entry: JournalEntry) => { + const users = (entry.body?.messages ?? []).filter((message) => message.role === "user") + return text(users.at(-1)?.content).includes(marker) +} + +const hasToolResult = (toolCallId: string) => (entry: JournalEntry) => + (entry.body?.messages ?? []).some((message) => message.role === "tool" && message.tool_call_id === toolCallId) + +suite("Dynamic MCP tool loading", function () { + setDefaultSuiteTimeout(this) + + let rooDir: string + + async function runTask(prompt: string, settings: RooCodeSettings) { + const api = globalThis.api + return waitUntilCompleted({ + api, + start: () => + api.startNewTask({ + configuration: { + mode: "code", + autoApprovalEnabled: true, + alwaysAllowMcp: true, + mcpEnabled: true, + enableCheckpoints: false, + ...settings, + }, + text: prompt, + }), + timeout: 45_000, + }) + } + + suiteSetup(async () => { + const workspaceDir = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath + assert.ok(workspaceDir, "No workspace folder found") + assert.ok(process.env.AIMOCK_URL, "AIMOCK_URL must be set for journal assertions") + rooDir = path.join(workspaceDir, ".roo") + const readyFile = path.join(workspaceDir, "mcp-dynamic-load-fixture", "ready") + await fs.rm(readyFile, { force: true }) + await fs.mkdir(rooDir, { recursive: true }) + await fs.writeFile( + path.join(rooDir, "mcp.json"), + JSON.stringify({ + mcpServers: { + [CATALOG_SERVER_NAME]: { + command: process.env.npm_node_execpath ?? "node", + args: [path.join(__dirname, "fixtures", "catalog-mcp-server.js")], + env: { MCP_TEST_READY_FILE: readyFile }, + alwaysAllow: catalogTools.map(({ name }) => name), + }, + }, + }), + ) + await waitFor( + () => + fs.access(readyFile).then( + () => true, + () => false, + ), + { timeout: 30_000 }, + ) + }) + + suiteTeardown(async () => { + await globalThis.api.setConfiguration(defaults).catch(() => {}) + await globalThis.api.clearCurrentTask().catch(() => {}) + await fs.rm(rooDir, { recursive: true, force: true }) + await fs.rm(path.join(path.dirname(rooDir), "mcp-dynamic-load-fixture"), { recursive: true, force: true }) + }) + + test("sends every allowed MCP tool when the mode has no more tools than the default threshold", async () => { + await runTask(DYNAMIC_LOAD_PROMPTS.ungated, defaults) + const request = await findRequest(lastUserTextIncludes(DYNAMIC_LOAD_PROMPTS.ungated)) + assert.deepStrictEqual(mcpToolNames(request), allCatalogNames) + assert.ok(!toolNames(request).includes("mcp_load"), "mcp_load must not be offered below the threshold") + }) + + test("sends every allowed MCP tool when Search turns is 0", async () => { + const marker = `${DYNAMIC_LOAD_PROMPTS.ungated} (search turns 0)` + await runTask(marker, { ...defaults, "mcp.dynamicLoad.threshold": 3, "mcp.dynamicLoad.searchTurns": 0 }) + const request = await findRequest(lastUserTextIncludes(marker)) + assert.deepStrictEqual(mcpToolNames(request), allCatalogNames) + assert.ok(!toolNames(request).includes("mcp_load"), "Search turns 0 must turn off mcp_load") + }) + + test("gates the tools, attaches the named tool with mcp_load, and keeps the selection on resume", async () => { + const api = globalThis.api + const gated: RooCodeSettings = { + "mcp.dynamicLoad.threshold": 3, + "mcp.dynamicLoad.initialK": 1, + "mcp.dynamicLoad.searchTurns": 1, + "mcp.dynamicLoad.searchK": 1, + } + const taskId = await runTask(DYNAMIC_LOAD_PROMPTS.gated, gated) + + const first = await findRequest(lastUserTextIncludes(DYNAMIC_LOAD_PROMPTS.gated)) + assert.ok(toolNames(first).includes("mcp_load"), "a gated build must offer mcp_load") + assert.deepStrictEqual(mcpToolNames(first), [catalogToolName("jira_count_tickets")]) + const searchTickets = catalogToolName("jira_search_tickets") + assert.ok(!mcpToolNames(first).includes(searchTickets), "the first build must leave the named tool unattached") + + const afterLoad = await findRequest(hasToolResult(DYNAMIC_LOAD_CALL_IDS.load)) + assert.deepStrictEqual(mcpToolNames(afterLoad), [...mcpToolNames(first), searchTickets].sort()) + + const saved = (await api.getTaskHistoryItem(taskId))?.attachedMcpToolNames?.slice().sort() + assert.deepStrictEqual(saved, mcpToolNames(afterLoad)) + + while (api.getCurrentTaskStack().length > 0) await api.clearCurrentTask() + let resumeAsked = false + const onMessage = ({ taskId: id, message }: { taskId: string; message: ClineMessage }) => { + if (id === taskId && message.type === "ask" && message.ask?.startsWith("resume")) resumeAsked = true + } + api.on(RooCodeEventName.Message, onMessage) + try { + await api.resumeTask(taskId) + await waitFor(() => resumeAsked, { timeout: 30_000 }) + } finally { + api.off(RooCodeEventName.Message, onMessage) + } + const resumedDone = waitUntilCompleted({ api, taskId, timeout: 45_000 }) + await api.sendMessage(DYNAMIC_LOAD_PROMPTS.resumed) + await resumedDone + const resumed = await findRequest(lastUserTextIncludes(DYNAMIC_LOAD_PROMPTS.resumed)) + assert.deepStrictEqual(mcpToolNames(resumed), saved, "a resumed task must send the saved selection") + }) +}) diff --git a/docs/architecture/mcp-dynamic-tool-loading.md b/docs/architecture/mcp-dynamic-tool-loading.md index 33df74e846c..93ccad2da2a 100644 --- a/docs/architecture/mcp-dynamic-tool-loading.md +++ b/docs/architecture/mcp-dynamic-tool-loading.md @@ -22,6 +22,7 @@ messages. Supplemental ranks stop after `mcp.dynamicLoad.searchTurns` (default 7 user messages since the last summary. A value of 0 turns dynamic loading off. A value of 1 keeps only the initial selection. Supplemental ranks also stop at 60 attached tools (`MAX_ATTACHED_DURING_ROLLING`). +The `mcp_load` tool can attach more tools past this cap. Recovered historical names count against the room for a supplemental rank. History recovery can exceed this cap when provider compatibility requires it. @@ -31,7 +32,10 @@ previous generation with an absent selection, so a reload also ranks again. Name because the fresh-start history no longer sends their `tool_use` blocks. Any change to the tools array, an append too, ends the provider prompt cache. The -search window limits that cost to one cache rewrite for each searched turn. +search window limits that cost to one cache rewrite for each searched turn. Each +`mcp_load` call that attaches a new tool costs one more rewrite, at any turn. A +load that attaches nothing new costs none. Anthropic `defer_loading` with `tool_reference` results +can keep the prefix, but this design does not use them. `docs/architecture/tla/McpToolSelectionLifecycle.tla` models these rules. If saving fails, the task retains its in-memory selection and continues. Later @@ -53,8 +57,55 @@ The gate limits advertised definitions; it does not add an execution permission boundary. Existing tool authorization still applies to calls by name. The settings schema and extension-state round trip are implemented for -`threshold`, `initialK`, and `searchTurns`. SettingsView controls are deferred -to #583. The `mcp_load` escape hatch is deferred to #579. +`threshold`, `initialK`, `searchTurns`, and `searchK`. SettingsView controls are +deferred to #583. + +## Loading more tools + +A gated build also declares the native `mcp_load` tool when the effective tool +policy allows it. The model calls it with a +query when it needs an MCP tool that is not attached. `McpToolSelection.load` +ranks the unattached tools in the scope of the newest gated build and attaches up to +`mcp.dynamicLoad.searchK` (default 10) matches. The next build declares them. Attached +tools cannot take the slots of an unattached match. If no unattached tool matches, +the load ranks the whole scope, so the result names the attached matches. + +The ranker counts each term of a server or tool name 3 times. This boost helps a +tool rank above tools that only mention its name, but it does not guarantee that +order. BM25 length normalization can still put a short description first. A query +word that contains `_` or `-` and equals a tool name gives priority to each tool +with that name. If two servers have that name, BM25 orders the two tools. A +qualified name such as `mcp--server--tool` or `mcp__server__tool` gives priority +to the tool of that server. A literal match ranks first. A match that treats `-` +and `_` as equal ranks next. Thus `mcp--my__server--search` puts `search` on the +server `my__server` above `server__search` on the server `my`. The query +`mcp__my__server__search` matches neither name literally, so BM25 orders the two +tools. The query `mcp--slack--search` also gives the lower priority to a tool +named `mcp__slack__search` on another server. A prose word such as `search` gets +no priority, even when a tool has that name. + +A load ignores the search window and the 60-tool cap. Before #578, every scoped +tool was attached, so a load cannot attach more than the old behavior did. A load +does not count as a user message and does not move the ranked message index. A +repeated query ranks the tools that are still unattached, so it attaches the next +matches. It attaches nothing new and does not save only when no unattached tool +matches. Condensation removes loaded +tools with the rest of the selection. A load that starts or completes after a +condensation, before the next build, does not commit. A condensation during the +save of a load also discards the result. The result then tells the model to call +`mcp_load` again in its next request. + +The next build intersects the selection with the current scope, so a load cannot +declare a tool that the mode or the tool policy removes. `mcp_load` is declared +only when the gate is on and the effective tool policy allows it. `disabledTools` +can disable it. The default build then omits it from `tools`. A build with +`includeAllToolsWithRestrictions` keeps the definition, but leaves `mcp_load` out +of `allowedFunctionNames`. When the gate is on, the policy allows `mcp_load`, and +every allowed MCP tool is attached, `mcp_load` stays declared. A call then lists +the matches as already attached. A call +when the gate is off does no harm, because that build declares every allowed MCP +tool. `docs/architecture/tla/McpToolSelectionLoadMC.tla` +checks that a load reaches the current topic at the cap and after the window. ## Tool status in the chat diff --git a/docs/architecture/tla/McpSelectionEpoch.LostCursor.cfg b/docs/architecture/tla/McpSelectionEpoch.LostCursor.cfg index 1e6c1e823ee..323e9170a61 100644 --- a/docs/architecture/tla/McpSelectionEpoch.LostCursor.cfg +++ b/docs/architecture/tla/McpSelectionEpoch.LostCursor.cfg @@ -1,4 +1,5 @@ SPECIFICATION Spec CONSTANT Variant = "LostCursor" INVARIANTS EpochOwned MessageRanked RecordKept CursorRetained RankOwned RecoveryCapped +PROPERTIES LoadReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpSelectionEpoch.LostReset.cfg b/docs/architecture/tla/McpSelectionEpoch.LostReset.cfg index 2b33f5bd8cf..b390f99d0c6 100644 --- a/docs/architecture/tla/McpSelectionEpoch.LostReset.cfg +++ b/docs/architecture/tla/McpSelectionEpoch.LostReset.cfg @@ -1,4 +1,5 @@ SPECIFICATION Spec CONSTANT Variant = "LostReset" INVARIANTS EpochOwned MessageRanked RecordKept CursorRetained RankOwned RecoveryCapped +PROPERTIES LoadReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpSelectionEpoch.RecoveryRoom.cfg b/docs/architecture/tla/McpSelectionEpoch.RecoveryRoom.cfg index 5e669371863..07763125cb2 100644 --- a/docs/architecture/tla/McpSelectionEpoch.RecoveryRoom.cfg +++ b/docs/architecture/tla/McpSelectionEpoch.RecoveryRoom.cfg @@ -1,4 +1,5 @@ SPECIFICATION Spec CONSTANT Variant = "RecoveryRoom" INVARIANTS EpochOwned MessageRanked RecordKept CursorRetained RankOwned RecoveryCapped +PROPERTIES LoadReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpSelectionEpoch.RejectEpoch.cfg b/docs/architecture/tla/McpSelectionEpoch.RejectEpoch.cfg index 214ad3b8d8c..e0f42b4126f 100644 --- a/docs/architecture/tla/McpSelectionEpoch.RejectEpoch.cfg +++ b/docs/architecture/tla/McpSelectionEpoch.RejectEpoch.cfg @@ -1,4 +1,5 @@ SPECIFICATION Spec CONSTANT Variant = "RejectEpoch" INVARIANTS EpochOwned MessageRanked RecordKept CursorRetained RankOwned RecoveryCapped +PROPERTIES LoadReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpSelectionEpoch.StaleLoadSave.cfg b/docs/architecture/tla/McpSelectionEpoch.StaleLoadSave.cfg new file mode 100644 index 00000000000..a6c1386f940 --- /dev/null +++ b/docs/architecture/tla/McpSelectionEpoch.StaleLoadSave.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANT Variant = "StaleLoadSave" +INVARIANTS EpochOwned MessageRanked RecordKept CursorRetained RankOwned RecoveryCapped +PROPERTIES LoadReported +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpSelectionEpoch.StaleRank.cfg b/docs/architecture/tla/McpSelectionEpoch.StaleRank.cfg index 4de56ecfbd7..f416bdb3d0f 100644 --- a/docs/architecture/tla/McpSelectionEpoch.StaleRank.cfg +++ b/docs/architecture/tla/McpSelectionEpoch.StaleRank.cfg @@ -1,4 +1,5 @@ SPECIFICATION Spec CONSTANT Variant = "StaleRank" INVARIANTS EpochOwned MessageRanked RecordKept CursorRetained RankOwned RecoveryCapped +PROPERTIES LoadReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpSelectionEpoch.StaleSave.cfg b/docs/architecture/tla/McpSelectionEpoch.StaleSave.cfg index a2484ea8bdf..1cf9e108ad0 100644 --- a/docs/architecture/tla/McpSelectionEpoch.StaleSave.cfg +++ b/docs/architecture/tla/McpSelectionEpoch.StaleSave.cfg @@ -1,4 +1,5 @@ SPECIFICATION Spec CONSTANT Variant = "StaleSave" INVARIANTS EpochOwned MessageRanked RecordKept CursorRetained RankOwned RecoveryCapped +PROPERTIES LoadReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpSelectionEpoch.TextOnly.cfg b/docs/architecture/tla/McpSelectionEpoch.TextOnly.cfg index 5943931d230..361167371dd 100644 --- a/docs/architecture/tla/McpSelectionEpoch.TextOnly.cfg +++ b/docs/architecture/tla/McpSelectionEpoch.TextOnly.cfg @@ -1,4 +1,5 @@ SPECIFICATION Spec CONSTANT Variant = "TextOnly" INVARIANTS EpochOwned MessageRanked RecordKept CursorRetained RankOwned RecoveryCapped +PROPERTIES LoadReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpSelectionEpoch.cfg b/docs/architecture/tla/McpSelectionEpoch.cfg index faebc06cae1..0acd4feed64 100644 --- a/docs/architecture/tla/McpSelectionEpoch.cfg +++ b/docs/architecture/tla/McpSelectionEpoch.cfg @@ -1,4 +1,5 @@ SPECIFICATION Spec CONSTANT Variant = "Fixed" INVARIANTS EpochOwned MessageRanked RecordKept CursorRetained RankOwned RecoveryCapped +PROPERTIES LoadReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpSelectionEpoch.tla b/docs/architecture/tla/McpSelectionEpoch.tla index 8e9db3c69d5..1f85401e22f 100644 --- a/docs/architecture/tla/McpSelectionEpoch.tla +++ b/docs/architecture/tla/McpSelectionEpoch.tla @@ -45,40 +45,60 @@ \* Review PR 2323 discussion_r4729239722 and discussion_r4729239726 extends cursor coverage in McpRankCursor. \* That submodel checks raw merge inputs and replacement input at one index without multiplying epoch states. \* Round: 0 covered, 2 added, 0 gap. The epoch invariants and all seven fault verdicts remain unchanged. +\* Review ratchet: PR 2777, CodeRabbit thread PRRT_kwDOSK-bwM69Kzds. Source: McpToolSelection.load. +\* Sink: the mcp_load result text. Failure: a reset during persist() removes loaded tools, but the result lists them. +\* Invariant: LoadReported. A result shown to the model lists only names that the selection holds. +\* Oracle: Task.condenseContext calls reset outside the load queue, so a reset can occur at each await. +\* Expect: StaleLoadSave, the code before the fix, violates LoadReported. Other verdicts stay. +\* False alarm: a state invariant failed when a reset came after the report. LoadReported checks the report step. +\* Result: Fixed holds in 448 states. StaleLoadSave fails LoadReported in 4 steps. All seven earlier faults fail. +\* Replay: the "reports the load" test in mcpToolSelection.spec.ts fails before the fix and passes after it. +\* Round: 0 covered, 1 added, 1 gap. Gap: the doc thread PRRT_kwDOSK-bwM69Kzdp is prose, not state. +\* Cost: the nine-config gate takes 7 seconds. Agent time was not measured. EXTENDS Naturals CONSTANT Variant -VARIABLES epoch, names, phase, oldSaved, turn, ranked, loaded, cursor, savedCursor, committed, recovered, added, validEpoch -vars == <> +VARIABLES epoch, names, phase, oldSaved, turn, ranked, loaded, cursor, savedCursor, committed, recovered, added, validEpoch, + report +vars == <> Init == /\ epoch = 0 /\ names = {"old"} /\ phase = "before" /\ oldSaved = FALSE /\ turn = 1 /\ ranked = 1 /\ loaded = FALSE /\ cursor = 1 /\ savedCursor = 1 /\ committed = FALSE /\ recovered = 0 /\ added = 0 /\ validEpoch \in BOOLEAN + /\ report = "none" Reset == /\ phase = "before" /\ phase' = "reset" /\ IF Variant = "LostReset" THEN UNCHANGED <> ELSE /\ epoch' = 1 /\ names' = {} /\ committed' = FALSE /\ cursor' = 0 /\ savedCursor' = 0 - /\ UNCHANGED <> + /\ UNCHANGED <> FreshSave == /\ phase = "reset" /\ phase' = "fresh" /\ names' = names \cup {"new"} /\ cursor' = 1 /\ savedCursor' = 1 - /\ UNCHANGED <> + /\ UNCHANGED <> OldSave == /\ ~oldSaved /\ oldSaved' = TRUE /\ names' = IF epoch = 0 \/ Variant = "StaleSave" THEN names \cup {"old"} ELSE names - /\ UNCHANGED <> + /\ UNCHANGED <> Message == /\ turn = 1 /\ turn' = 2 /\ ranked' = IF Variant = "TextOnly" THEN ranked ELSE 2 - /\ UNCHANGED <> + /\ UNCHANGED <> Reload == /\ ~loaded /\ loaded' = TRUE /\ cursor' = IF Variant = "LostCursor" THEN 0 ELSE savedCursor - /\ UNCHANGED <> + /\ UNCHANGED <> RankFinish == /\ ~committed /\ committed' = (epoch = 0 \/ Variant = "StaleRank") - /\ UNCHANGED <> + /\ UNCHANGED <> Recover == /\ recovered = 0 /\ recovered' = 1 /\ added' = IF Variant = "RecoveryRoom" THEN 1 ELSE 0 - /\ UNCHANGED <> -Next == Reset \/ FreshSave \/ OldSave \/ Message \/ Reload \/ RankFinish \/ Recover + /\ UNCHANGED <> +\* A load ranks and commits in phase "before". Only that epoch has a later reset. +LoadCommit == /\ phase = "before" /\ report = "none" /\ report' = "saving" + /\ names' = names \cup {"load"} + /\ UNCHANGED <> +LoadReport == /\ report = "saving" + /\ report' = IF epoch = 0 \/ Variant = "StaleLoadSave" THEN "shown" ELSE "dropped" + /\ UNCHANGED <> +Next == Reset \/ FreshSave \/ OldSave \/ Message \/ Reload \/ RankFinish \/ Recover \/ LoadCommit \/ LoadReport Spec == Init /\ [][Next]_vars EpochOwned == phase # "before" => /\ epoch = 1 /\ "old" \notin names MessageRanked == ranked = turn @@ -87,4 +107,5 @@ CursorRetained == loaded => cursor = savedCursor RankOwned == committed => epoch = 0 \* One slot remains under the cap before recovery. RecoveryCapped == recovered + added <= 1 +LoadReported == [][LoadReport /\ report' = "shown" => "load" \in names]_vars ==== diff --git a/docs/architecture/tla/McpToolSelectionLifecycle.tla b/docs/architecture/tla/McpToolSelectionLifecycle.tla index d6e3a277cc3..636fdf27e4b 100644 --- a/docs/architecture/tla/McpToolSelectionLifecycle.tla +++ b/docs/architecture/tla/McpToolSelectionLifecycle.tla @@ -13,7 +13,8 @@ \* Failure 5: a reader of the stored searchTurns value gets a value that differs from the other readers. \* Invariant 5: SharedDefault. Each reader gets a valid stored value, 0 included, or else the shared default. \* Source: the stored mcp.dynamicLoad.searchTurns. Sinks: ClineProvider.getState, getStateToPostToWebview, -\* buildNativeToolsArrayWithRestrictions, and McpToolSelection.select. All use resolveMcpDynamicLoadSettings. +\* buildNativeToolsArrayWithRestrictions, and McpToolSelection.select. The first three use +\* resolveMcpDynamicLoadSettings. select uses the value from buildNativeToolsArrayWithRestrictions. \* Oracle: the schema. It rejects Unset and Invalid and accepts each natural number. \* Expect (Failure 5): a null result. FalsyDefault, a reader that replaces 0 with the default, violates SharedDefault. \* Oracle: the ranker returns relevant tools from scope, capped at k. @@ -72,6 +73,57 @@ \* The production scope model passes 530 states and 80 scenarios. All four selection fault injections fail. \* Root tests pass all 14 tasks. Types and lint pass. Suppression counts are unchanged. Focused tests take 5.5 seconds. \* Cost: each TLC config takes under 1 second. Agent time was not measured. +\* Issue 579 adds mcp_load. Source: McpLoadTool.execute and McpToolSelection.load. Sink: the next tool build. +\* Failure 6: after the window closes or the cap fills, the model cannot get a tool for the current topic. +\* Invariant 6: LoadReachable. A load for the current topic attaches a tool for that topic. +\* Decision: a load ignores the window and the cap. Before issue 578, every scoped tool was attached. +\* So RollingCapped now limits supplements only. It is an action property. +\* Oracle: the ranker ranks the whole scope for the load query, capped at SearchK. +\* Load needs phase = "model_ready". McpToolSelection.load returns undefined until a build initializes it. +\* Not modeled: scope. The next build intersects the selection with the current scope. +\* Expect: LoadCapped and LoadWindowed fail LoadReachable in McpToolSelectionLoadMC. Other verdicts stay. +\* Finding: the cap decision broke the RollingCapped state invariant. PrunedSinceCondense needed a load term. +\* Result: Fixed holds in 91 states and window 1 in 78. All seven earlier faults fail their earlier properties. +\* Replay: in production, a capped load fails 9 tests, a stale load 1, a moved cursor 12, and no queue 2. +\* Property test: mcpToolSelection.spec.ts "mcp_load" checks LoadReachable for 4 sizes and 3 window positions. +\* Cost: the 12-config gate for the three selection modules takes 10 seconds. Agent time was not measured. +\* Review round 1: 1 covered, 0 added, 2 gap. Covered: a load after a condensation. The Load precondition +\* had it, and the code did not. Gap: telemetry names and result text are not state. +\* Simplification expectation: null result. select uses the limits that build-tools resolved. So WindowRead +\* equals GateRead, and the readers drop from four to three. FalsyDefault must still fail SharedDefault. +\* Basis: https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/ checks input once at the boundary. +\* Not modeled: persist moves to the constructor. It is the same callback on each call, so no state changes. +\* Result: null result. Fixed holds in 91 states, window 1 and load in 78. FalsyDefault and all faults fail. +\* Replay: 407 focused tests pass. Without the load epoch guard, the resetDuringSave test fails. +\* Manual test, task 01a22a0e: 1 added, 2 gap. Four mcp_load calls named jira_search_tickets and got none. +\* Failure 7: a load returns only attached tools, so an unattached relevant tool never comes. +\* Invariant 7: LoadAddsNew. If a relevant tool is not attached, a load attaches a new relevant tool. +\* Added: the load oracle may rank any relevant tools first. LoadAttached ranks the whole scope, as the code did. +\* Gap: an exact tool name in the query, and the name weight in Bm25Ranker. The spec treats the ranker as an oracle. +\* Expect: LoadAttached fails LoadAddsNew. Fixed, LoadCapped and LoadWindowed keep their verdicts. +\* Review PR 2777 round 2: 2 covered, 0 added, 5 gap. Expect: null result. All verdicts stay. +\* Covered: a repeated query attaches the next match (thread 4735067963). LoadAddsNew requires it. +\* Covered: a failed save (thread 4735067967). Each saveClineMessages writes the in-memory selection. +\* Gap: a word such as "search" names a tool (thread 4735067978). The spec treats the ranker as an oracle. +\* Gap: the doc ranking claim and three test assertions are not state (threads 4735067956, +\* 4735067959, 4735067971 and 4735067953). +\* Result: null result. All 13 verdicts stay. Without the identifier rule, 1 Bm25Ranker test fails. +\* Review PR 2777 round 3: 0 covered, 1 added, 3 gap. +\* Added: a second load before condensation (thread 4735280401). One load could not check round 2's +\* repeated query, so that verdict was wrong. loads counts to MaxLoads. LoadCached skips a repeat load. +\* Gap: a qualified name such as mcp--slack--search or mcp__server__tool (threads 4735280407 and +\* 4735280413). The spec treats the ranker as an oracle. Gap: the doc ranking claim (thread 4735280393). +\* Expect: LoadCached fails LoadAddsNew on the second load. Fixed and the 13 earlier verdicts stay. +\* Result: as expected. 14 of 14 verdicts hold. Fixed has 141 states, load 120 and window 1 125. +\* LoadCached uses SearchK = 1 and fails in 40 states. Fixed on that domain holds in 156. +\* Replay: a cache for a repeated query fails 13 mcpToolSelection tests. The old ranker fails 3 tests. +\* Cost: the 14-config gate takes 11 seconds. Agent time was not measured. +\* Simplification expectation: null result. Task has three condensation paths and one Condense action. +\* Task.afterSummary keeps the reset in one place. load drops its empty-scope guard. The ranker +\* returns no tools for an empty scope, as LoadResults does. All 14 verdicts must stay. +\* Basis: https://refactoring.guru/consolidate-duplicate-conditional-fragments moves code that each branch repeats. +\* Result: null result. 14 of 14 verdicts stay. 2384 focused tests and 3 e2e tests pass. +\* Replay: afterSummary without the reset fails 3 tests, for the manual and the emergency condense paths. EXTENDS Integers, FiniteSets CONSTANTS @@ -82,6 +134,8 @@ CONSTANTS SupplementalK, \* max tools from supplemental ranking per turn SearchTurns, \* user turns since the last condensation that still get a supplemental rank MaxAttached, \* attach cap for supplemental ranks + SearchK, \* max tools from one load + MaxLoads, \* max loads between condensations. Two show a repeated query. MaxTurns, \* max user turns to explore StoredValues, \* stored searchTurns inputs. Negative numbers stand for rejected values. DefaultSearchTurns, @@ -92,9 +146,10 @@ VARIABLES turn, \* current user turn; the task message is turn 1 topic, \* current user topic: "A" or "B" phase, \* "idle" (not initialized) | "needs_supplement" | "model_ready" - condensedTurn \* turn of the last condensation (0 = never) + condensedTurn, \* turn of the last condensation (0 = never) + loads \* loads since the last condensation -vars == <> +vars == <> TypeOK == /\ selection \subseteq Catalog @@ -102,6 +157,7 @@ TypeOK == /\ topic \in {"A", "B"} /\ phase \in {"idle", "needs_supplement", "model_ready"} /\ condensedTurn \in 0..MaxTurns + /\ loads \in 0..MaxLoads Max(a, b) == IF a > b THEN a ELSE b @@ -117,11 +173,12 @@ RankQueryTools == IF Variant = "TaskTextRerank" THEN TopicA ELSE RelevantTools Resolve(v) == IF v < 0 THEN DefaultSearchTurns ELSE v \* Each reader gets the output of the reader before it. getState reads storage. +\* McpToolSelection.select uses the gate value as it is. It does not resolve again. StateRead(v) == Resolve(v) WebviewRead(v) == Resolve(StateRead(v)) GateRead(v) == Resolve(StateRead(v)) WindowRead(v) == - IF Variant = "FalsyDefault" /\ GateRead(v) = 0 THEN DefaultSearchTurns ELSE Resolve(GateRead(v)) + IF Variant = "FalsyDefault" /\ GateRead(v) = 0 THEN DefaultSearchTurns ELSE GateRead(v) \* TLC and check.sh report a violation only for a state-level invariant, so it names a variable. SharedDefault == @@ -152,13 +209,14 @@ Init == /\ topic = "A" /\ phase = "idle" /\ condensedTurn = 0 + /\ loads = 0 \* The initial ranking runs at task start and again after each condensation. InitialRank == /\ phase = "idle" /\ selection' = RankedResult(Catalog, InitialK, RankQueryTools) /\ phase' = "model_ready" - /\ UNCHANGED <> + /\ UNCHANGED <> UserMessage == /\ phase = "model_ready" @@ -166,14 +224,14 @@ UserMessage == /\ turn' = turn + 1 /\ \E t \in {"A", "B"} : topic' = t /\ phase' = "needs_supplement" - /\ UNCHANGED <> + /\ UNCHANGED <> \* Runs in buildNativeToolsArrayWithRestrictions before the model sees tools. SupplementalRank == /\ phase = "needs_supplement" /\ selection' = selection \cup Supplement /\ phase' = "model_ready" - /\ UNCHANGED <> + /\ UNCHANGED <> \* Condensation drops the selection. NoPrune leaves the selection as it is. \* attemptApiRequest condenses after the user message and before the tool build, so needs_supplement is allowed. @@ -181,13 +239,38 @@ Condense == /\ phase \in {"model_ready", "needs_supplement"} /\ turn > condensedTurn /\ condensedTurn' = turn + /\ loads' = 0 /\ IF Variant = "NoPrune" THEN UNCHANGED <> ELSE /\ selection' = {} /\ phase' = "idle" /\ UNCHANGED <> -Next == InitialRank \/ UserMessage \/ SupplementalRank \/ Condense +\* LoadAttached ranks the whole scope, so attached tools can take every SearchK slot. +LoadScope == IF Variant = "LoadAttached" THEN Catalog ELSE Catalog \ selection + +\* Oracle: the ranker can put any relevant tools of the scope first. +LoadResults == + LET relevant == LoadScope \cap RelevantTools + n == IF Cardinality(relevant) <= SearchK THEN Cardinality(relevant) ELSE SearchK + IN {r \in SUBSET relevant : Cardinality(r) = n} + +\* LoadCached returns nothing for a repeat load, as an idempotency cache would. +LoadResult(ranked) == + CASE Variant = "LoadWindowed" /\ ~InWindow -> {} + [] Variant = "LoadCached" /\ loads > 0 -> {} + [] Variant = "LoadCapped" -> CapTo(ranked \ selection, MaxAttached - Cardinality(selection)) + [] OTHER -> ranked + +\* The model calls mcp_load after a gated build. A load does not count as a user message. +Load == + /\ phase = "model_ready" + /\ loads < MaxLoads + /\ loads' = loads + 1 + /\ \E ranked \in LoadResults : selection' = selection \cup LoadResult(ranked) + /\ UNCHANGED <> + +Next == InitialRank \/ UserMessage \/ SupplementalRank \/ Condense \/ Load Spec == Init /\ [][Next]_vars @@ -195,9 +278,15 @@ TopicReachable == (phase = "model_ready" /\ InWindow /\ SearchTurns > 1 /\ Cardinality(selection) < MaxAttached) => RelevantTools \cap selection # {} -PrunedSinceCondense == Cardinality(selection) <= InitialK + SupplementalK * (turn - condensedTurn) +PrunedSinceCondense == + Cardinality(selection) <= InitialK + SupplementalK * (turn - condensedTurn) + SearchK * loads + +\* A load can pass the cap. A supplement never grows the selection past it. +RollingCapped == [][SupplementalRank => Cardinality(selection') <= Max(Cardinality(selection), MaxAttached)]_vars + +LoadReachable == [][Load => RelevantTools \cap selection' # {}]_vars -RollingCapped == Cardinality(selection) <= Max(InitialK, MaxAttached) +LoadAddsNew == [][Load /\ RelevantTools \ selection # {} => (selection' \ selection) \cap RelevantTools # {}]_vars FrozenAfterWindow == [][phase = "needs_supplement" /\ ~InWindow => selection' \subseteq selection]_vars diff --git a/docs/architecture/tla/McpToolSelectionLifecycleMC.FalsyDefault.cfg b/docs/architecture/tla/McpToolSelectionLifecycleMC.FalsyDefault.cfg index 06a5f9dff12..bb7bc213fb5 100644 --- a/docs/architecture/tla/McpToolSelectionLifecycleMC.FalsyDefault.cfg +++ b/docs/architecture/tla/McpToolSelectionLifecycleMC.FalsyDefault.cfg @@ -6,11 +6,13 @@ CONSTANTS InitialK = 3 SupplementalK = 2 SearchTurns = 2 + SearchK = 2 + MaxLoads = 2 MaxAttached = 4 MaxTurns = 3 StoredValues <- MCStoredValues DefaultSearchTurns = 7 Variant = "FalsyDefault" -INVARIANTS TypeOK TopicReachable PrunedSinceCondense RollingCapped SharedDefault -PROPERTY FrozenAfterWindow +INVARIANTS TypeOK TopicReachable PrunedSinceCondense SharedDefault +PROPERTIES FrozenAfterWindow RollingCapped LoadReachable LoadAddsNew CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpToolSelectionLifecycleMC.NoCap.cfg b/docs/architecture/tla/McpToolSelectionLifecycleMC.NoCap.cfg index d7aa8c6a0fc..eaae464dc76 100644 --- a/docs/architecture/tla/McpToolSelectionLifecycleMC.NoCap.cfg +++ b/docs/architecture/tla/McpToolSelectionLifecycleMC.NoCap.cfg @@ -6,11 +6,13 @@ CONSTANTS InitialK = 3 SupplementalK = 2 SearchTurns = 2 + SearchK = 2 + MaxLoads = 2 MaxAttached = 4 MaxTurns = 3 StoredValues <- MCStoredValues DefaultSearchTurns = 7 Variant = "NoCap" -INVARIANTS TypeOK TopicReachable PrunedSinceCondense RollingCapped -PROPERTY FrozenAfterWindow +INVARIANTS TypeOK TopicReachable PrunedSinceCondense +PROPERTIES FrozenAfterWindow RollingCapped LoadReachable LoadAddsNew CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpToolSelectionLifecycleMC.NoFreeze.cfg b/docs/architecture/tla/McpToolSelectionLifecycleMC.NoFreeze.cfg index 3078f95fad3..bf8f31d0c7b 100644 --- a/docs/architecture/tla/McpToolSelectionLifecycleMC.NoFreeze.cfg +++ b/docs/architecture/tla/McpToolSelectionLifecycleMC.NoFreeze.cfg @@ -6,11 +6,13 @@ CONSTANTS InitialK = 3 SupplementalK = 2 SearchTurns = 2 + SearchK = 2 + MaxLoads = 2 MaxAttached = 4 MaxTurns = 3 StoredValues <- MCStoredValues DefaultSearchTurns = 7 Variant = "NoFreeze" -INVARIANTS TypeOK TopicReachable PrunedSinceCondense RollingCapped -PROPERTY FrozenAfterWindow +INVARIANTS TypeOK TopicReachable PrunedSinceCondense +PROPERTIES FrozenAfterWindow RollingCapped LoadReachable LoadAddsNew CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpToolSelectionLifecycleMC.NoPrune.cfg b/docs/architecture/tla/McpToolSelectionLifecycleMC.NoPrune.cfg index ea179f6c111..ce7b9c4ac76 100644 --- a/docs/architecture/tla/McpToolSelectionLifecycleMC.NoPrune.cfg +++ b/docs/architecture/tla/McpToolSelectionLifecycleMC.NoPrune.cfg @@ -6,11 +6,13 @@ CONSTANTS InitialK = 3 SupplementalK = 2 SearchTurns = 2 + SearchK = 2 + MaxLoads = 2 MaxAttached = 4 MaxTurns = 3 StoredValues <- MCStoredValues DefaultSearchTurns = 7 Variant = "NoPrune" -INVARIANTS TypeOK TopicReachable PrunedSinceCondense RollingCapped -PROPERTY FrozenAfterWindow +INVARIANTS TypeOK TopicReachable PrunedSinceCondense +PROPERTIES FrozenAfterWindow RollingCapped LoadReachable LoadAddsNew CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpToolSelectionLifecycleMC.NoSupplement.cfg b/docs/architecture/tla/McpToolSelectionLifecycleMC.NoSupplement.cfg index d81cc570e8e..d5ad44a2c5e 100644 --- a/docs/architecture/tla/McpToolSelectionLifecycleMC.NoSupplement.cfg +++ b/docs/architecture/tla/McpToolSelectionLifecycleMC.NoSupplement.cfg @@ -6,11 +6,13 @@ CONSTANTS InitialK = 3 SupplementalK = 2 SearchTurns = 2 + SearchK = 2 + MaxLoads = 2 MaxAttached = 4 MaxTurns = 3 StoredValues <- MCStoredValues DefaultSearchTurns = 7 Variant = "NoSupplement" -INVARIANTS TypeOK TopicReachable PrunedSinceCondense RollingCapped -PROPERTY FrozenAfterWindow +INVARIANTS TypeOK TopicReachable PrunedSinceCondense +PROPERTIES FrozenAfterWindow RollingCapped LoadReachable LoadAddsNew CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpToolSelectionLifecycleMC.TaskTextRerank.cfg b/docs/architecture/tla/McpToolSelectionLifecycleMC.TaskTextRerank.cfg index 05207b2ac59..81ad36d2653 100644 --- a/docs/architecture/tla/McpToolSelectionLifecycleMC.TaskTextRerank.cfg +++ b/docs/architecture/tla/McpToolSelectionLifecycleMC.TaskTextRerank.cfg @@ -6,11 +6,13 @@ CONSTANTS InitialK = 3 SupplementalK = 2 SearchTurns = 2 + SearchK = 2 + MaxLoads = 2 MaxAttached = 4 MaxTurns = 3 StoredValues <- MCStoredValues DefaultSearchTurns = 7 Variant = "TaskTextRerank" -INVARIANTS TypeOK TopicReachable PrunedSinceCondense RollingCapped -PROPERTY FrozenAfterWindow +INVARIANTS TypeOK TopicReachable PrunedSinceCondense +PROPERTIES FrozenAfterWindow RollingCapped LoadReachable LoadAddsNew CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpToolSelectionLifecycleMC.cfg b/docs/architecture/tla/McpToolSelectionLifecycleMC.cfg index 8a79b5061bf..bc9b10fd453 100644 --- a/docs/architecture/tla/McpToolSelectionLifecycleMC.cfg +++ b/docs/architecture/tla/McpToolSelectionLifecycleMC.cfg @@ -6,11 +6,13 @@ CONSTANTS InitialK = 3 SupplementalK = 2 SearchTurns = 2 + SearchK = 2 + MaxLoads = 2 MaxAttached = 4 MaxTurns = 3 StoredValues <- MCStoredValues DefaultSearchTurns = 7 Variant = "Fixed" -INVARIANTS TypeOK TopicReachable PrunedSinceCondense RollingCapped SharedDefault -PROPERTY FrozenAfterWindow +INVARIANTS TypeOK TopicReachable PrunedSinceCondense SharedDefault +PROPERTIES FrozenAfterWindow RollingCapped LoadReachable LoadAddsNew CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpToolSelectionLoadMC.LoadAttached.cfg b/docs/architecture/tla/McpToolSelectionLoadMC.LoadAttached.cfg new file mode 100644 index 00000000000..d5075e0aa02 --- /dev/null +++ b/docs/architecture/tla/McpToolSelectionLoadMC.LoadAttached.cfg @@ -0,0 +1,18 @@ +SPECIFICATION Spec +CONSTANTS + Catalog <- MCCatalog + TopicA <- MCTopicA + TopicB <- MCTopicB + InitialK = 2 + SupplementalK = 2 + SearchTurns = 2 + SearchK = 2 + MaxLoads = 2 + MaxAttached = 3 + MaxTurns = 3 + StoredValues <- MCStoredValues + DefaultSearchTurns = 7 + Variant = "LoadAttached" +INVARIANTS TypeOK TopicReachable PrunedSinceCondense SharedDefault +PROPERTIES FrozenAfterWindow RollingCapped LoadReachable LoadAddsNew +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpToolSelectionLoadMC.LoadCached.cfg b/docs/architecture/tla/McpToolSelectionLoadMC.LoadCached.cfg new file mode 100644 index 00000000000..e10eb3220fa --- /dev/null +++ b/docs/architecture/tla/McpToolSelectionLoadMC.LoadCached.cfg @@ -0,0 +1,18 @@ +SPECIFICATION Spec +CONSTANTS + Catalog <- MCCatalog + TopicA <- MCTopicA + TopicB <- MCTopicB + InitialK = 3 + SupplementalK = 2 + SearchTurns = 2 + SearchK = 1 + MaxLoads = 2 + MaxAttached = 3 + MaxTurns = 3 + StoredValues <- MCStoredValues + DefaultSearchTurns = 7 + Variant = "LoadCached" +INVARIANTS TypeOK TopicReachable PrunedSinceCondense SharedDefault +PROPERTIES FrozenAfterWindow RollingCapped LoadReachable LoadAddsNew +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpToolSelectionLoadMC.LoadCapped.cfg b/docs/architecture/tla/McpToolSelectionLoadMC.LoadCapped.cfg new file mode 100644 index 00000000000..8c39fc2473a --- /dev/null +++ b/docs/architecture/tla/McpToolSelectionLoadMC.LoadCapped.cfg @@ -0,0 +1,18 @@ +SPECIFICATION Spec +CONSTANTS + Catalog <- MCCatalog + TopicA <- MCTopicA + TopicB <- MCTopicB + InitialK = 3 + SupplementalK = 2 + SearchTurns = 2 + SearchK = 2 + MaxLoads = 2 + MaxAttached = 3 + MaxTurns = 3 + StoredValues <- MCStoredValues + DefaultSearchTurns = 7 + Variant = "LoadCapped" +INVARIANTS TypeOK TopicReachable PrunedSinceCondense SharedDefault +PROPERTIES FrozenAfterWindow RollingCapped LoadReachable LoadAddsNew +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpToolSelectionLoadMC.LoadWindowed.cfg b/docs/architecture/tla/McpToolSelectionLoadMC.LoadWindowed.cfg new file mode 100644 index 00000000000..952a98ccbd0 --- /dev/null +++ b/docs/architecture/tla/McpToolSelectionLoadMC.LoadWindowed.cfg @@ -0,0 +1,18 @@ +SPECIFICATION Spec +CONSTANTS + Catalog <- MCCatalog + TopicA <- MCTopicA + TopicB <- MCTopicB + InitialK = 3 + SupplementalK = 2 + SearchTurns = 2 + SearchK = 2 + MaxLoads = 2 + MaxAttached = 3 + MaxTurns = 3 + StoredValues <- MCStoredValues + DefaultSearchTurns = 7 + Variant = "LoadWindowed" +INVARIANTS TypeOK TopicReachable PrunedSinceCondense SharedDefault +PROPERTIES FrozenAfterWindow RollingCapped LoadReachable LoadAddsNew +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpToolSelectionLoadMC.cfg b/docs/architecture/tla/McpToolSelectionLoadMC.cfg new file mode 100644 index 00000000000..2c49715f224 --- /dev/null +++ b/docs/architecture/tla/McpToolSelectionLoadMC.cfg @@ -0,0 +1,18 @@ +SPECIFICATION Spec +CONSTANTS + Catalog <- MCCatalog + TopicA <- MCTopicA + TopicB <- MCTopicB + InitialK = 3 + SupplementalK = 2 + SearchTurns = 2 + SearchK = 2 + MaxLoads = 2 + MaxAttached = 3 + MaxTurns = 3 + StoredValues <- MCStoredValues + DefaultSearchTurns = 7 + Variant = "Fixed" +INVARIANTS TypeOK TopicReachable PrunedSinceCondense SharedDefault +PROPERTIES FrozenAfterWindow RollingCapped LoadReachable LoadAddsNew +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpToolSelectionLoadMC.tla b/docs/architecture/tla/McpToolSelectionLoadMC.tla new file mode 100644 index 00000000000..86f3f89ceaa --- /dev/null +++ b/docs/architecture/tla/McpToolSelectionLoadMC.tla @@ -0,0 +1,19 @@ +---- MODULE McpToolSelectionLoadMC ---- +\* Source: McpToolSelectionLifecycle Load. Sink: LoadReachable. +\* Domain: MaxAttached equals InitialK, so the first rank fills the cap. Turn 3 is outside the window. +\* Expect: Fixed holds. LoadCapped fails at the cap. LoadWindowed fails after the window. +\* Result: Fixed holds in 78 states. LoadCapped fails in 18 states and LoadWindowed in 44. No false alarm. +\* LoadAttached uses InitialK = 2, so one relevant tool stays unattached. It fails LoadAddsNew in 6 states. +\* The trace attaches jira_1 and jira_2, and the load returns them again. Fixed on that domain holds in 90. +\* LoadCached uses SearchK = 1, so two loads must attach the two slack tools. It fails in 40 states. +\* PR 2777 round 3 allows MaxLoads = 2 loads. Fixed now holds in 120 states. +\* Review PR 2777 round 4: 0 covered, 0 added, 1 gap. Gap: mcp__my__server__search gets no priority +\* for server my__server (thread 4747824497). The spec treats the ranker as an oracle. +\* Expect: null result. All 14 verdicts stay. A Bm25Ranker test for that server fails on the old code. +\* Result: as expected. 14 of 14 verdicts stay. The old ranker fails the mcp__my__server__search test. +\* Review PR 2777 round 5: 0 covered, 0 added, 2 gaps. Gap: a normalized name ties with the literal name +\* (threads 4748045977, 4748045973). The spec treats the ranker as an oracle. +\* Expect: null result. All 14 verdicts stay. A Bm25Ranker test for each tie fails on the old code. +\* Result: as expected. 14 of 14 verdicts stay. The old ranker fails both literal-match tests. +EXTENDS McpToolSelectionLifecycleMC +==== diff --git a/docs/architecture/tla/McpToolSelectionWindowOneMC.OldReachability.cfg b/docs/architecture/tla/McpToolSelectionWindowOneMC.OldReachability.cfg index d1516031069..20cbecfa330 100644 --- a/docs/architecture/tla/McpToolSelectionWindowOneMC.OldReachability.cfg +++ b/docs/architecture/tla/McpToolSelectionWindowOneMC.OldReachability.cfg @@ -6,11 +6,13 @@ CONSTANTS InitialK = 3 SupplementalK = 2 SearchTurns = 1 + SearchK = 2 + MaxLoads = 2 MaxAttached = 4 MaxTurns = 3 StoredValues <- MCStoredValues DefaultSearchTurns = 7 Variant = "OldReachability" -INVARIANTS TypeOK WindowReachable PrunedSinceCondense RollingCapped SharedDefault -PROPERTY FrozenAfterWindow +INVARIANTS TypeOK WindowReachable PrunedSinceCondense SharedDefault +PROPERTIES FrozenAfterWindow RollingCapped LoadReachable LoadAddsNew CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpToolSelectionWindowOneMC.cfg b/docs/architecture/tla/McpToolSelectionWindowOneMC.cfg index 8703f34f7dc..1251ad8ea1a 100644 --- a/docs/architecture/tla/McpToolSelectionWindowOneMC.cfg +++ b/docs/architecture/tla/McpToolSelectionWindowOneMC.cfg @@ -6,11 +6,13 @@ CONSTANTS InitialK = 3 SupplementalK = 2 SearchTurns = 1 + SearchK = 2 + MaxLoads = 2 MaxAttached = 4 MaxTurns = 3 StoredValues <- MCStoredValues DefaultSearchTurns = 7 Variant = "Fixed" -INVARIANTS TypeOK WindowReachable PrunedSinceCondense RollingCapped SharedDefault -PROPERTY FrozenAfterWindow +INVARIANTS TypeOK WindowReachable PrunedSinceCondense SharedDefault +PROPERTIES FrozenAfterWindow RollingCapped LoadReachable LoadAddsNew CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/McpToolSelectionWindowOneMC.tla b/docs/architecture/tla/McpToolSelectionWindowOneMC.tla index 05508788091..ae6b531d1fe 100644 --- a/docs/architecture/tla/McpToolSelectionWindowOneMC.tla +++ b/docs/architecture/tla/McpToolSelectionWindowOneMC.tla @@ -4,8 +4,8 @@ \* Review: PR 2323 discussion_r4729239711. 0 covered, 1 added, 0 gap. \* Expect: the old antecedent fails after condensation. The fixed antecedent holds. \* Oracle and domain: reuse McpToolSelectionLifecycleMC with SearchTurns = 1 and three turns. -\* Replay: the old antecedent fails in 26 states. Runtime tests confirm the initial-only window-1 behavior. -\* Result: the fixed window-1 config holds in 36 states. OldReachability still fails. +\* Replay: the old antecedent fails in 39 states. Runtime tests confirm the initial-only window-1 behavior. +\* Result: the fixed window-1 config holds in 78 states. OldReachability still fails. Issue 579 added Load. \* The bounded-history property and the condensation trace check both windows on production code. \* Findings: the model property was too strong. The runtime needs no window change. No false alarm remains. \* Cost: each config takes under 1 second. Agent time was not measured. diff --git a/packages/types/src/__tests__/global-settings.test.ts b/packages/types/src/__tests__/global-settings.test.ts index 0e9139160a4..3e74720ac8a 100644 --- a/packages/types/src/__tests__/global-settings.test.ts +++ b/packages/types/src/__tests__/global-settings.test.ts @@ -53,32 +53,42 @@ describe("collapseCommandOutputByDefault global setting", () => { }) }) -describe.each(["mcp.dynamicLoad.threshold", "mcp.dynamicLoad.initialK", "mcp.dynamicLoad.searchTurns"] as const)( - "%s", - (key) => { - it.each([undefined, 1, 30, 50, 100])("round-trips %s through the settings schema", (value) => { - const settings = globalSettingsSchema.parse({ [key]: value }) - expect(globalSettingsSchema.parse(JSON.parse(JSON.stringify(settings)))[key]).toBe(value) - expect(GLOBAL_SETTINGS_KEYS).toContain(key) - }) - it.each([-1, 1.5, NaN, Infinity, "30", null])("rejects %s", (value) => { - expect(globalSettingsSchema.safeParse({ [key]: value }).success).toBe(false) - }) - it("allows zero except for initialK", () => { - expect(globalSettingsSchema.safeParse({ [key]: 0 }).success).toBe(key !== "mcp.dynamicLoad.initialK") - }) - }, -) +describe.each([ + "mcp.dynamicLoad.threshold", + "mcp.dynamicLoad.initialK", + "mcp.dynamicLoad.searchTurns", + "mcp.dynamicLoad.searchK", +] as const)("%s", (key) => { + it.each([undefined, 1, 30, 50, 100])("round-trips %s through the settings schema", (value) => { + const settings = globalSettingsSchema.parse({ [key]: value }) + expect(globalSettingsSchema.parse(JSON.parse(JSON.stringify(settings)))[key]).toBe(value) + expect(GLOBAL_SETTINGS_KEYS).toContain(key) + }) + it.each([-1, 1.5, NaN, Infinity, "30", null])("rejects %s", (value) => { + expect(globalSettingsSchema.safeParse({ [key]: value }).success).toBe(false) + }) + it("allows zero only for threshold and searchTurns", () => { + expect(globalSettingsSchema.safeParse({ [key]: 0 }).success).toBe( + key === "mcp.dynamicLoad.threshold" || key === "mcp.dynamicLoad.searchTurns", + ) + }) +}) describe("runtime MCP routing defaults", () => { it.each([undefined, null, -1, 1.5, NaN, Infinity, "30", {}])("replaces invalid input %j", (value) => { - expect(resolveMcpDynamicLoadSettings(value, value, value)).toEqual({ + expect(resolveMcpDynamicLoadSettings(value, value, value, value)).toEqual({ threshold: 50, initialK: 30, searchTurns: 7, + searchK: 10, }) }) it("preserves a zero threshold, a positive limit and zero search turns", () => { - expect(resolveMcpDynamicLoadSettings(0, 1, 0)).toEqual({ threshold: 0, initialK: 1, searchTurns: 0 }) + expect(resolveMcpDynamicLoadSettings(0, 1, 0, 1)).toEqual({ + threshold: 0, + initialK: 1, + searchTurns: 0, + searchK: 1, + }) }) }) diff --git a/packages/types/src/__tests__/mcp-dynamic-load.property.test.ts b/packages/types/src/__tests__/mcp-dynamic-load.property.test.ts index 6cd14b62ecc..0d77a906481 100644 --- a/packages/types/src/__tests__/mcp-dynamic-load.property.test.ts +++ b/packages/types/src/__tests__/mcp-dynamic-load.property.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest" import { DEFAULT_MCP_DYNAMIC_LOAD_INITIAL_K, + DEFAULT_MCP_DYNAMIC_LOAD_SEARCH_K, DEFAULT_MCP_DYNAMIC_LOAD_SEARCH_TURNS, DEFAULT_MCP_DYNAMIC_LOAD_THRESHOLD, resolveMcpDynamicLoadSettings, @@ -8,27 +9,39 @@ import { const invalid: unknown[] = [undefined, null, "2", {}, [], NaN, Infinity, -Infinity, -1, 0.5] const inputs: unknown[] = [...invalid, 0, 1, 2, 50] +const settings: { key: string; valid: number[]; fallback: number }[] = [ + { key: "threshold", valid: [0, 1, 2, 50], fallback: DEFAULT_MCP_DYNAMIC_LOAD_THRESHOLD }, + { key: "initialK", valid: [1, 2, 50], fallback: DEFAULT_MCP_DYNAMIC_LOAD_INITIAL_K }, + { key: "searchTurns", valid: [0, 1, 2, 50], fallback: DEFAULT_MCP_DYNAMIC_LOAD_SEARCH_TURNS }, + { key: "searchK", valid: [1, 2, 50], fallback: DEFAULT_MCP_DYNAMIC_LOAD_SEARCH_K }, +] +const pairs = settings.flatMap((_, a) => settings.slice(a + 1).map((_, offset) => [a, a + 1 + offset] as const)) describe("MCP setting default invariant", () => { - it("resolves each setting consistently and remains stable across repeated readers", () => { - // Spec: McpToolSelectionLifecycle, SharedDefault. - // Shared-default property: each reader uses the same - // valid value or shared default, including when it receives resolved state. - const resolve = (value: unknown, valid: number[], fallback: number) => - typeof value === "number" && valid.includes(value) ? value : fallback - for (const threshold of inputs) { - for (const initialK of inputs) { - for (const searchTurns of inputs) { - const resolved = resolveMcpDynamicLoadSettings(threshold, initialK, searchTurns) - expect(resolved).toEqual({ - threshold: resolve(threshold, [0, 1, 2, 50], DEFAULT_MCP_DYNAMIC_LOAD_THRESHOLD), - initialK: resolve(initialK, [1, 2, 50], DEFAULT_MCP_DYNAMIC_LOAD_INITIAL_K), - searchTurns: resolve(searchTurns, [0, 1, 2, 50], DEFAULT_MCP_DYNAMIC_LOAD_SEARCH_TURNS), - }) - expect( - resolveMcpDynamicLoadSettings(resolved.threshold, resolved.initialK, resolved.searchTurns), - ).toEqual(resolved) - } + // Spec: McpToolSelectionLifecycle, SharedDefault. Each setting parses alone, so pairs cover every interaction. + it.each(pairs)("resolves settings %i and %i consistently and remains stable across repeated readers", (a, b) => { + for (const x of inputs) { + for (const y of inputs) { + const args: [unknown, unknown, unknown, unknown] = [undefined, undefined, undefined, undefined] + args[a] = x + args[b] = y + const resolved = resolveMcpDynamicLoadSettings(...args) + expect(resolved).toEqual( + Object.fromEntries( + settings.map(({ key, valid, fallback }, index) => { + const value = args[index] + return [key, typeof value === "number" && valid.includes(value) ? value : fallback] + }), + ), + ) + expect( + resolveMcpDynamicLoadSettings( + resolved.threshold, + resolved.initialK, + resolved.searchTurns, + resolved.searchK, + ), + ).toEqual(resolved) } } }) diff --git a/packages/types/src/global-settings.ts b/packages/types/src/global-settings.ts index 721e4a53f62..2ca8270d18d 100644 --- a/packages/types/src/global-settings.ts +++ b/packages/types/src/global-settings.ts @@ -15,7 +15,12 @@ import { toolNamesSchema } from "./tool.js" import { type Keys } from "./type-fu.js" import { languagesSchema } from "./vscode.js" import { providerIdentifiers } from "./provider-identifiers.js" -import { mcpDynamicLoadThresholdSchema, mcpDynamicLoadInitialKSchema, mcpDynamicLoadSearchTurnsSchema } from "./mcp.js" +import { + mcpDynamicLoadThresholdSchema, + mcpDynamicLoadInitialKSchema, + mcpDynamicLoadSearchTurnsSchema, + mcpDynamicLoadSearchKSchema, +} from "./mcp.js" /** * Default delay in milliseconds after writes to allow diagnostics to detect potential problems. @@ -272,6 +277,7 @@ export const globalSettingsSchema = z.object({ "mcp.dynamicLoad.threshold": mcpDynamicLoadThresholdSchema.optional(), "mcp.dynamicLoad.initialK": mcpDynamicLoadInitialKSchema.optional(), "mcp.dynamicLoad.searchTurns": mcpDynamicLoadSearchTurnsSchema.optional(), + "mcp.dynamicLoad.searchK": mcpDynamicLoadSearchKSchema.optional(), mode: z.string().optional(), modeApiConfigs: z.record(z.string(), z.string()).optional(), diff --git a/packages/types/src/mcp.ts b/packages/types/src/mcp.ts index c72ffa697f0..c0cbb88884c 100644 --- a/packages/types/src/mcp.ts +++ b/packages/types/src/mcp.ts @@ -10,6 +10,7 @@ export function isCanonicalMcpToolName(name: string): boolean { export const DEFAULT_MCP_DYNAMIC_LOAD_THRESHOLD = 50 export const DEFAULT_MCP_DYNAMIC_LOAD_INITIAL_K = 30 export const DEFAULT_MCP_DYNAMIC_LOAD_SEARCH_TURNS = 7 +export const DEFAULT_MCP_DYNAMIC_LOAD_SEARCH_K = 10 export const MAX_ATTACHED_DURING_ROLLING = 60 /** The MCP declarations of the newest gated tool build of a task. */ @@ -22,14 +23,21 @@ export interface McpToolStatus { export const mcpDynamicLoadThresholdSchema = z.number().int().min(0) export const mcpDynamicLoadInitialKSchema = z.number().int().min(1) export const mcpDynamicLoadSearchTurnsSchema = z.number().int().min(0) +export const mcpDynamicLoadSearchKSchema = z.number().int().min(1) /** Apply the same validation to persisted values and direct runtime callers. */ -export function resolveMcpDynamicLoadSettings(threshold: unknown, initialK: unknown, searchTurns?: unknown) { +export function resolveMcpDynamicLoadSettings( + threshold: unknown, + initialK: unknown, + searchTurns?: unknown, + searchK?: unknown, +) { return { threshold: mcpDynamicLoadThresholdSchema.safeParse(threshold).data ?? DEFAULT_MCP_DYNAMIC_LOAD_THRESHOLD, initialK: mcpDynamicLoadInitialKSchema.safeParse(initialK).data ?? DEFAULT_MCP_DYNAMIC_LOAD_INITIAL_K, searchTurns: mcpDynamicLoadSearchTurnsSchema.safeParse(searchTurns).data ?? DEFAULT_MCP_DYNAMIC_LOAD_SEARCH_TURNS, + searchK: mcpDynamicLoadSearchKSchema.safeParse(searchK).data ?? DEFAULT_MCP_DYNAMIC_LOAD_SEARCH_K, } } diff --git a/packages/types/src/tool.ts b/packages/types/src/tool.ts index 03c10bc3e70..3e4521fe8f5 100644 --- a/packages/types/src/tool.ts +++ b/packages/types/src/tool.ts @@ -36,6 +36,7 @@ export const toolNames = [ "list_files", "use_mcp_tool", "access_mcp_resource", + "mcp_load", "ask_followup_question", "attempt_completion", "switch_mode", diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index 86cedb85cc6..25d0ef8cc82 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -418,6 +418,7 @@ export type ExtensionState = Pick< "mcp.dynamicLoad.threshold"?: number "mcp.dynamicLoad.initialK"?: number "mcp.dynamicLoad.searchTurns"?: number + "mcp.dynamicLoad.searchK"?: number /** `null` clears the webview value. An absent key keeps it. */ mcpToolStatus?: McpToolStatus | null diff --git a/scripts/check-mcp-tool-selection.ts b/scripts/check-mcp-tool-selection.ts index 6ac667b4883..001666b4657 100644 --- a/scripts/check-mcp-tool-selection.ts +++ b/scripts/check-mcp-tool-selection.ts @@ -47,8 +47,19 @@ async function replay(scenario: Scenario, trace: Action[], fault: Fault): Promis const saves = new Map void>() const admitted = new Set(scenario.saved) let failure: unknown + // The serialized selection saves for one caller at a time. Its current scope names that caller. + const persist = (): Promise => { + const caller = selection["scope"] === scenario.scopes[0] ? 0 : 1 + // Inject loss at commit; staging can repair a mutation made during ranking. + if (fault === "trim-saved") for (const name of scenario.saved ?? []) selection.names.delete(name) + const completion = new Promise((resolve) => { + saves.set(caller, resolve) + }) + return fault === "unawaited-save" ? Promise.resolve() : completion + } const selection = new McpToolSelection( scenario.saved, + persist, (_query, scope) => new Promise((resolve) => { assert.ok(scenario.scopes.includes(scope), "rank must use a caller's scope") @@ -81,15 +92,7 @@ async function replay(scenario: Scenario, trace: Action[], fault: Fault): Promis ? Promise.resolve() : fault === "shared-promise" && preceding ? preceding - : selection.initialize(scenario.scopes[caller], LIMITS, "search", [], () => { - // Inject loss at commit; staging can repair a mutation made during ranking. - if (fault === "trim-saved") - for (const name of scenario.saved ?? []) selection.names.delete(name) - const completion = new Promise((resolve) => { - saves.set(caller, resolve) - }) - return fault === "unawaited-save" ? Promise.resolve() : completion - }) + : selection.initialize(scenario.scopes[caller], LIMITS, "search", []) promises[caller] = promise void promise.then( () => { diff --git a/src/core/assistant-message/NativeToolCallParser.ts b/src/core/assistant-message/NativeToolCallParser.ts index 90da07cc8df..1c3cee4b3a1 100644 --- a/src/core/assistant-message/NativeToolCallParser.ts +++ b/src/core/assistant-message/NativeToolCallParser.ts @@ -640,6 +640,12 @@ export class NativeToolCallParser { } break + case "mcp_load": + if (partialArgs.query !== undefined) { + nativeArgs = { query: partialArgs.query } + } + break + case "apply_patch": if (partialArgs.patch !== undefined) { nativeArgs = { @@ -1002,6 +1008,12 @@ export class NativeToolCallParser { } break + case "mcp_load": + if (args.query !== undefined) { + nativeArgs = { query: args.query } as NativeArgsFor + } + break + case "access_mcp_resource": if (args.server_name !== undefined && args.uri !== undefined) { nativeArgs = { diff --git a/src/core/assistant-message/__tests__/presentAssistantMessage-tool-usage-attribution.spec.ts b/src/core/assistant-message/__tests__/presentAssistantMessage-tool-usage-attribution.spec.ts index 02156f3b3d8..ac24fe44ea9 100644 --- a/src/core/assistant-message/__tests__/presentAssistantMessage-tool-usage-attribution.spec.ts +++ b/src/core/assistant-message/__tests__/presentAssistantMessage-tool-usage-attribution.spec.ts @@ -12,6 +12,7 @@ import { getModeBySlug } from "../../../shared/modes" import type { Task } from "../../task/Task" import type { RequestPolicySnapshot } from "../../prompts/tools/effective-tool-policy" import { useMcpToolTool } from "../../tools/UseMcpToolTool" +import { mcpLoadTool } from "../../tools/McpLoadTool" vi.mock("../../task/Task") vi.mock("../../../shared/modes", async (importOriginal) => { @@ -194,6 +195,26 @@ describe("presentAssistantMessage - tool usage attribution", () => { expect(mockTask.recordToolUsage).toHaveBeenCalledWith("read_file") }) + it("parses an mcp_load call, dispatches it, and records it as mcp_load", async () => { + const handle = vi.spyOn(mcpLoadTool, "handle").mockResolvedValue(undefined) + const parsed = NativeToolCallParser.parseToolCall({ + id: "call_load", + name: "mcp_load", + arguments: JSON.stringify({ query: "send a slack message" }), + }) + mockTask.assistantMessageContent = [{ ...parsed, id: "call_load" }] + + await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot) + + expect(handle).toHaveBeenCalledExactlyOnceWith( + mockTask, + expect.objectContaining({ name: "mcp_load", nativeArgs: { query: "send a slack message" } }), + expect.anything(), + ) + expect(mockTask.recordToolUsage).toHaveBeenCalledExactlyOnceWith("mcp_load") + handle.mockRestore() + }) + it("records a valid dynamic mcp_ tool name as use_mcp_tool", async () => { mockTask.assistantMessageContent = [ { diff --git a/src/core/assistant-message/__tests__/toTelemetryToolName.spec.ts b/src/core/assistant-message/__tests__/toTelemetryToolName.spec.ts index 699cececdda..e24b40b2af0 100644 --- a/src/core/assistant-message/__tests__/toTelemetryToolName.spec.ts +++ b/src/core/assistant-message/__tests__/toTelemetryToolName.spec.ts @@ -30,6 +30,10 @@ describe("toTelemetryToolName", () => { expect(toTelemetryToolName("mcp_my_server_do_thing", false, undefined)).toBe("use_mcp_tool") }) + it("keeps mcp_load as its own name", () => { + expect(toTelemetryToolName("mcp_load", false, undefined)).toBe("mcp_load") + }) + it("maps a malformed mcp_ tool name to use_mcp_tool", () => { expect(toTelemetryToolName("mcp_", false, undefined)).toBe("use_mcp_tool") }) diff --git a/src/core/assistant-message/presentAssistantMessage.ts b/src/core/assistant-message/presentAssistantMessage.ts index 0e991d2c6c8..4e6768f442d 100644 --- a/src/core/assistant-message/presentAssistantMessage.ts +++ b/src/core/assistant-message/presentAssistantMessage.ts @@ -38,6 +38,7 @@ import { newTaskTool } from "../tools/NewTaskTool" import { updateTodoListTool } from "../tools/UpdateTodoListTool" import { runSlashCommandTool } from "../tools/RunSlashCommandTool" import { skillTool } from "../tools/SkillTool" +import { mcpLoadTool } from "../tools/McpLoadTool" import { generateImageTool } from "../tools/GenerateImageTool" import { applyDiffTool as applyDiffToolClass } from "../tools/ApplyDiffTool" import { isValidToolName, validateToolUse } from "../tools/validateToolUse" @@ -61,6 +62,10 @@ export function toTelemetryToolName( return "custom_tool" } + if (toolName === "mcp_load") { + return toolName + } + if (toolName.startsWith("mcp_")) { return "use_mcp_tool" } @@ -528,6 +533,8 @@ async function presentAssistantMessageBlock(cline: Task, policySnapshot: Request return `[${block.name} for '${block.params.server_name}']` case "access_mcp_resource": return `[${block.name} for '${block.params.server_name}']` + case "mcp_load": + return `[${block.name} for '${block.params.query}']` case "ask_followup_question": return `[${block.name} for '${block.params.question}']` case "attempt_completion": @@ -1029,6 +1036,14 @@ async function presentAssistantMessageBlock(cline: Task, policySnapshot: Request toolCallId, }) break + case "mcp_load": + await mcpLoadTool.handle(cline, block as ToolUse<"mcp_load">, { + askApproval, + handleError, + pushToolResult, + toolCallId, + }) + break case "ask_followup_question": await askFollowupQuestionTool.handle(cline, block as ToolUse<"ask_followup_question">, { askApproval, diff --git a/src/core/prompts/tools/native-tools/__tests__/strict-schema-subset.spec.ts b/src/core/prompts/tools/native-tools/__tests__/strict-schema-subset.spec.ts index 8e72bf74399..33e6eed35d9 100644 --- a/src/core/prompts/tools/native-tools/__tests__/strict-schema-subset.spec.ts +++ b/src/core/prompts/tools/native-tools/__tests__/strict-schema-subset.spec.ts @@ -6,7 +6,7 @@ import { getNativeTools } from ".." type FunctionTool = OpenAI.Chat.ChatCompletionFunctionTool describe("native tool strict schema subset", () => { - const tools = getNativeTools().filter((tool): tool is FunctionTool => tool.type === "function") + const tools = getNativeTools({ mcpLoad: true }).filter((tool): tool is FunctionTool => tool.type === "function") it.each(tools.map((tool) => [tool.function.name, tool] as const))( "keeps %s within the portable strict subset", diff --git a/src/core/prompts/tools/native-tools/index.ts b/src/core/prompts/tools/native-tools/index.ts index d5f75b590cd..70d10be3ffb 100644 --- a/src/core/prompts/tools/native-tools/index.ts +++ b/src/core/prompts/tools/native-tools/index.ts @@ -9,6 +9,7 @@ import editTool from "./edit" import executeCommand from "./execute_command" import generateImage from "./generate_image" import listFiles from "./list_files" +import mcpLoadTool from "./mcp_load" import newTask from "./new_task" import readCommandOutput from "./read_command_output" import { createReadFileTool, type ReadFileToolOptions } from "./read_file" @@ -31,6 +32,8 @@ export type { ReadFileToolOptions } from "./read_file" export interface NativeToolsOptions { /** Whether the model supports image processing (default: false) */ supportsImages?: boolean + /** Whether dynamic MCP tool loading limits the attached MCP tools (default: false) */ + mcpLoad?: boolean } /** @@ -40,7 +43,7 @@ export interface NativeToolsOptions { * @returns Array of native tool definitions */ export function getNativeTools(options: NativeToolsOptions = {}): OpenAI.Chat.ChatCompletionTool[] { - const { supportsImages = false } = options + const { supportsImages = false, mcpLoad = false } = options const readFileOptions: ReadFileToolOptions = { supportsImages, @@ -68,5 +71,6 @@ export function getNativeTools(options: NativeToolsOptions = {}): OpenAI.Chat.Ch switchMode, updateTodoList, writeToFile, + ...(mcpLoad ? [mcpLoadTool] : []), ] satisfies OpenAI.Chat.ChatCompletionTool[] } diff --git a/src/core/prompts/tools/native-tools/mcp_load.ts b/src/core/prompts/tools/native-tools/mcp_load.ts new file mode 100644 index 00000000000..b5214477396 --- /dev/null +++ b/src/core/prompts/tools/native-tools/mcp_load.ts @@ -0,0 +1,30 @@ +import type OpenAI from "openai" + +const MCP_LOAD_DESCRIPTION = `Attach more MCP tools to this task. Your tool list can omit some available MCP tools. Use this tool when you need an MCP tool that is not in your tool list. + +Describe the task that the tool must do. The result lists the matching tools. Attached tools are available from your next request. + +Example: Find tools to send a Slack message +{ "query": "send a message to a Slack channel" }` + +const QUERY_PARAMETER_DESCRIPTION = `Words that describe the tool you need, for example the service and the action` + +export default { + type: "function", + function: { + name: "mcp_load", + description: MCP_LOAD_DESCRIPTION, + strict: true, + parameters: { + type: "object", + properties: { + query: { + type: "string", + description: QUERY_PARAMETER_DESCRIPTION, + }, + }, + required: ["query"], + additionalProperties: false, + }, + }, +} satisfies OpenAI.Chat.ChatCompletionTool diff --git a/src/core/task-persistence/__tests__/mcpAttachments.integration.spec.ts b/src/core/task-persistence/__tests__/mcpAttachments.integration.spec.ts index 72b6e9be4ca..7a32dd0cce2 100644 --- a/src/core/task-persistence/__tests__/mcpAttachments.integration.spec.ts +++ b/src/core/task-persistence/__tests__/mcpAttachments.integration.spec.ts @@ -12,7 +12,7 @@ describe("MCP attachment history round trip", () => { const peer = new TaskHistoryStore(directory) const restored = new TaskHistoryStore(directory) try { - const selection = new McpToolSelection(["mcp--catalog--initial"]) + const selection = new McpToolSelection(["mcp--catalog--initial"], async () => {}) const snapshot = () => taskMetadata({ taskId: "reset-task", @@ -36,13 +36,17 @@ describe("MCP attachment history round trip", () => { expect(saved?.attachedMcpToolNames).toBeUndefined() expect(saved?.mcpToolSelectionEpoch).toBe(1) const rank = vi.fn(async () => ["mcp--catalog--new"]) - const resumed = new McpToolSelection(saved?.attachedMcpToolNames, rank, saved?.mcpToolSelectionEpoch) + const resumed = new McpToolSelection( + saved?.attachedMcpToolNames, + async () => {}, + rank, + saved?.mcpToolSelectionEpoch, + ) await resumed.initialize( ["initial", "new"].map((toolName) => ({ serverName: "catalog", toolName, description: toolName })), { initialK: 1, searchTurns: 7 }, "new topic", [], - async () => {}, ) expect(rank).toHaveBeenCalledTimes(1) expect([...resumed.names]).toEqual(["mcp--catalog--new"]) @@ -77,22 +81,17 @@ describe("MCP attachment history round trip", () => { const rank = vi.fn(async () => ["mcp--catalog--new"]) const selection = new McpToolSelection( saved?.attachedMcpToolNames, + async () => {}, rank, saved?.mcpToolSelectionEpoch, saved?.mcpToolSelectionMessageIndex, ) const scope = ["initial", "new"].map((toolName) => ({ serverName: "catalog", toolName, description: "" })) const message = { role: "user" as const, content: "search" } - await selection.initialize(scope, { initialK: 1, searchTurns }, "search", [message], async () => {}) + await selection.initialize(scope, { initialK: 1, searchTurns }, "search", [message]) expect(rank).not.toHaveBeenCalled() expect([...selection.names]).toEqual(["mcp--catalog--initial"]) - await selection.initialize( - scope, - { initialK: 1, searchTurns }, - "search", - [message, message], - async () => {}, - ) + await selection.initialize(scope, { initialK: 1, searchTurns }, "search", [message, message]) expect(rank).toHaveBeenCalledTimes(searchTurns === 1 ? 0 : 1) expect([...selection.names]).toEqual( searchTurns === 1 ? ["mcp--catalog--initial"] : ["mcp--catalog--initial", "mcp--catalog--new"], diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index cbef22d7b3d..f9d4acf1276 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -56,6 +56,7 @@ import { providerIdentifiers, type MentionSegment, attachedMcpToolNamesSchema, + resolveMcpDynamicLoadSettings, } from "@roo-code/types" import { TelemetryService } from "@roo-code/telemetry" @@ -100,7 +101,7 @@ import { SYSTEM_PROMPT } from "../prompts/system" import type { InstructionFailureCollector } from "../prompts/sections/custom-instructions" import { partitionDisabledToolsForProtocol } from "../prompts/tools/effective-tool-policy" import { buildNativeToolsArrayWithRestrictions } from "./build-tools" -import { McpToolSelection, type McpSelectionLimits } from "./mcpToolSelection" +import { McpToolSelection, type McpSelectionLimits, type McpToolMatch } from "./mcpToolSelection" import { McpToolStatusTracker } from "./mcpToolStatus" import type { ToolDoc } from "../../services/tools/types" @@ -439,6 +440,12 @@ export class Task extends EventEmitter implements TaskLike { this.instructionRefreshGeneration++ } + /** Spec: McpToolSelectionLifecycle Condense. Each condensation path calls this after a summary. */ + private afterSummary(): void { + this.armInstructionRefresh() + this.mcpToolSelection.reset() + } + // TaskStatus idleAsk?: ClineMessage resumableAsk?: ClineMessage @@ -793,6 +800,7 @@ export class Task extends EventEmitter implements TaskLike { const savedMcpToolNames = attachedMcpToolNamesSchema.parse(historyItem?.attachedMcpToolNames) this.mcpToolSelection = new McpToolSelection( savedMcpToolNames, + () => this.persistMcpToolSelection(), undefined, historyItem?.mcpToolSelectionEpoch, historyItem?.mcpToolSelectionMessageIndex, @@ -2846,8 +2854,7 @@ export class Task extends EventEmitter implements TaskLike { return } if (summary) { - this.armInstructionRefresh() - this.mcpToolSelection.reset() + this.afterSummary() } await this.overwriteApiConversationHistory(messages) @@ -3116,17 +3123,28 @@ export class Task extends EventEmitter implements TaskLike { limits, this.metadata.task ?? "", this.apiConversationHistory, - async () => { - try { - if (!(await this.saveClineMessages(true, true))) - throw new Error("Failed to save MCP tool selection") - } catch (error) { - console.error("[Task] Failed to persist MCP tool selection; keeping in-memory selection:", error) - } - }, ) } + public async loadMcpTools(query: string): Promise { + const state = await this.providerRef.deref()?.getState() + const { searchK } = resolveMcpDynamicLoadSettings( + undefined, + undefined, + undefined, + state?.["mcp.dynamicLoad.searchK"], + ) + return this.mcpToolSelection.load(query, searchK) + } + + private async persistMcpToolSelection(): Promise { + try { + if (!(await this.saveClineMessages(true, true))) throw new Error("Failed to save MCP tool selection") + } catch (error) { + console.error("[Task] Failed to persist MCP tool selection; keeping in-memory selection:", error) + } + } + private async startTask(task?: string, images?: string[]): Promise { try { // `conversationHistory` (for API) and `clineMessages` (for webview) @@ -5715,8 +5733,7 @@ export class Task extends EventEmitter implements TaskLike { if (this.abort || this.abandoned) return if (truncateResult.summary) { - this.armInstructionRefresh() - this.mcpToolSelection.reset() + this.afterSummary() } if (truncateResult.messages !== this.apiConversationHistory) { await this.overwriteApiConversationHistory(truncateResult.messages) @@ -5993,8 +6010,7 @@ export class Task extends EventEmitter implements TaskLike { if (this.abort || this.abandoned) return if (truncateResult.summary) { - this.armInstructionRefresh() - this.mcpToolSelection.reset() + this.afterSummary() } if (truncateResult.messages !== this.apiConversationHistory) { await this.overwriteApiConversationHistory(truncateResult.messages) diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index df05cf35d07..73b53b16133 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -5979,11 +5979,13 @@ describe("Cline", () => { expect(names.filter((name) => name.startsWith("mcp--"))).toHaveLength(expected) if (historyCall) expect(names).toContain("mcp--catalog--tool_99") expect(names).toContain("read_file") - expect(names).not.toContain("mcp_load") - if (provider === providerIdentifiers.gemini) + expect(names.includes("mcp_load")).toBe(expected < 100) + if (provider === providerIdentifiers.gemini) { expect( metadata?.allowedFunctionNames?.filter((name) => name.startsWith("mcp--")), ).toHaveLength(expected) + expect(metadata?.allowedFunctionNames?.includes("mcp_load")).toBe(expected < 100) + } }, ) diff --git a/src/core/task/__tests__/build-tools-dynamic-load.integration.spec.ts b/src/core/task/__tests__/build-tools-dynamic-load.integration.spec.ts index 7e794c035d1..5245bb565ab 100644 --- a/src/core/task/__tests__/build-tools-dynamic-load.integration.spec.ts +++ b/src/core/task/__tests__/build-tools-dynamic-load.integration.spec.ts @@ -39,7 +39,7 @@ afterEach(() => { vi.restoreAllMocks() }) -function setup(count: number, savedNames?: string[]) { +function setup(count: number, savedNames?: string[], state: Record = {}) { const server: McpServer = { name: "catalog", config: "{}", @@ -53,7 +53,7 @@ function setup(count: number, savedNames?: string[]) { const provider = { context: makeExtensionContext({ globalStorageUri: makeUri("/test-storage") }), getMcpHub: () => ({ getServers: () => servers }), - getState: async () => ({ mode: "code", currentApiConfigName: "default" }), + getState: async () => ({ mode: "code", currentApiConfigName: "default", ...state }), log: vi.fn(), postStateToWebviewWithoutClineMessages: vi.fn().mockResolvedValue(undefined), } as unknown as ClineProvider @@ -142,10 +142,10 @@ describe.each([false, true])("MCP dynamic loading (all definitions: %s)", (inclu const attached = declarations.filter((name) => name.startsWith("mcp--")) expect(attached).toHaveLength(initialK ?? 30) expect(new Set(attached)).toEqual(task.attachedMcpToolNames) - expect(declarations.filter((name) => !name.startsWith("mcp--"))).toEqual(names(baseline.tools)) - expect(declarations).not.toContain("mcp_load") + expect(declarations.filter((name) => !name.startsWith("mcp--"))).toEqual([...names(baseline.tools), "mcp_load"]) if (includeAllToolsWithRestrictions) { expect(result.allowedFunctionNames?.filter((name) => name.startsWith("mcp--"))).toEqual(attached) + expect(result.allowedFunctionNames).toContain("mcp_load") } }) @@ -260,3 +260,89 @@ describe.each([false, true])("MCP dynamic loading (all definitions: %s)", (inclu expect(callable.some((name) => name.startsWith("mcp--"))).toBe(false) }) }) + +describe.each([false, true])("mcp_load (all definitions: %s)", (includeAllToolsWithRestrictions) => { + const slackTool = { name: "slack_send", description: "send a slack message" } + + it.each([ + { count: 50, searchTurns: undefined, declared: false }, + { count: 51, searchTurns: undefined, declared: true }, + { count: 100, searchTurns: 0, declared: false }, + { count: 100, searchTurns: 1, declared: true }, + ])( + "declares mcp_load $declared for $count tools and searchTurns $searchTurns", + async ({ count, searchTurns, declared }) => { + const { task, options } = setup(count) + const result = await buildNativeToolsArrayWithRestrictions({ + ...options, + mcpDynamicLoadSearchTurns: searchTurns, + includeAllToolsWithRestrictions, + }) + expect(names(result.tools).includes("mcp_load")).toBe(declared) + expect(result.allowedFunctionNames?.includes("mcp_load")).toBe( + includeAllToolsWithRestrictions ? declared : undefined, + ) + if (!declared) expect(await task.loadMcpTools("slack")).toBeUndefined() + }, + ) + + it("does not declare mcp_load when policy disables it", async () => { + const { options } = setup(100) + const result = await buildNativeToolsArrayWithRestrictions({ + ...options, + disabledTools: ["mcp_load"], + includeAllToolsWithRestrictions, + }) + expect(names(result.tools).includes("mcp_load")).toBe(includeAllToolsWithRestrictions) + expect(result.allowedFunctionNames?.includes("mcp_load")).toBe( + includeAllToolsWithRestrictions ? false : undefined, + ) + }) + + it("declares a loaded tool in the next build and saves it", async () => { + const { server, task, options } = setup(100) + server.tools?.push(slackTool) + const build = () => buildNativeToolsArrayWithRestrictions({ ...options, includeAllToolsWithRestrictions }) + const first = await build() + expect(names(first.tools)).not.toContain("mcp--catalog--slack_send") + + const matches = await task.loadMcpTools("send a slack message") + expect(matches?.[0]).toEqual({ + name: "mcp--catalog--slack_send", + description: slackTool.description, + added: true, + }) + expect(task["saveClineMessages"]).toHaveBeenCalledTimes(2) + + const second = await build() + expect(names(second.tools)).toContain("mcp--catalog--slack_send") + if (includeAllToolsWithRestrictions) expect(second.allowedFunctionNames).toContain("mcp--catalog--slack_send") + expect(task.mcpToolStatus.value?.attachedToolNames).toContain("mcp--catalog--slack_send") + }) + + it.each([ + { searchK: undefined, expected: 10 }, + { searchK: 2, expected: 2 }, + ])("attaches $expected tools for searchK $searchK", async ({ searchK, expected }) => { + const { task, options } = setup(100, undefined, { "mcp.dynamicLoad.searchK": searchK }) + await buildNativeToolsArrayWithRestrictions({ + ...options, + mcpDynamicLoadInitialK: 3, + includeAllToolsWithRestrictions, + }) + const matches = await task.loadMcpTools("search tickets") + expect(matches).toHaveLength(expected) + }) + + it("drops a loaded tool that leaves the scope", async () => { + const { server, task, options } = setup(100) + server.tools?.push(slackTool) + const build = () => buildNativeToolsArrayWithRestrictions({ ...options, includeAllToolsWithRestrictions }) + await build() + await task.loadMcpTools("send a slack message") + server.tools = server.tools?.filter((tool) => tool !== slackTool) + const result = await build() + expect(names(result.tools)).not.toContain("mcp--catalog--slack_send") + expect(result.allowedFunctionNames ?? []).not.toContain("mcp--catalog--slack_send") + }) +}) diff --git a/src/core/task/__tests__/mcpToolSelection.spec.ts b/src/core/task/__tests__/mcpToolSelection.spec.ts index 35284c3419b..5c254db1732 100644 --- a/src/core/task/__tests__/mcpToolSelection.spec.ts +++ b/src/core/task/__tests__/mcpToolSelection.spec.ts @@ -25,15 +25,15 @@ describe("MCP selection scope invariant", () => { async ({ historical, toolNames }) => { const scope = [tools[0], ...toolNames.map((toolName) => ({ ...tools[0], toolName }))] const rank = vi.fn<(_query: string, _scope: ToolDoc[], _k: number) => Promise>() - const selection = new McpToolSelection([names[0]], rank) + const persist = vi.fn().mockResolvedValue(undefined) + const selection = new McpToolSelection([names[0]], persist, rank) const history: Anthropic.MessageParam[] = [ { role: "assistant", content: [{ type: "tool_use", id: "historical", name: historical, input: {} }], }, ] - const persist = vi.fn().mockResolvedValue(undefined) - await selection.initialize(scope, limits(1), "search", history, persist) + await selection.initialize(scope, limits(1), "search", history) const canonicalNames = toolNames.map((toolName) => buildMcpToolName("catalog", toolName)) const expected = canonicalNames.includes(historical) ? historical @@ -48,7 +48,6 @@ describe("MCP selection scope invariant", () => { limits(1), "search", history, - persist, ) expect(selection.names.has("mcp--catalog--get-info")).toBe(true) expect(selection.names.has(expected)).toBe(true) @@ -61,11 +60,11 @@ describe("MCP selection scope invariant", () => { for (const saved of selections) { for (const first of scopes) { for (const second of scopes) { - const selection = new McpToolSelection(saved) const persist = vi.fn().mockResolvedValue(undefined) + const selection = new McpToolSelection(saved, persist) for (const scope of [first, second]) { const before = [...selection.names] - await selection.initialize(scope, limits(1), "search", [], persist) + await selection.initialize(scope, limits(1), "search", []) for (const name of before) expect(selection.names.has(name)).toBe(true) if (saved?.length !== 0 && scope.length > 0) { expect( @@ -86,10 +85,10 @@ describe("MCP selection scope invariant", () => { release = resolve }) const rank = vi.spyOn(ToolRouter.getInstance(), "attachInitial").mockReturnValueOnce(gate) - const selection = new McpToolSelection() const persist = vi.fn().mockResolvedValue(undefined) - const first = selection.initialize([tools[0]], limits(1), "search", [], persist) - const second = selection.initialize([tools[1]], limits(1), "search", [], persist) + const selection = new McpToolSelection(undefined, persist) + const first = selection.initialize([tools[0]], limits(1), "search", []) + const second = selection.initialize([tools[1]], limits(1), "search", []) release([names[0]]) await Promise.all([first, second]) expect(rank).toHaveBeenCalledTimes(2) @@ -97,18 +96,18 @@ describe("MCP selection scope invariant", () => { }) it.each([false, true])("rechecks live scope after initialization (blank task: %s)", async (blank) => { - const selection = new McpToolSelection() const persist = vi.fn().mockResolvedValue(undefined) - await selection.initialize([tools[0]], limits(1), blank ? "" : "search", [], persist) - await selection.initialize([tools[1]], limits(1), blank ? "" : "search", [], persist) + const selection = new McpToolSelection(undefined, persist) + await selection.initialize([tools[0]], limits(1), blank ? "" : "search", []) + await selection.initialize([tools[1]], limits(1), blank ? "" : "search", []) expect([...selection.names]).toEqual(names) expect(persist).toHaveBeenCalledTimes(2) }) it("preserves an explicit empty selection without ranking", async () => { const rank = vi.spyOn(ToolRouter.getInstance(), "attachInitial") - const selection = new McpToolSelection([]) - await selection.initialize(tools, limits(1), "search", [], vi.fn()) + const selection = new McpToolSelection([], vi.fn()) + await selection.initialize(tools, limits(1), "search", []) expect(rank).not.toHaveBeenCalled() expect([...selection.names]).toEqual([]) }) @@ -145,10 +144,9 @@ describe("ranking on the latest user message", () => { function setup(saved?: string[], searchTurns = DEFAULT_MCP_DYNAMIC_LOAD_SEARCH_TURNS) { const rank = vi.fn<(_query: string, _scope: ToolDoc[], _k: number) => Promise>() - const selection = new McpToolSelection(saved, rank) - const persist = vi.fn().mockResolvedValue(undefined) + const selection = new McpToolSelection(saved, vi.fn().mockResolvedValue(undefined), rank) const select = (history: ApiMessage[]) => - selection.initialize(allTools, { initialK: 5, searchTurns }, "search jira tickets", history, persist) + selection.initialize(allTools, { initialK: 5, searchTurns }, "search jira tickets", history) return { rank, selection, select } } @@ -202,8 +200,8 @@ describe("ranking on the latest user message", () => { it.each([undefined, []])("saves an empty initial rank only when selection is absent (%s)", async (saved) => { const persist = vi.fn(async () => {}) const rank = vi.fn(async () => []) - const selection = new McpToolSelection(saved, rank) - await selection.initialize(allTools, limits(5), "jira", [], persist) + const selection = new McpToolSelection(saved, persist, rank) + await selection.initialize(allTools, limits(5), "jira", []) expect(selection.initialized).toBe(true) expect([...selection.names]).toEqual([]) expect(persist).toHaveBeenCalledTimes(saved === undefined ? 1 : 0) @@ -229,12 +227,12 @@ describe("ranking on the latest user message", () => { const rank = vi.fn(async (_query: string, candidates: ToolDoc[], k: number) => candidates.slice(0, k).map((tool) => buildMcpToolName(tool.serverName, tool.toolName)), ) - const selection = new McpToolSelection(undefined, rank) + const selection = new McpToolSelection(undefined, async () => {}, rank) const history: ApiMessage[] = [] for (let turn = 1; turn <= count; turn++) { history.push(userTurn("continue")) - await selection.initialize(scope, limits(1), "continue", history, async () => {}) - await selection.initialize(scope, limits(1), "continue", [...history, toolTurn(`${turn}`)], async () => {}) + await selection.initialize(scope, limits(1), "continue", history) + await selection.initialize(scope, limits(1), "continue", [...history, toolTurn(`${turn}`)]) expect(rank).toHaveBeenCalledTimes(turn) expect(selection.names.size).toBe(1 + 7 * (turn - 1)) } @@ -329,16 +327,16 @@ describe("selection review invariants", () => { it.each([1, 2, 7])("does not rank a saved message again with window %s", async (searchTurns) => { const rank = vi.fn(async () => [names[1]]) const persist = vi.fn(async () => {}) - const selection = new McpToolSelection([names[0]], rank, 0, 0) - await selection.initialize(tools, { initialK: 1, searchTurns }, "search", [user("same")], persist) + const selection = new McpToolSelection([names[0]], persist, rank, 0, 0) + await selection.initialize(tools, { initialK: 1, searchTurns }, "search", [user("same")]) expect(rank).not.toHaveBeenCalled() - await selection.initialize(tools, { initialK: 1, searchTurns }, "search", [user("same"), user("same")], persist) + await selection.initialize(tools, { initialK: 1, searchTurns }, "search", [user("same"), user("same")]) expect(rank).toHaveBeenCalledTimes(searchTurns === 1 ? 0 : 1) }) it("keeps a legacy restored selection when searchTurns is 1", async () => { const rank = vi.fn(async () => [names[1]]) - const selection = new McpToolSelection([names[0]], rank) - await selection.initialize(tools, { initialK: 1, searchTurns: 1 }, "search", [user("search")], async () => {}) + const selection = new McpToolSelection([names[0]], async () => {}, rank) + await selection.initialize(tools, { initialK: 1, searchTurns: 1 }, "search", [user("search")]) expect(rank).not.toHaveBeenCalled() expect([...selection.names]).toEqual([names[0]]) }) @@ -351,9 +349,9 @@ describe("selection review invariants", () => { release = resolve }), ) - const selection = new McpToolSelection(supplement ? [names[0]] : undefined, rank) const persist = vi.fn(async () => {}) - const pending = selection.initialize(tools, limits(1), "search", [user("search")], persist) + const selection = new McpToolSelection(supplement ? [names[0]] : undefined, persist, rank) + const pending = selection.initialize(tools, limits(1), "search", [user("search")]) selection.reset() release([names[1]]) await pending @@ -362,7 +360,7 @@ describe("selection review invariants", () => { expect(selection.lastRankedMessage).toBe(-1) expect(persist).not.toHaveBeenCalled() rank.mockResolvedValue([names[0]]) - await selection.initialize(tools, limits(1), "search", [user("search")], persist) + await selection.initialize(tools, limits(1), "search", [user("search")]) expect(rank.mock.calls.at(-1)).toEqual(["search", tools, 1]) expect(persist).toHaveBeenCalledTimes(1) }) @@ -371,12 +369,12 @@ describe("selection review invariants", () => { const saved = [names[0], ...Array.from({ length: size - 1 }, (_, i) => `mcp--other--t${i}`)] const third = { ...tools[0], toolName: "c" } const rank = vi.fn(async (_query: string, _scope: ToolDoc[], k: number) => ["mcp--catalog--c"].slice(0, k)) - const selection = new McpToolSelection(saved, rank) + const selection = new McpToolSelection(saved, async () => {}, rank) const history: ApiMessage[] = [ user("search"), { role: "assistant", content: [{ type: "tool_use", id: "used", name: names[1], input: {} }] }, ] - await selection.initialize([...tools, third], limits(1), "search", history, async () => {}) + await selection.initialize([...tools, third], limits(1), "search", history) expect(selection.names.size).toBeLessThanOrEqual(Math.max(60, size + 1)) expect(selection.names.has(names[1])).toBe(true) if (size < 59) @@ -384,3 +382,191 @@ describe("selection review invariants", () => { else expect(rank).not.toHaveBeenCalled() }) }) + +describe("mcp_load", () => { + const jira: ToolDoc[] = Array.from({ length: 70 }, (_, i) => ({ + serverName: "jira", + toolName: `t${i}`, + description: "jira", + })) + const slack: ToolDoc = { serverName: "slack", toolName: "send", description: "slack\nsecond line" } + const scope = [...jira, slack] + const nameOf = (tool: ToolDoc) => buildMcpToolName(tool.serverName, tool.toolName) + const slackName = nameOf(slack) + const byTopic = async (query: string, docs: ToolDoc[], k: number) => + docs + .filter((tool) => query.includes(tool.description.split("\n")[0])) + .slice(0, k) + .map(nameOf) + const userTurn = (text: string): ApiMessage => ({ + role: "user", + content: [{ type: "text", text: `\n${text}\n` }], + }) + const limits = { initialK: 30, searchTurns: 7 } + + async function built(size: number, turns: number) { + const history = Array.from({ length: turns }, () => userTurn("jira")) + const rank = vi.fn(byTopic) + const persist = vi.fn().mockResolvedValue(undefined) + const selection = new McpToolSelection(jira.slice(0, size).map(nameOf), persist, rank, 0, turns - 1) + await selection.initialize(scope, limits, "jira", history) + return { rank, selection, persist, history } + } + + // LoadReachable: the window and the cap do not limit a load. + it.each([0, 59, 60, 70].flatMap((size) => [1, 7, 8].map((turns) => ({ size, turns }))))( + "attaches the requested tool with $size selected after $turns user messages", + async ({ size, turns }) => { + const { rank, selection, persist } = await built(size, turns) + expect(rank).not.toHaveBeenCalled() + const first = await selection.load("slack", 10) + expect(first).toEqual([{ name: slackName, description: slack.description, added: true }]) + expect(selection.names.size).toBe(size + 1) + expect(rank.mock.calls[0][1]).toEqual(scope.slice(size)) + const again = await selection.load("slack", 10) + expect(again).toEqual([{ name: slackName, description: slack.description, added: false }]) + expect(selection.names.size).toBe(size + 1) + expect(persist).toHaveBeenCalledTimes(1) + expect(selection.lastRankedMessage).toBe(turns - 1) + }, + ) + + it("leaves the next user message its supplemental rank", async () => { + const { rank, selection, history } = await built(30, 1) + await selection.load("slack", 10) + await selection.initialize(scope, limits, "jira", [...history, userTurn("jira again")]) + expect(rank).toHaveBeenCalledTimes(2) + expect(rank.mock.calls[1][2]).toBe(7) + expect(selection.lastRankedMessage).toBe(1) + }) + + it("returns undefined before the first gated build", async () => { + const rank = vi.fn(byTopic) + const selection = new McpToolSelection(undefined, vi.fn(), rank) + expect(await selection.load("slack", 10)).toBeUndefined() + expect(rank).not.toHaveBeenCalled() + }) + + it("returns undefined after a reset until the next build", async () => { + const { rank, selection, persist } = await built(0, 1) + selection.reset() + expect(await selection.load("slack", 10)).toBeUndefined() + expect(rank).not.toHaveBeenCalled() + expect(persist).not.toHaveBeenCalled() + expect(selection.names.size).toBe(0) + }) + + it("ignores ranked names outside the scope", async () => { + const selection = new McpToolSelection([], vi.fn().mockResolvedValue(undefined), async () => [ + "mcp--gone--tool", + slackName, + ]) + await selection.initialize(scope, limits, "jira", []) + expect((await selection.load("slack", 10))?.map((match) => match.name)).toEqual([slackName]) + expect(selection.names.has("mcp--gone--tool")).toBe(false) + }) + + it("discards a load that completes after a reset", async () => { + const persist = vi.fn().mockResolvedValue(undefined) + let finish!: (names: string[]) => void + const deferred = new McpToolSelection( + [], + persist, + () => + new Promise((resolve) => { + finish = resolve + }), + ) + await deferred.initialize(scope, limits, "jira", []) + const load = deferred.load("slack", 10) + await vi.waitFor(() => expect(finish).toBeDefined()) + deferred.reset() + finish([slackName]) + expect(await load).toBeUndefined() + expect([...deferred.names]).toEqual([]) + expect(persist).not.toHaveBeenCalled() + }) + + // LoadReported: a result lists only names that the selection holds. + it.each([ + { resetDuringSave: false, expected: [slackName] }, + { resetDuringSave: true, expected: undefined }, + ])("reports the load when resetDuringSave is $resetDuringSave", async ({ resetDuringSave, expected }) => { + const persist = vi.fn(async () => { + if (resetDuringSave) selection.reset() + }) + const selection = new McpToolSelection([], persist, byTopic) + await selection.initialize(scope, limits, "jira", []) + const result = await selection.load("slack", 10) + expect(result?.map((match) => match.name)).toEqual(expected) + expect(persist).toHaveBeenCalledTimes(1) + if (result) for (const match of result) expect(selection.names.has(match.name)).toBe(true) + }) + + it("waits for a pending selection before it ranks", async () => { + const order: string[] = [] + let finish!: (names: string[]) => void + const persist = vi.fn().mockResolvedValue(undefined) + const selection = new McpToolSelection(undefined, persist, async (query, docs, k) => { + order.push(query) + if (query === "jira") return new Promise((resolve) => (finish = resolve)) + return byTopic(query, docs, k) + }) + const build = selection.initialize(scope, limits, "jira", []) + const load = selection.load("slack", 10) + await vi.waitFor(() => expect(finish).toBeDefined()) + expect(order).toEqual(["jira"]) + finish([nameOf(jira[0])]) + await build + expect((await load)?.map((match) => match.name)).toEqual([slackName]) + expect(order).toEqual(["jira", "slack"]) + }) + + // LoadAddsNew: attached tools do not take the slots of a relevant tool that is not attached. + it.each([1, 2, 3].flatMap((k) => [0, 1, 2, 3].map((attached) => ({ k, attached }))))( + "attaches a new relevant tool with k $k and $attached of 4 relevant tools attached", + async ({ k, attached }) => { + const relevant = jira.slice(0, 4) + const attachedFirst = async (_query: string, docs: ToolDoc[], limit: number) => + docs + .filter((tool) => relevant.includes(tool)) + .slice(0, limit) + .map(nameOf) + const selection = new McpToolSelection( + relevant.slice(0, attached).map(nameOf), + vi.fn().mockResolvedValue(undefined), + attachedFirst, + 0, + 0, + ) + await selection.initialize(scope, limits, "jira", [userTurn("jira")]) + const expected = relevant + .slice(attached, attached + k) + .map((tool) => ({ name: nameOf(tool), description: tool.description, added: true })) + expect(await selection.load("jira", k)).toEqual(expected) + }, + ) + + it("attaches the next relevant tool when the same query loads again", async () => { + const relevant = jira.slice(0, 2) + const attachedFirst = async (_query: string, docs: ToolDoc[], limit: number) => + docs + .filter((tool) => relevant.includes(tool)) + .slice(0, limit) + .map(nameOf) + const selection = new McpToolSelection([], vi.fn().mockResolvedValue(undefined), attachedFirst, 0, 0) + await selection.initialize(scope, limits, "jira", [userTurn("jira")]) + const added = (tool: ToolDoc) => [{ name: nameOf(tool), description: tool.description, added: true }] + + expect(await selection.load("jira", 1)).toEqual(added(relevant[0])) + expect(await selection.load("jira", 1)).toEqual(added(relevant[1])) + }) + + it("reports the attached matches when every relevant tool is attached", async () => { + const selection = new McpToolSelection([slackName], vi.fn().mockResolvedValue(undefined), byTopic, 0, 0) + await selection.initialize(scope, limits, "jira", [userTurn("jira")]) + expect(await selection.load("slack", 2)).toEqual([ + { name: slackName, description: slack.description, added: false }, + ]) + }) +}) diff --git a/src/core/task/build-tools.ts b/src/core/task/build-tools.ts index 21c16ffb752..1a82c6a2dac 100644 --- a/src/core/task/build-tools.ts +++ b/src/core/task/build-tools.ts @@ -114,18 +114,35 @@ export async function buildNativeToolsArrayWithRestrictions(options: BuildToolsO modelInfo, } + // Resolve mode config to get allowedMcpServers for MCP server filtering. + const modeConfig = getModeBySlug(mode ?? defaultModeSlug, customModes) + const allowedMcpServers = modeConfig?.allowedMcpServers + + // Filter MCP tools based on mode restrictions and the effective tool policy: + // the same disabledTools/modelInfo the native filter consumes also gate the + // dynamic mcp--* declarations, which all represent use_mcp_tool. + const mcpTools = getMcpServerTools(mcpHub, allowedMcpServers) + let filteredMcpTools = filterMcpToolsForMode(mcpTools, mode, customModes, experiments, { + disabledTools, + modelInfo, + }) + const { threshold, initialK, searchTurns } = resolveMcpDynamicLoadSettings( + options.mcpDynamicLoadThreshold, + options.mcpDynamicLoadInitialK, + options.mcpDynamicLoadSearchTurns, + ) + const totalScoped = filteredMcpTools.length + const gated = options.task !== undefined && searchTurns > 0 && totalScoped > threshold + // Check if the model supports images for read_file tool description. const supportsImages = modelInfo?.supportsImages ?? false // Build native tools with dynamic read_file tool based on settings. const nativeTools = getNativeTools({ supportsImages, + mcpLoad: gated, }) - // Resolve mode config to get allowedMcpServers for MCP server filtering. - const modeConfig = getModeBySlug(mode ?? defaultModeSlug, customModes) - const allowedMcpServers = modeConfig?.allowedMcpServers - // Filter native tools based on mode restrictions. The allowlist is forwarded so the // access_mcp_resource availability check only considers resources from allowed servers; // otherwise a restricted mode could still read resources from disallowed servers. @@ -140,22 +157,7 @@ export async function buildNativeToolsArrayWithRestrictions(options: BuildToolsO allowedMcpServers, ) - // Filter MCP tools based on mode restrictions and the effective tool policy: - // the same disabledTools/modelInfo the native filter consumes also gate the - // dynamic mcp--* declarations, which all represent use_mcp_tool. - const mcpTools = getMcpServerTools(mcpHub, allowedMcpServers) - let filteredMcpTools = filterMcpToolsForMode(mcpTools, mode, customModes, experiments, { - disabledTools, - modelInfo, - }) let advertisedMcpTools = mcpTools - const { threshold, initialK, searchTurns } = resolveMcpDynamicLoadSettings( - options.mcpDynamicLoadThreshold, - options.mcpDynamicLoadInitialK, - options.mcpDynamicLoadSearchTurns, - ) - const totalScoped = filteredMcpTools.length - const gated = options.task !== undefined && searchTurns > 0 && totalScoped > threshold if (options.task && gated) { const scopedNames = new Set(filteredMcpTools.map(getToolName)) const scopedTools = getMcpToolCatalog(mcpHub, allowedMcpServers) diff --git a/src/core/task/mcpToolSelection.ts b/src/core/task/mcpToolSelection.ts index a8d2f953b17..220906bbe83 100644 --- a/src/core/task/mcpToolSelection.ts +++ b/src/core/task/mcpToolSelection.ts @@ -1,4 +1,4 @@ -import { MAX_ATTACHED_DURING_ROLLING, resolveMcpDynamicLoadSettings } from "@roo-code/types" +import { MAX_ATTACHED_DURING_ROLLING } from "@roo-code/types" import { ToolRouter } from "../../services/tools/ToolRouter" import type { ToolDoc } from "../../services/tools/types" import { buildMcpToolName, isMcpTool, normalizeMcpToolName } from "../../utils/mcp-name" @@ -9,12 +9,19 @@ const SUPPLEMENTAL_K = 7 const USER_MESSAGE_TAG = "" type RankFn = (query: string, scope: ToolDoc[], k: number) => Promise +type PersistFn = () => Promise export interface McpSelectionLimits { initialK: number searchTurns: number } +export interface McpToolMatch { + name: string + description: string + added: boolean +} + interface CatalogEntry { name: string serverName: string @@ -25,10 +32,12 @@ interface CatalogEntry { export class McpToolSelection { readonly names: Set initialized: boolean - private pending?: Promise + private pending?: Promise + private scope: ToolDoc[] = [] constructor( - savedNames?: string[], + savedNames: string[] | undefined, + private readonly persist: PersistFn, private readonly rank: RankFn = (query, scope, k) => ToolRouter.getInstance().attachInitial(query, scope, k), public epoch = 0, public lastRankedMessage = -1, @@ -45,17 +54,51 @@ export class McpToolSelection { this.initialized = false } + /** limits must come from resolveMcpDynamicLoadSettings. */ async initialize( scope: ToolDoc[], limits: McpSelectionLimits, taskText: string, history: ApiMessage[], - persist: () => Promise, ): Promise { + await this.serialize(() => { + this.scope = scope + return this.select(scope, limits, taskText.trim(), history) + }) + } + + /** + * Spec: Load, LoadAddsNew. Rank the unattached tools of the newest gated build, so attached tools cannot + * take every slot. With no new match, rank the whole scope to report the attached matches. + * Returns undefined after a reset. + */ + async load(query: string, k: number): Promise { + return this.serialize(async () => { + if (!this.initialized) return undefined + const epoch = this.epoch + const scope = this.scope + const unattached = scope.filter((tool) => !this.names.has(toolName(tool))) + const newMatches = await this.rank(query, unattached, k) + const ranked = newMatches.length > 0 ? newMatches : await this.rank(query, scope, k) + if (this.epoch !== epoch) return undefined + const firstByName = new Map() + for (const tool of scope) if (!firstByName.has(toolName(tool))) firstByName.set(toolName(tool), tool) + const matches = ranked.flatMap((name) => { + const tool = firstByName.get(name) + return tool ? [{ name, description: tool.description, added: !this.names.has(name) }] : [] + }) + for (const match of matches) this.names.add(match.name) + if (matches.some((match) => match.added)) await this.persist() + return this.epoch === epoch ? matches : undefined + }) + } + + private async serialize(work: () => Promise): Promise { while (this.pending) await this.pending - this.pending = this.select(scope, limits, taskText.trim(), history, persist) + const run = work() + this.pending = run try { - await this.pending + return await run } finally { this.pending = undefined } @@ -66,7 +109,6 @@ export class McpToolSelection { limits: McpSelectionLimits, taskText: string, history: ApiMessage[], - persist: () => Promise, ): Promise { const epoch = this.epoch let rankedMessage = this.lastRankedMessage @@ -80,7 +122,7 @@ export class McpToolSelection { !this.initialized || (this.names.size > 0 && !catalog.some((entry) => this.names.has(entry.name))) const { messageIndex, text, turnsSinceSummary } = readUserHistory(history) const query = text || (fullRank ? taskText : "") - const { initialK, searchTurns } = resolveMcpDynamicLoadSettings(undefined, limits.initialK, limits.searchTurns) + const { initialK, searchTurns } = limits const supplement = !fullRank && searchTurns > 1 && @@ -102,7 +144,7 @@ export class McpToolSelection { for (const name of selected) this.names.add(name) this.lastRankedMessage = rankedMessage this.initialized = true - await persist() + await this.persist() } /** Spec: CapTo. The room is 0 when initialK already exceeds the cap. */ diff --git a/src/core/tools/McpLoadTool.ts b/src/core/tools/McpLoadTool.ts new file mode 100644 index 00000000000..f2aeee4ccdf --- /dev/null +++ b/src/core/tools/McpLoadTool.ts @@ -0,0 +1,45 @@ +import { Task } from "../task/Task" +import type { McpToolMatch } from "../task/mcpToolSelection" +import { BaseTool, ToolCallbacks } from "./BaseTool" + +const MAX_DESCRIPTION_LENGTH = 200 + +export class McpLoadTool extends BaseTool<"mcp_load"> { + readonly name = "mcp_load" as const + + async execute(params: { query: string }, task: Task, callbacks: ToolCallbacks): Promise { + const { handleError, pushToolResult } = callbacks + try { + if (!params.query?.trim()) { + task.consecutiveMistakeCount++ + task.recordToolError("mcp_load") + task.didToolFailInCurrentTurn = true + pushToolResult(await task.sayAndCreateMissingParamError("mcp_load", "query")) + return + } + task.consecutiveMistakeCount = 0 + pushToolResult(formatMatches(await task.loadMcpTools(params.query))) + } catch (error) { + await handleError("loading MCP tools", error as Error) + } + } +} + +function formatMatches(matches: McpToolMatch[] | undefined): string { + if (!matches) + return "The MCP tool selection is not built yet, for example after context condensation. If you still need a tool, call mcp_load again in your next request." + if (matches.length === 0) + return "No MCP tools match this query. If no MCP tool fits the task, continue without one." + const lines = matches.map( + ({ name, description, added }) => + `- ${name}${added ? "" : " (already attached)"}: ${oneLine(description) || "(no description)"}`, + ) + return `These MCP tools are attached. New tools are available from your next request.\n${lines.join("\n")}` +} + +function oneLine(text: string): string { + const line = text.trim().split("\n")[0].trim() + return line.length > MAX_DESCRIPTION_LENGTH ? `${line.slice(0, MAX_DESCRIPTION_LENGTH)}...` : line +} + +export const mcpLoadTool = new McpLoadTool() diff --git a/src/core/tools/__tests__/mcpLoadTool.spec.ts b/src/core/tools/__tests__/mcpLoadTool.spec.ts new file mode 100644 index 00000000000..f0c13c2ed84 --- /dev/null +++ b/src/core/tools/__tests__/mcpLoadTool.spec.ts @@ -0,0 +1,81 @@ +import { mcpLoadTool } from "../McpLoadTool" +import type { Task } from "../../task/Task" +import type { McpToolMatch } from "../../task/mcpToolSelection" +import type { ToolUse } from "../../../shared/tools" +import type { ToolCallbacks } from "../BaseTool" + +function setup(matches: McpToolMatch[] | undefined) { + const double = { + consecutiveMistakeCount: 3, + didToolFailInCurrentTurn: false, + recordToolError: vi.fn(), + sayAndCreateMissingParamError: vi.fn().mockResolvedValue("missing query"), + loadMcpTools: vi.fn().mockResolvedValue(matches), + } + // The double provides the members that McpLoadTool reads. Task has many unrelated members. + const task = double as unknown as Task + const callbacks: ToolCallbacks = { + askApproval: vi.fn(), + handleError: vi.fn(), + pushToolResult: vi.fn(), + toolCallId: "call_load", + } + const run = (query: string) => { + const block: ToolUse<"mcp_load"> = { + type: "tool_use", + name: "mcp_load", + params: {}, + partial: false, + nativeArgs: { query }, + } + return mcpLoadTool.handle(task, block, callbacks) + } + return { double, callbacks, run } +} + +describe("mcp_load tool", () => { + it.each(["", " "])("reports a missing query %j", async (query) => { + const { double, callbacks, run } = setup([]) + await run(query) + expect(double.loadMcpTools).not.toHaveBeenCalled() + expect(double.consecutiveMistakeCount).toBe(4) + expect(double.recordToolError).toHaveBeenCalledWith("mcp_load") + expect(double.didToolFailInCurrentTurn).toBe(true) + expect(callbacks.pushToolResult).toHaveBeenCalledWith("missing query") + }) + + it.each([ + { + matches: undefined, + result: "The MCP tool selection is not built yet, for example after context condensation. If you still need a tool, call mcp_load again in your next request.", + }, + { matches: [], result: "No MCP tools match this query. If no MCP tool fits the task, continue without one." }, + { + matches: [ + { name: "mcp--slack--send", description: "Send a message.\nUse a channel ID.", added: true }, + { name: "mcp--slack--read", description: "", added: false }, + { name: "mcp--slack--long", description: "x".repeat(250), added: true }, + ], + result: [ + "These MCP tools are attached. New tools are available from your next request.", + "- mcp--slack--send: Send a message.", + "- mcp--slack--read (already attached): (no description)", + `- mcp--slack--long: ${"x".repeat(200)}...`, + ].join("\n"), + }, + ])("returns the load result for $matches.length matches", async ({ matches, result }) => { + const { double, callbacks, run } = setup(matches) + await run("send slack") + expect(double.loadMcpTools).toHaveBeenCalledWith("send slack") + expect(double.consecutiveMistakeCount).toBe(0) + expect(callbacks.askApproval).not.toHaveBeenCalled() + expect(vi.mocked(callbacks.pushToolResult).mock.calls[0][0]).toContain(result) + }) + + it("reports a load failure", async () => { + const { double, callbacks, run } = setup([]) + double.loadMcpTools.mockRejectedValue(new Error("rank failed")) + await run("send slack") + expect(callbacks.handleError).toHaveBeenCalledWith("loading MCP tools", new Error("rank failed")) + }) +}) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index a2e6885472e..233972076d5 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -3265,6 +3265,7 @@ export class ClineProvider "mcp.dynamicLoad.threshold": mcpDynamicLoadThreshold, "mcp.dynamicLoad.initialK": mcpDynamicLoadInitialK, "mcp.dynamicLoad.searchTurns": mcpDynamicLoadSearchTurns, + "mcp.dynamicLoad.searchK": mcpDynamicLoadSearchK, currentApiConfigName, listApiConfigMeta, pinnedApiConfigs, @@ -3396,6 +3397,7 @@ export class ClineProvider mcpDynamicLoadThreshold, mcpDynamicLoadInitialK, mcpDynamicLoadSearchTurns, + mcpDynamicLoadSearchK, ) return { @@ -3455,6 +3457,7 @@ export class ClineProvider "mcp.dynamicLoad.threshold": mcpDynamicLoad.threshold, "mcp.dynamicLoad.initialK": mcpDynamicLoad.initialK, "mcp.dynamicLoad.searchTurns": mcpDynamicLoad.searchTurns, + "mcp.dynamicLoad.searchK": mcpDynamicLoad.searchK, currentApiConfigName: currentTask ? currentTaskApiConfigName : currentApiConfigName, listApiConfigMeta: listApiConfigMeta ?? [], pinnedApiConfigs: pinnedApiConfigs ?? {}, @@ -3652,6 +3655,7 @@ export class ClineProvider stateValues["mcp.dynamicLoad.threshold"], stateValues["mcp.dynamicLoad.initialK"], stateValues["mcp.dynamicLoad.searchTurns"], + stateValues["mcp.dynamicLoad.searchK"], ) // Return the same structure as before. @@ -3711,6 +3715,7 @@ export class ClineProvider "mcp.dynamicLoad.threshold": mcpDynamicLoad.threshold, "mcp.dynamicLoad.initialK": mcpDynamicLoad.initialK, "mcp.dynamicLoad.searchTurns": mcpDynamicLoad.searchTurns, + "mcp.dynamicLoad.searchK": mcpDynamicLoad.searchK, mcpServers: this.mcpHub?.getAllServers() ?? [], currentApiConfigName: stateValues.currentApiConfigName ?? "default", listApiConfigMeta: stateValues.listApiConfigMeta ?? [], diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index a7ebd61959b..0acb4049a47 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -4591,25 +4591,74 @@ describe("ClineProvider", () => { threshold: undefined, initialK: undefined, turns: undefined, + searchK: undefined, expectedThreshold: 50, expectedK: 30, expectedTurns: 7, + expectedSearchK: 10, + }, + { + threshold: 0, + initialK: 7, + turns: 0, + searchK: 1, + expectedThreshold: 0, + expectedK: 7, + expectedTurns: 0, + expectedSearchK: 1, + }, + { + threshold: 100, + initialK: 20, + turns: 3, + searchK: 25, + expectedThreshold: 100, + expectedK: 20, + expectedTurns: 3, + expectedSearchK: 25, + }, + { + threshold: -1, + initialK: NaN, + turns: -1, + searchK: 0, + expectedThreshold: 50, + expectedK: 30, + expectedTurns: 7, + expectedSearchK: 10, + }, + { + threshold: Infinity, + initialK: 0, + turns: NaN, + searchK: 1.5, + expectedThreshold: 50, + expectedK: 30, + expectedTurns: 7, + expectedSearchK: 10, }, - { threshold: 0, initialK: 7, turns: 0, expectedThreshold: 0, expectedK: 7, expectedTurns: 0 }, - { threshold: 100, initialK: 20, turns: 3, expectedThreshold: 100, expectedK: 20, expectedTurns: 3 }, - { threshold: -1, initialK: NaN, turns: -1, expectedThreshold: 50, expectedK: 30, expectedTurns: 7 }, - { threshold: Infinity, initialK: 0, turns: NaN, expectedThreshold: 50, expectedK: 30, expectedTurns: 7 }, ])( - "round-trips MCP routing settings ($threshold, $initialK, $turns)", - async ({ threshold, initialK, turns, expectedThreshold, expectedK, expectedTurns }) => { + "round-trips MCP routing settings ($threshold, $initialK, $turns, $searchK)", + async ({ + threshold, + initialK, + turns, + searchK, + expectedThreshold, + expectedK, + expectedTurns, + expectedSearchK, + }) => { await provider.resolveWebviewView(mockWebviewView) await provider.contextProxy.setValue("mcp.dynamicLoad.threshold", threshold) await provider.contextProxy.setValue("mcp.dynamicLoad.initialK", initialK) await provider.contextProxy.setValue("mcp.dynamicLoad.searchTurns", turns) + await provider.contextProxy.setValue("mcp.dynamicLoad.searchK", searchK) for (const state of [await provider.getState(), await provider.getStateToPostToWebview()]) { expect(state["mcp.dynamicLoad.threshold"]).toBe(expectedThreshold) expect(state["mcp.dynamicLoad.initialK"]).toBe(expectedK) expect(state["mcp.dynamicLoad.searchTurns"]).toBe(expectedTurns) + expect(state["mcp.dynamicLoad.searchK"]).toBe(expectedSearchK) } }, ) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 8c57dcbfce7..a7056057358 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -1929,32 +1929,34 @@ describe("webviewMessageHandler - mcpEnabled", () => { }) }) -describe.each(["mcp.dynamicLoad.threshold", "mcp.dynamicLoad.initialK", "mcp.dynamicLoad.searchTurns"] as const)( - "webviewMessageHandler - %s", - (key) => { - beforeEach(() => vi.clearAllMocks()) - it.each([undefined, 1, 30, 100])("persists valid value %s", async (value) => { - await webviewMessageHandler(mockClineProvider, { - type: "updateSettings", - updatedSettings: { [key]: value }, - }) - expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith(key, value) - }) - it.each([-1, 1.5, NaN, Infinity])("rejects invalid value %s", async (value) => { - await webviewMessageHandler(mockClineProvider, { - type: "updateSettings", - updatedSettings: { [key]: value }, - }) - expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() +describe.each([ + "mcp.dynamicLoad.threshold", + "mcp.dynamicLoad.initialK", + "mcp.dynamicLoad.searchTurns", + "mcp.dynamicLoad.searchK", +] as const)("webviewMessageHandler - %s", (key) => { + beforeEach(() => vi.clearAllMocks()) + it.each([undefined, 1, 30, 100])("persists valid value %s", async (value) => { + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { [key]: value }, }) - it("accepts zero except for initialK", async () => { - await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { [key]: 0 } }) - if (key !== "mcp.dynamicLoad.initialK") - expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith(key, 0) - else expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith(key, value) + }) + it.each([-1, 1.5, NaN, Infinity])("rejects invalid value %s", async (value) => { + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { [key]: value }, }) - }, -) + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + }) + it("accepts zero only for threshold and searchTurns", async () => { + await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { [key]: 0 } }) + if (key === "mcp.dynamicLoad.threshold" || key === "mcp.dynamicLoad.searchTurns") + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith(key, 0) + else expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + }) +}) describe("webviewMessageHandler - destructiveCommandGuardEnabled", () => { beforeEach(() => { diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index d99a5ada8e8..9cfa0bccdc8 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -891,7 +891,8 @@ export const webviewMessageHandler = async ( } else if ( key === "mcp.dynamicLoad.threshold" || key === "mcp.dynamicLoad.initialK" || - key === "mcp.dynamicLoad.searchTurns" + key === "mcp.dynamicLoad.searchTurns" || + key === "mcp.dynamicLoad.searchK" ) { const parsed = globalSettingsSchema.shape[key].safeParse(value) if (!parsed.success) { diff --git a/src/services/tools/Bm25Ranker.ts b/src/services/tools/Bm25Ranker.ts index b82ad6975a9..11c37b80f55 100644 --- a/src/services/tools/Bm25Ranker.ts +++ b/src/services/tools/Bm25Ranker.ts @@ -1,8 +1,10 @@ +import { buildMcpToolName, normalizeForComparison } from "../../utils/mcp-name" import { Ranker, ToolDoc } from "./types" type IndexedDocument = { item: ToolDoc termFrequencies: Map + names: string[] length: number index: number } @@ -24,14 +26,26 @@ export class Bm25Ranker implements Ranker { this.ensureIndex(items) + const literal = new Set(nameWords(query)) + const normalized = new Set(Array.from(literal, normalizeForComparison)) + const nameMatch = ({ names }: IndexedDocument) => + names.some((name) => literal.has(name)) + ? 2 + : names.some((name) => normalized.has(normalizeForComparison(name))) + ? 1 + : 0 const scores = this.documents .map((document) => ({ document, + match: nameMatch(document), score: this.score(document, new Set(queryTerms)), })) - .filter(({ score }) => score > 0) + .filter(({ match, score }) => match > 0 || score > 0) - scores.sort((left, right) => right.score - left.score || left.document.index - right.document.index) + scores.sort( + (left, right) => + right.match - left.match || right.score - left.score || left.document.index - right.document.index, + ) return scores.slice(0, k).map(({ document }) => document.item) } @@ -53,6 +67,9 @@ export class Bm25Ranker implements Ranker { return { item, termFrequencies, + names: [item.toolName, buildMcpToolName(item.serverName, item.toolName)].map((name) => + name.toLowerCase(), + ), length: Array.from(termFrequencies.values()).reduce((total, count) => total + count, 0), index, } @@ -93,13 +110,27 @@ function tokenize(value: string): string[] { .filter(Boolean) } +// Only identifier words name a tool, so the prose word "search" does not outrank context. +// A literal name match ranks above a match that treats "-" and "_" as equal. +function nameWords(query: string): string[] { + return query + .normalize("NFC") + .toLowerCase() + .split(/[^\p{L}\p{M}\p{N}_-]+/u) + .filter((word) => /[_-]/.test(word)) +} + +// BM25F-style field boost: a name term counts NAME_WEIGHT times, so a tool that only mentions a name ranks lower. +const NAME_WEIGHT = 3 + function countTerms(item: ToolDoc): Map { const frequencies = new Map() - const text = `${item.serverName} ${item.toolName} ${item.description}` - - for (const term of tokenize(text)) { - frequencies.set(term, (frequencies.get(term) ?? 0) + 1) + const add = (text: string, weight: number) => { + for (const term of tokenize(text)) frequencies.set(term, (frequencies.get(term) ?? 0) + weight) } + add(`${item.serverName} ${item.toolName}`, NAME_WEIGHT) + add(item.description, 1) + return frequencies } diff --git a/src/services/tools/__tests__/Bm25Ranker.spec.ts b/src/services/tools/__tests__/Bm25Ranker.spec.ts index 24938e51137..f2f188d722a 100644 --- a/src/services/tools/__tests__/Bm25Ranker.spec.ts +++ b/src/services/tools/__tests__/Bm25Ranker.spec.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest" import { Bm25Ranker } from "../Bm25Ranker" import { ToolDoc } from "../types" +import { jiraTools, searchTickets } from "./fixtures/jiraTools" const tool = (serverName: string, toolName: string, description: string): ToolDoc => ({ serverName, @@ -82,6 +83,70 @@ describe("Bm25Ranker", () => { expect(new Bm25Ranker().rank("github repos", [item], 10)).toEqual([item]) }) + it.each([ + "jira_search_tickets", + "load jira_search_tickets to list tickets", + "mcp--mcplocker--jira_search_tickets", + "mcp__mcplocker__jira_search_tickets", + ])("ranks the tool that the query %j names first", (query) => { + expect(new Bm25Ranker().rank(query, jiraTools, 2)[0]).toBe(searchTickets) + }) + + it("ranks a tool whose name matches the query above tools that only mention it", () => { + const ranked = new Bm25Ranker().rank("search jira tickets", jiraTools, jiraTools.length).map((t) => t.toolName) + const mentioners = jiraTools.filter( + (t) => !t.toolName.includes("search") && t.description.includes("jira_search_tickets"), + ) + + expect(ranked).toContain("jira_search_tickets") + expect(mentioners.length).toBeGreaterThan(2) + for (const { toolName } of mentioners) { + expect(ranked.indexOf("jira_search_tickets")).toBeLessThan(ranked.indexOf(toolName)) + } + }) + + it("does not let a prose word that equals a tool name outrank context", () => { + const slackSearch = tool("slack", "search", "Search messages") + + expect(new Bm25Ranker().rank("search jira tickets", [slackSearch, searchTickets], 1)).toEqual([searchTickets]) + expect(new Bm25Ranker().rank("mcp--slack--search", [searchTickets, slackSearch], 1)).toEqual([slackSearch]) + }) + + it.each(["mcp--slack--search", "mcp__slack__search"])( + "ranks only the tool of the server that the qualified name %j names first", + (query) => { + const slackSearch = tool("slack", "search", "Search messages") + const bridgeSearch = tool("mcp-bridge", "search", "Search slack through mcp") + + expect(new Bm25Ranker().rank(query, [bridgeSearch, slackSearch], 1)).toEqual([slackSearch]) + }, + ) + + it.each(["mcp--my__server--search", "mcp__my__server__search"])( + "ranks the tool of a server whose name contains __ first for %j", + (query) => { + const serverSearch = tool("my__server", "search", "Look up stored records by key in the local archive") + const other = tool("mcp-my-server", "search", "Search my server") + + expect(new Bm25Ranker().rank("mcp my server search", [serverSearch, other], 1)).toEqual([other]) + expect(new Bm25Ranker().rank(query, [other, serverSearch], 1)).toEqual([serverSearch]) + }, + ) + + it.each([ + ["mcp--my__server--search", tool("my", "server__search", ""), tool("my__server", "search", "")], + ["mcp--slack--search", tool("other", "mcp__slack__search", ""), tool("slack", "search", "")], + ])("ranks the literal match of %j above a separator match", (query, separatorMatch, literalMatch) => { + expect(new Bm25Ranker().rank(query, [separatorMatch, literalMatch], 2)).toEqual([literalMatch, separatorMatch]) + }) + + it("does not rank a tool first when the query only shares part of its name", () => { + const items = [tool("jira", "get_ticket", "Get a ticket"), tool("jira", "get_ticket_history", "History")] + + expect(new Bm25Ranker().rank("get_ticket_history", items, 1)).toEqual([items[1]]) + expect(new Bm25Ranker().rank("get_ticket", items, 1)).toEqual([items[0]]) + }) + it("rebuilds only when the items array reference changes", () => { const items = [tool("slack", "send", "Send a message")] const ranker = new Bm25Ranker() diff --git a/src/services/tools/__tests__/fixtures/jiraTools.ts b/src/services/tools/__tests__/fixtures/jiraTools.ts new file mode 100644 index 00000000000..976af4593a3 --- /dev/null +++ b/src/services/tools/__tests__/fixtures/jiraTools.ts @@ -0,0 +1,29 @@ +import type { ToolDoc } from "../../types" + +// Descriptions copied from the mcplocker Jira server. Task 01a22a0e failed four mcp_load calls with this catalog. +const descriptions: Record = { + jira_search_tickets: + "Search for JIRA tickets using simple fields (project_key, status, assignee, summary, issue_type, due_date) or a JQL query. When jql is sent, the simple fields are ignored (named in the note); put those conditions in the jql instead. Simple field 'due_date' supports operators: '<=2025-11-10', '>=now()', ' AND statusCategory = \"In Progress\". active_sprints carry sprint_id, start_date and end_date as in jira_list_sprints, plus the older id, startDate and endDate. Issues from restricted projects are left out and counted in restricted_issues_omitted; when every issue read is restricted, sprint names and counts are left out too and total_issues is absent.", +} + +export const jiraTools: ToolDoc[] = Object.entries(descriptions).map(([toolName, description]) => ({ + serverName: "mcplocker", + toolName, + description, +})) + +export const searchTickets = jiraTools[0] diff --git a/src/shared/tools.ts b/src/shared/tools.ts index 40664ff7328..5a533f5907b 100644 --- a/src/shared/tools.ts +++ b/src/shared/tools.ts @@ -152,6 +152,7 @@ export type NativeToolArgs = { switch_mode: { mode_slug: string; reason: string } update_todo_list: { todos: string } use_mcp_tool: { server_name: string; tool_name: string; arguments?: Record } + mcp_load: { query: string } write_to_file: { path: string; content: string } // Add more tools as they are migrated to native protocol } @@ -223,7 +224,7 @@ export const TOOL_GROUPS: Record = { tools: ["execute_command", "read_command_output"], }, mcp: { - tools: ["use_mcp_tool", "access_mcp_resource"], + tools: ["use_mcp_tool", "access_mcp_resource", "mcp_load"], }, modes: { tools: ["switch_mode", "new_task"],