Skip to content

Commit 217c8ce

Browse files
committed
test(mcp): cover native mcp validation guard branches; drop redundant optional chains
Three tests pin the guard's deref-undefined fallback, the includedTools alias-map resolution, and the id-omitted rejection branch, taking patch coverage of the changed window from 78.9% to 100% and clearing codecov/patch. The modelInfo and toolError simplifications are behavior-preserving per the typed contracts (non-nullable getModel() return; toolError returns string). Mutation-diff survivor forms are eliminated: all 15 mutants in the regression map are killed. Issue: Zoo-Code-Org#1646
1 parent 6d69c2a commit 217c8ce

2 files changed

Lines changed: 134 additions & 3 deletions

File tree

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

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,137 @@ describe("presentAssistantMessage - tool usage attribution", () => {
491491
expect(mockTask.userMessageContent).toHaveLength(0)
492492
expect(mockTask.consecutiveMistakeCount).toBe(0)
493493
})
494+
495+
it("rejects through the state ?? {} fallback when the provider is unavailable", async () => {
496+
// With no provider state the validator must still receive the task-local
497+
// mode plus empty policy inputs: customModes [] and an empty requirements
498+
// map, rather than the dispatch crashing.
499+
mockTask.providerRef = { deref: () => undefined }
500+
vi.mocked(validateToolUse).mockImplementationOnce(() => {
501+
throw new Error('Tool "use_mcp_tool" is not allowed in code mode.')
502+
})
503+
504+
mockTask.assistantMessageContent = [
505+
{
506+
type: "mcp_tool_use",
507+
id: "call_native_mcp_no_provider",
508+
name: "mcp_my_server_do_thing",
509+
serverName: "my_server",
510+
toolName: "do_thing",
511+
arguments: {},
512+
partial: false,
513+
},
514+
]
515+
516+
await presentAssistantMessage(mockTask as unknown as Task)
517+
518+
// The validator throws so the handler is never reached — the assertions
519+
// pin the arguments the call site passed under the empty-state fallback.
520+
const calls = vi.mocked(validateToolUse).mock.calls
521+
expect(calls.length).toBeGreaterThan(0)
522+
expect(calls[calls.length - 1][0]).toBe("use_mcp_tool")
523+
expect(calls[calls.length - 1][1]).toBe("code")
524+
expect(calls[calls.length - 1][2]).toEqual([])
525+
expect(calls[calls.length - 1][3]).toEqual({})
526+
// The default model info carries no includedTools.
527+
expect(calls[calls.length - 1][6]).toBeUndefined()
528+
529+
expect(mockTask.userMessageContent).toHaveLength(1)
530+
expect(mockTask.userMessageContent).toContainEqual(
531+
expect.objectContaining({
532+
type: "tool_result",
533+
tool_use_id: "call_native_mcp_no_provider",
534+
is_error: true,
535+
content: expect.stringContaining("not allowed in code mode"),
536+
}),
537+
)
538+
539+
expect(mockTask.recordToolUsage).not.toHaveBeenCalled()
540+
expect(TelemetryService.instance.captureToolUsage).not.toHaveBeenCalled()
541+
expect(mockTask.recordToolError).toHaveBeenCalledWith("use_mcp_tool", expect.any(String))
542+
expect(mockTask.consecutiveMistakeCount).toBe(1)
543+
expect(mockTask.didAlreadyUseTool).toBe(false)
544+
})
545+
546+
it("resolves aliases in the model's includedTools before passing them to the shared layer", async () => {
547+
// A model may advertise tools under alias names; the shared layer compares
548+
// canonical names, so "write_file" must arrive as "write_to_file".
549+
mockTask.api = {
550+
getModel: () => ({ id: "test-model", info: { includedTools: ["write_file"] } }),
551+
}
552+
mockTask.providerRef = {
553+
deref: () => ({
554+
getState: vi.fn().mockResolvedValue({
555+
mode: "code",
556+
customModes: [],
557+
}),
558+
getMcpHub: () => ({
559+
findServerNameBySanitizedName: () => "my_server",
560+
}),
561+
}),
562+
}
563+
vi.mocked(validateToolUse).mockImplementationOnce(() => {
564+
throw new Error('Tool "use_mcp_tool" is not allowed in code mode.')
565+
})
566+
567+
mockTask.assistantMessageContent = [
568+
{
569+
type: "mcp_tool_use",
570+
id: "call_native_mcp_alias",
571+
name: "mcp_my_server_do_thing",
572+
serverName: "my_server",
573+
toolName: "do_thing",
574+
arguments: {},
575+
partial: false,
576+
},
577+
]
578+
579+
await presentAssistantMessage(mockTask as unknown as Task)
580+
581+
const calls = vi.mocked(validateToolUse).mock.calls
582+
expect(calls.length).toBeGreaterThan(0)
583+
expect(calls[calls.length - 1][0]).toBe("use_mcp_tool")
584+
expect(calls[calls.length - 1][6]).toEqual(["write_to_file"])
585+
})
586+
587+
it("pushes no tool_result when the native block omits its id, but still records the rejection", async () => {
588+
// McpToolUse.id is optional; with no tool_use_id there is nothing to
589+
// answer, so the error tool_result is skipped while the rejection is
590+
// still recorded.
591+
mockTask.providerRef = {
592+
deref: () => ({
593+
getState: vi.fn().mockResolvedValue({
594+
mode: "code",
595+
customModes: [],
596+
}),
597+
getMcpHub: () => ({
598+
findServerNameBySanitizedName: () => "my_server",
599+
}),
600+
}),
601+
}
602+
vi.mocked(validateToolUse).mockImplementationOnce(() => {
603+
throw new Error('Tool "use_mcp_tool" is not allowed in code mode.')
604+
})
605+
606+
mockTask.assistantMessageContent = [
607+
{
608+
type: "mcp_tool_use",
609+
name: "mcp_my_server_do_thing",
610+
serverName: "my_server",
611+
toolName: "do_thing",
612+
arguments: {},
613+
partial: false,
614+
},
615+
]
616+
617+
await presentAssistantMessage(mockTask as unknown as Task)
618+
619+
expect(mockTask.pushToolResultToUserContent).not.toHaveBeenCalled()
620+
expect(mockTask.userMessageContent).toHaveLength(0)
621+
expect(mockTask.recordToolError).toHaveBeenCalledWith("use_mcp_tool", expect.any(String))
622+
expect(mockTask.consecutiveMistakeCount).toBe(1)
623+
expect(mockTask.didAlreadyUseTool).toBe(false)
624+
})
494625
})
495626

