Skip to content

Commit 6d69c2a

Browse files
committed
fix(mcp): validate native mcp_tool_use dispatch through the shared tool-policy layer
The native mcp_tool_use arm now consults the shared validateToolUse layer (under the canonical use_mcp_tool name) before dispatching to the handler. A disabledTools or excludedTools entry naming use_mcp_tool is rejected at dispatch with a structured is_error tool_result and the server method is never invoked; the enabled path is unchanged. Issue: #1646
1 parent 08d05eb commit 6d69c2a

2 files changed

Lines changed: 277 additions & 0 deletions

File tree

‎src/core/assistant-message/__tests__/presentAssistantMessage-tool-usage-attribution.spec.ts‎

Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,178 @@ describe("presentAssistantMessage - tool usage attribution", () => {
319319
expect(mockTask.recordToolUsage).not.toHaveBeenCalled()
320320
expect(TelemetryService.instance.captureToolUsage).not.toHaveBeenCalled()
321321
})
322+
323+
it("rejects at dispatch when use_mcp_tool is in disabledTools, without invoking the server method", async () => {
324+
const mockHub = {
325+
findServerNameBySanitizedName: () => "my_server",
326+
getAllServers: () => [
327+
{
328+
name: "my_server",
329+
tools: [{ name: "do_thing", enabledForPrompt: true }],
330+
},
331+
],
332+
callTool: vi.fn(),
333+
}
334+
mockTask.providerRef = {
335+
deref: () => ({
336+
getState: vi.fn().mockResolvedValue({
337+
mode: "code",
338+
customModes: [],
339+
disabledTools: ["use_mcp_tool"],
340+
}),
341+
getMcpHub: () => mockHub,
342+
}),
343+
}
344+
vi.mocked(validateToolUse).mockImplementationOnce(() => {
345+
throw new Error('Tool "use_mcp_tool" is not allowed in code mode.')
346+
})
347+
348+
mockTask.assistantMessageContent = [
349+
{
350+
type: "mcp_tool_use",
351+
id: "call_native_mcp_disabled",
352+
name: "mcp_my_server_do_thing",
353+
serverName: "my_server",
354+
toolName: "do_thing",
355+
arguments: {},
356+
partial: false,
357+
},
358+
]
359+
360+
await presentAssistantMessage(mockTask as unknown as Task)
361+
362+
// The decision must come from the shared layer, under the canonical name,
363+
// with the disabledTools entry folded into the requirements map.
364+
const calls = vi.mocked(validateToolUse).mock.calls
365+
expect(calls.length).toBeGreaterThan(0)
366+
expect(calls[calls.length - 1][0]).toBe("use_mcp_tool")
367+
expect(calls[calls.length - 1][3]).toMatchObject({ use_mcp_tool: false })
368+
369+
// Exactly one error tool_result for the block's id; the handler is never
370+
// reached, so the server method is never invoked.
371+
expect(mockTask.userMessageContent).toHaveLength(1)
372+
expect(mockTask.userMessageContent).toContainEqual(
373+
expect.objectContaining({
374+
type: "tool_result",
375+
tool_use_id: "call_native_mcp_disabled",
376+
is_error: true,
377+
content: expect.stringContaining("not allowed in code mode"),
378+
}),
379+
)
380+
expect(mockHub.callTool).not.toHaveBeenCalled()
381+
382+
// No success attribution on rejection; a safe static failure key instead.
383+
expect(mockTask.recordToolUsage).not.toHaveBeenCalled()
384+
expect(TelemetryService.instance.captureToolUsage).not.toHaveBeenCalled()
385+
expect(mockTask.recordToolError).toHaveBeenCalledWith("use_mcp_tool", expect.any(String))
386+
expect(mockTask.consecutiveMistakeCount).toBe(1)
387+
// The stream must not be interrupted by a validation rejection.
388+
expect(mockTask.didAlreadyUseTool).toBe(false)
389+
})
390+
391+
it("rejects at dispatch when use_mcp_tool is in the model's excludedTools", async () => {
392+
const mockHub = {
393+
findServerNameBySanitizedName: () => "my_server",
394+
getAllServers: () => [
395+
{
396+
name: "my_server",
397+
tools: [{ name: "do_thing", enabledForPrompt: true }],
398+
},
399+
],
400+
callTool: vi.fn(),
401+
}
402+
mockTask.providerRef = {
403+
deref: () => ({
404+
getState: vi.fn().mockResolvedValue({
405+
mode: "code",
406+
customModes: [],
407+
}),
408+
getMcpHub: () => mockHub,
409+
}),
410+
}
411+
// excludedTools reaches the requirements map only through
412+
// buildToolRequirements' modelInfo fold, so this pins that input on the
413+
// native path.
414+
mockTask.api = {
415+
getModel: () => ({ id: "test-model", info: { excludedTools: ["use_mcp_tool"] } }),
416+
}
417+
vi.mocked(validateToolUse).mockImplementationOnce(() => {
418+
throw new Error('Tool "use_mcp_tool" is not allowed in code mode.')
419+
})
420+
421+
mockTask.assistantMessageContent = [
422+
{
423+
type: "mcp_tool_use",
424+
id: "call_native_mcp_excluded",
425+
name: "mcp_my_server_do_thing",
426+
serverName: "my_server",
427+
toolName: "do_thing",
428+
arguments: {},
429+
partial: false,
430+
},
431+
]
432+
433+
await presentAssistantMessage(mockTask as unknown as Task)
434+
435+
const calls = vi.mocked(validateToolUse).mock.calls
436+
expect(calls.length).toBeGreaterThan(0)
437+
expect(calls[calls.length - 1][0]).toBe("use_mcp_tool")
438+
expect(calls[calls.length - 1][3]).toMatchObject({ use_mcp_tool: false })
439+
440+
expect(mockTask.userMessageContent).toHaveLength(1)
441+
expect(mockTask.userMessageContent).toContainEqual(
442+
expect.objectContaining({
443+
type: "tool_result",
444+
tool_use_id: "call_native_mcp_excluded",
445+
is_error: true,
446+
content: expect.stringContaining("not allowed in code mode"),
447+
}),
448+
)
449+
expect(mockHub.callTool).not.toHaveBeenCalled()
450+
451+
expect(mockTask.recordToolUsage).not.toHaveBeenCalled()
452+
expect(TelemetryService.instance.captureToolUsage).not.toHaveBeenCalled()
453+
expect(mockTask.recordToolError).toHaveBeenCalledWith("use_mcp_tool", expect.any(String))
454+
expect(mockTask.consecutiveMistakeCount).toBe(1)
455+
expect(mockTask.didAlreadyUseTool).toBe(false)
456+
})
457+
458+
it("skips shared-layer validation for partial blocks so streaming never pushes error results", async () => {
459+
// Validating partial blocks would surface one validation error tool_result
460+
// per streamed chunk for the same tool_use_id.
461+
mockTask.providerRef = {
462+
deref: () => ({
463+
getState: vi.fn().mockResolvedValue({
464+
mode: "code",
465+
customModes: [],
466+
}),
467+
getMcpHub: () => ({
468+
findServerNameBySanitizedName: () => "my_server",
469+
}),
470+
}),
471+
}
472+
vi.mocked(validateToolUse).mockImplementationOnce(() => {
473+
throw new Error('Tool "use_mcp_tool" is not allowed in code mode.')
474+
})
475+
476+
mockTask.assistantMessageContent = [
477+
{
478+
type: "mcp_tool_use",
479+
id: "call_native_mcp_partial",
480+
name: "mcp_my_server_do_thing",
481+
serverName: "my_server",
482+
toolName: "do_thing",
483+
arguments: {},
484+
partial: true,
485+
},
486+
]
487+
488+
await presentAssistantMessage(mockTask as unknown as Task)
489+
490+
expect(validateToolUse).not.toHaveBeenCalled()
491+
expect(mockTask.userMessageContent).toHaveLength(0)
492+
expect(mockTask.consecutiveMistakeCount).toBe(0)
493+
})
322494
})
323495

