Skip to content

Commit ade25d7

Browse files
committed
feat(mcp): gate task tools with persisted ranked selections
1 parent 802554a commit ade25d7

22 files changed

Lines changed: 867 additions & 75 deletions
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# MCP dynamic tool loading
2+
3+
Issue #578 adds a task-scoped gate to API tool declarations. When the tools
4+
allowed by the current mode and tool policy exceed `mcp.dynamicLoad.threshold`
5+
(default 50), the task initially attaches up to `mcp.dynamicLoad.initialK`
6+
(default 30) ranked tools. Images-only tasks use the first distinct scoped
7+
tools because there is no initial text to rank.
8+
9+
The selection is stored in task history. Missing or invalid selections are
10+
initialized on demand; a valid empty selection remains initialized. MCP names
11+
already used in conversation history are retained for provider compatibility,
12+
so resumed tasks can require more than `initialK` declarations. This is an
13+
initial selection limit, not a lifetime cap. Historical names accumulate during
14+
a task and are not trimmed, since removing their definitions can cause providers
15+
to reject conversation history. Current server, mode, and tool-policy
16+
restrictions still apply.
17+
18+
If saving fails, the task retains its in-memory selection and continues. Later
19+
normal history saves retry persistence. Storage errors do not trigger API
20+
stream retries.
21+
22+
The gate limits advertised definitions; it does not add an execution permission
23+
boundary. Existing tool authorization still applies to calls by name.
24+
25+
The settings schema and extension-state round trip are implemented. SettingsView
26+
controls and replacement of the legacy catalog-wide warning are deferred to
27+
#581. The legacy warning uses its own catalog advisory threshold; it does not
28+
report the scoped tool count for a running task. The `mcp_load` escape hatch is
29+
deferred to #579.

‎packages/types/src/__tests__/global-settings.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
GLOBAL_SETTINGS_KEYS,
55
globalSettingsSchema,
66
} from "../global-settings.js"
7+
import { resolveMcpDynamicLoadSettings } from "../mcp.js"
78