496627
describe("undefined provider state", () => {

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ export async function presentAssistantMessage(cline: Task) {
304304
const modelInfo = cline.api.getModel()
305305
// Resolve aliases in includedTools before validation
306306
// e.g., "write_file" should resolve to "write_to_file"
307-
const rawIncludedTools = modelInfo?.info?.includedTools
307+
const rawIncludedTools = modelInfo.info.includedTools
308308
const { resolveToolAlias } = await import("../prompts/tools/filter-tools-for-mode")
309309
const includedTools = rawIncludedTools?.map((tool) => resolveToolAlias(tool))
310310

@@ -316,7 +316,7 @@ export async function presentAssistantMessage(cline: Task) {
316316
// entry reaches the validator, which checks them before the
317317
// always-available class. See `buildToolRequirements` in
318318
// effective-tool-policy.ts.
319-
const toolRequirements = buildToolRequirements(disabledTools, modelInfo?.info)
319+
const toolRequirements = buildToolRequirements(disabledTools, modelInfo.info)
320320

321321
validateToolUse(
322322
"use_mcp_tool",
@@ -338,7 +338,7 @@ export async function presentAssistantMessage(cline: Task) {
338338
cline.pushToolResultToUserContent({
339339
type: "tool_result",
340340
tool_use_id: sanitizeToolUseId(toolCallId),
341-
content: typeof errorContent === "string" ? errorContent : "(validation error)",
341+
content: errorContent,
342342
is_error: true,
343343
})
344344
}

0 commit comments

Comments
 (0)