324496
describe("undefined provider state", () => {
@@ -386,5 +558,49 @@ describe("presentAssistantMessage - tool usage attribution", () => {
386558
expect(calls[0][0]).toBe("read_file")
387559
expect(calls[0][1]).toBe("architect")
388560
})
561+
562+
it("passes the task-local mode to validateToolUse for a native mcp_tool_use block", async () => {
563+
// The native mcp arm has its own validateToolUse call site and must honor
564+
// the same task-local mode contract as the tool_use arm: provider state
565+
// deliberately reports a different mode than the task's.
566+
mockTask.providerRef = {
567+
deref: () => ({
568+
getState: vi.fn().mockResolvedValue({
569+
mode: "orchestrator",
570+
customModes: [],
571+
}),
572+
getMcpHub: () => ({
573+
findServerNameBySanitizedName: () => "my_server",
574+
}),
575+
}),
576+
}
577+
mockTask.getTaskMode = vi.fn().mockResolvedValue("architect")
578+
// Throw so the handler is never reached — the assertion is on the
579+
// arguments the call site passed to the shared layer.
580+
vi.mocked(validateToolUse).mockImplementationOnce(() => {
581+
throw new Error("Task-local mode check.")
582+
})
583+
584+
mockTask.assistantMessageContent = [
585+
{
586+
type: "mcp_tool_use",
587+
id: "call_delegation_mcp",
588+
name: "mcp_my_server_do_thing",
589+
serverName: "my_server",
590+
toolName: "do_thing",
591+
arguments: {},
592+
partial: false,
593+
},
594+
]
595+
596+
await presentAssistantMessage(mockTask as unknown as Task)
597+
598+
const calls = vi.mocked(validateToolUse).mock.calls
599+
expect(calls.length).toBeGreaterThan(0)
600+
expect(calls[calls.length - 1][0]).toBe("use_mcp_tool")
601+
// The discriminating assertion: task-local "architect", not provider
602+
// "orchestrator" — the exact pre-delegation bug shape.
603+
expect(calls[calls.length - 1][1]).toBe("architect")
604+
})
389605
})
390606
})