89
describe("destructive command guard global setting", () => {
910
it("is opt-in by default", () => {
@@ -51,3 +52,26 @@ describe("collapseCommandOutputByDefault global setting", () => {
5152
expect(globalSettingsSchema.safeParse({ collapseCommandOutputByDefault: "true" }).success).toBe(false)
5253
})
5354
})
55+
56+
describe.each(["mcp.dynamicLoad.threshold", "mcp.dynamicLoad.initialK"] as const)("%s", (key) => {
57+
it.each([undefined, 1, 30, 50, 100])("round-trips %s through the settings schema", (value) => {
58+
const settings = globalSettingsSchema.parse({ [key]: value })
59+
expect(globalSettingsSchema.parse(JSON.parse(JSON.stringify(settings)))[key]).toBe(value)
60+
expect(GLOBAL_SETTINGS_KEYS).toContain(key)
61+
})
62+
it.each([-1, 1.5, NaN, Infinity, "30", null])("rejects %s", (value) => {
63+
expect(globalSettingsSchema.safeParse({ [key]: value }).success).toBe(false)
64+
})
65+
it("allows zero only for the threshold", () => {
66+
expect(globalSettingsSchema.safeParse({ [key]: 0 }).success).toBe(key === "mcp.dynamicLoad.threshold")
67+
})
68+
})
69+
70+
describe("runtime MCP routing defaults", () => {
71+
it.each([undefined, null, -1, 1.5, NaN, Infinity, "30", {}])("replaces invalid input %j", (value) => {
72+
expect(resolveMcpDynamicLoadSettings(value, value)).toEqual({ threshold: 50, initialK: 30 })
73+
})
74+
it("preserves a zero threshold and a positive limit", () => {
75+
expect(resolveMcpDynamicLoadSettings(0, 1)).toEqual({ threshold: 0, initialK: 1 })
76+
})
77+
})

‎packages/types/src/__tests__/history.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,19 @@ describe("historyItemSchema", () => {
6363
it("leaves title unset when absent", () => {
6464
expect(historyItemSchema.parse(baseItem)).not.toHaveProperty("title")
6565
})
66+
67+
it.each([
68+
{ value: undefined, expected: undefined },
69+
{ value: null, expected: undefined },
70+
{ value: "abc", expected: undefined },
71+
{ value: 42, expected: undefined },
72+
{ value: {}, expected: undefined },
73+
{ value: [42], expected: undefined },
74+
{ value: [], expected: [] },
75+
{ value: ["mcp--a--b", null, 42], expected: ["mcp--a--b"] },
76+
])("normalizes persisted attachments $value without losing the task", ({ value, expected }) => {
77+
const parsed = historyItemSchema.parse({ ...baseItem, attachedMcpToolNames: value })
78+
expect(parsed.id).toBe(baseItem.id)
79+
expect(parsed.attachedMcpToolNames).toEqual(expected)
80+
})
6681
})

‎packages/types/src/global-settings.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { toolNamesSchema } from "./tool.js"
1515
import { type Keys } from "./type-fu.js"
1616
import { languagesSchema } from "./vscode.js"
1717
import { providerIdentifiers } from "./provider-identifiers.js"
18+
import { mcpDynamicLoadThresholdSchema, mcpDynamicLoadInitialKSchema } from "./mcp.js"
1819

1920
/**
2021
* Default delay in milliseconds after writes to allow diagnostics to detect potential problems.
@@ -265,6 +266,8 @@ export const globalSettingsSchema = z.object({
265266
telemetrySetting: telemetrySettingsSchema.optional(),
266267

267268
mcpEnabled: z.boolean().optional(),
269+
"mcp.dynamicLoad.threshold": mcpDynamicLoadThresholdSchema.optional(),
270+
"mcp.dynamicLoad.initialK": mcpDynamicLoadInitialKSchema.optional(),
268271

269272
mode: z.string().optional(),
270273
modeApiConfigs: z.record(z.string(), z.string()).optional(),

‎packages/types/src/history.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,14 @@ export const pendingTaskActionSchema = z.discriminatedUnion("kind", [
2626

2727
export type PendingTaskAction = z.infer<typeof pendingTaskActionSchema>
2828

29+
// Older or hand-edited history can contain an invalid attachment field. Do not
30+
// discard the task record or mark a non-array value as an initialized selection.
31+
export const attachedMcpToolNamesSchema = z.preprocess((value) => {
32+
if (!Array.isArray(value)) return undefined
33+
const names = value.filter((name): name is string => typeof name === "string")
34+
return value.length > 0 && names.length === 0 ? undefined : names
35+
}, z.array(z.string()).optional())
36+
2937
export const historyItemSchema = z.object({
3038
id: z.string(),
3139
rootTaskId: z.string().optional(),
@@ -50,6 +58,8 @@ export const historyItemSchema = z.object({
5058
completedByChildId: z.string().optional(), // Child that completed and resumed this parent
5159
completionResultSummary: z.string().optional(), // Summary from completed child
5260
pendingAction: pendingTaskActionSchema.optional(),
61+
// Absent means routing has not run; an empty array is an initialized selection.
62+
attachedMcpToolNames: attachedMcpToolNamesSchema,
5363
})
5464

5565
export type HistoryItem = z.infer<typeof historyItemSchema>

‎packages/types/src/mcp.ts‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,22 @@
11
import { z } from "zod"
22

3-
/**
4-
* Maximum number of MCP tools that can be enabled before showing a warning.
5-
* LLMs tend to perform poorly when given too many tools to choose from.
6-
*/
3+
export const DEFAULT_MCP_DYNAMIC_LOAD_THRESHOLD = 50
4+
export const DEFAULT_MCP_DYNAMIC_LOAD_INITIAL_K = 30
5+
6+
/** @deprecated Legacy catalog advisory. Runtime routing uses the dynamic-load settings. */
77
export const MAX_MCP_TOOLS_THRESHOLD = 60
88

9+
export const mcpDynamicLoadThresholdSchema = z.number().int().min(0)
10+
export const mcpDynamicLoadInitialKSchema = z.number().int().min(1)
11+
12+
/** Apply the same validation to persisted values and direct runtime callers. */
13+
export function resolveMcpDynamicLoadSettings(threshold: unknown, initialK: unknown) {
14+
return {
15+
threshold: mcpDynamicLoadThresholdSchema.safeParse(threshold).data ?? DEFAULT_MCP_DYNAMIC_LOAD_THRESHOLD,
16+
initialK: mcpDynamicLoadInitialKSchema.safeParse(initialK).data ?? DEFAULT_MCP_DYNAMIC_LOAD_INITIAL_K,
17+
}
18+
}
19+
920
/**
1021
* McpServerUse
1122
*/
@@ -155,7 +166,7 @@ export interface EnabledMcpToolsCount {
155166
* @example
156167
* const { enabledToolCount, enabledServerCount } = countEnabledMcpTools(mcpServers)
157168
* if (enabledToolCount > MAX_MCP_TOOLS_THRESHOLD) {
158-
* // Show warning
169+
* // Show the legacy catalog advisory, separate from task-scoped routing.
159170
* }
160171
*/
161172
export function countEnabledMcpTools(servers: McpServer[]): EnabledMcpToolsCount {

‎packages/types/src/message.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ export function isNonBlockingAsk(ask: ClineAsk): ask is NonBlockingAsk {
139139
* - `condense_context`: Context condensation/summarization has started
140140
* - `condense_context_error`: Error occurred during context condensation
141141
* - `codebase_search_result`: Results from searching the codebase
142-
* - `too_many_tools_warning`: Warning that too many MCP tools are enabled, which may confuse the LLM
142+
* - `too_many_tools_warning`: Legacy warning retained for history rendering; no longer emitted by Task.
143143
* - `ignored_disabled_tools_warning`: Warning that a `disabledTools` entry names a protocol tool, which user settings cannot disable
144144
*/
145145
export const clineSays = [

‎packages/types/src/vscode-extension-host.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,8 @@ export type ExtensionState = Pick<
377377
experiments: Experiments // Map of experiment IDs to their enabled state
378378

379379
mcpEnabled: boolean
380+
"mcp.dynamicLoad.threshold"?: number
381+
"mcp.dynamicLoad.initialK"?: number
380382

381383
mode: string
382384
customModes: ModeConfig[]
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import * as fs from "fs/promises"
2+
import * as os from "os"
3+
import * as path from "path"
4+
import { TaskHistoryStore } from "../TaskHistoryStore"
5+
import { taskMetadata } from "../taskMetadata"
6+
7+
describe("MCP attachment history round trip", () => {
8+
it.each([{ names: undefined }, { names: [] }, { names: ["mcp--github--issues"] }])(
9+
"preserves $names across a store restart",
10+
async ({ names }) => {
11+
const directory = await fs.mkdtemp(path.join(os.tmpdir(), "mcp-attachments-"))
12+
const store = new TaskHistoryStore(directory)
13+
const restored = new TaskHistoryStore(directory)
14+
try {
15+
const { historyItem } = await taskMetadata({
16+
taskId: "attachment-task",
17+
taskNumber: 1,
18+
messages: [],
19+
workspace: directory,
20+
globalStoragePath: directory,
21+
attachedMcpToolNames: names,
22+
})
23+
await store.initialize()
24+
await store.upsert(historyItem)
25+
store.dispose()
26+
await restored.initialize()
27+
expect(restored.get(historyItem.id)?.attachedMcpToolNames).toEqual(names)
28+
} finally {
29+
store.dispose()
30+
restored.dispose()
31+
await fs.rm(directory, { recursive: true, force: true })
32+
}
33+
},
34+
)
35+
})

‎src/core/task-persistence/taskMetadata.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ export type TaskMetadataOptions = {
2323
mode?: string
2424
/** Provider profile name for the task (sticky profile feature) */
2525
apiConfigName?: string
26+
attachedMcpToolNames?: string[]
2627
/** Initial status for the task (e.g., "active" for child tasks) */
2728
initialStatus?: "active" | "delegated" | "completed" | "interrupted"
2829
}
@@ -38,6 +39,7 @@ export async function taskMetadata({
3839
mode,
3940
apiConfigName,
4041
initialStatus,
42+
attachedMcpToolNames,
4143
}: TaskMetadataOptions) {
4244
const taskDir = await getTaskDirectoryPath(globalStoragePath, id)
4345

@@ -112,6 +114,7 @@ export async function taskMetadata({
112114
mode,
113115
...(typeof apiConfigName === "string" && apiConfigName.length > 0 ? { apiConfigName } : {}),
114116
...(initialStatus && { status: initialStatus }),
117+
...(attachedMcpToolNames !== undefined && { attachedMcpToolNames }),
115118
}
116119

117120
return { historyItem, tokenUsage }

0 commit comments

Comments
 (0)