‎src/core/assistant-message/presentAssistantMessage.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,67 @@ export async function presentAssistantMessage(cline: Task) {
290290
},
291291
}
292292

293+
// Consult the shared policy layer before executing — ONLY for complete
294+
// (non-partial) blocks. Validating partial blocks would surface validation
295+
// errors repeatedly during streaming, pushing multiple tool_results for the
296+
// same tool_use_id and making the stream appear frozen.
297+
if (!mcpBlock.partial) {
298+
const state = await cline.providerRef.deref()?.getState()
299+
const { customModes, experiments: stateExperiments, disabledTools } = state ?? {}
300+
// Read the task-local mode, not the shared provider mode.
301+
// A delegated child task may run in a different mode than its parent.
302+
const taskMode = await cline.getTaskMode()
303+
304+
const modelInfo = cline.api.getModel()
305+
// Resolve aliases in includedTools before validation
306+
// e.g., "write_file" should resolve to "write_to_file"
307+
const rawIncludedTools = modelInfo?.info?.includedTools
308+
const { resolveToolAlias } = await import("../prompts/tools/filter-tools-for-mode")
309+
const includedTools = rawIncludedTools?.map((tool) => resolveToolAlias(tool))
310+
311+
try {
312+
// Validate under the canonical "use_mcp_tool" name: the requirements map
313+
// is keyed by canonical/alias names, so the dynamic mcp_* name would never
314+
// key-match a disabledTools or excludedTools entry naming use_mcp_tool.
315+
// Build requirements through the shared policy module so every suppressed
316+
// entry reaches the validator, which checks them before the
317+
// always-available class. See `buildToolRequirements` in
318+
// effective-tool-policy.ts.
319+
const toolRequirements = buildToolRequirements(disabledTools, modelInfo?.info)
320+
321+
validateToolUse(
322+
"use_mcp_tool",
323+
taskMode,
324+
customModes ?? [],
325+
toolRequirements,
326+
syntheticToolUse.params,
327+
stateExperiments,
328+
includedTools,
329+
)
330+
} catch (error) {
331+
cline.consecutiveMistakeCount++
332+
// For validation errors, send a tool_result with the error (required for
333+
// native tool calling) but do NOT set didAlreadyUseTool = true — the tool
334+
// was never executed, and interrupting the stream here would make the
335+
// extension appear to hang.
336+
const errorContent = formatResponse.toolError(error.message)
337+
if (toolCallId) {
338+
cline.pushToolResultToUserContent({
339+
type: "tool_result",
340+
tool_use_id: sanitizeToolUseId(toolCallId),
341+
content: typeof errorContent === "string" ? errorContent : "(validation error)",
342+
is_error: true,
343+
})
344+
}
345+
346+
// The validator's message names the canonical tool, never the
347+
// model-controlled dynamic name, so this key is safe.
348+
cline.recordToolError("use_mcp_tool", error.message)
349+
350+
break
351+
}
352+
}
353+
293354
await useMcpToolTool.handle(cline, syntheticToolUse, {
294355
askApproval,
295356
handleError,

0 commit comments

Comments
 (0)