Repository navigation
Expand file tree
/
Copy pathpresentAssistantMessage-tool-usage-attribution.spec.ts
More file actions
967 lines (869 loc) · 31.4 KB
/
Copy pathpresentAssistantMessage-tool-usage-attribution.spec.ts
File metadata and controls
967 lines (869 loc) · 31.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
// npx vitest src/core/assistant-message/__tests__/presentAssistantMessage-tool-usage-attribution.spec.ts
import { DispatchState, type PendingWork } from "../../task/dispatchState"
import type { Anthropic } from "@anthropic-ai/sdk"
import { TelemetryEventName } from "@roo-code/types"
import { describe, it, expect, beforeEach, vi, type Mock } from "vitest"
import { presentAssistantMessage } from "../presentAssistantMessage"
import { validateToolUse } from "../../tools/validateToolUse"
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"
vi.mock("../../task/Task")
vi.mock("../../../shared/modes", async (importOriginal) => {
const actual = await importOriginal<typeof import("../../../shared/modes")>()
return {
...actual,
getModeBySlug: vi.fn(actual.getModeBySlug),
}
})
// isValidToolName is left as the real implementation (only validateToolUse is
// mocked): it has its own independent mcp_ prefix carve-out, and a hand-rolled
// mock allowlist here would mask a regression in toTelemetryToolName's
// ordering relative to isValidToolName.
vi.mock("../../tools/validateToolUse", async (importOriginal) => {
const actual = await importOriginal<typeof import("../../tools/validateToolUse")>()
return {
...actual,
validateToolUse: vi.fn(),
}
})
vi.mock("@roo-code/core", () => ({
customToolRegistry: {
has: vi.fn(() => false),
get: vi.fn(),
},
}))
vi.mock("@roo-code/telemetry", () => ({
TelemetryService: {
instance: {
captureConsecutiveMistakeError: vi.fn(),
captureEvent: vi.fn(),
},
},
}))
import { TelemetryService } from "@roo-code/telemetry"
// The snapshot the presenter consumes; the getState doubles below deliberately
// disagree with it so any surviving live-read re-entry is caught by assertions.
const baseSnapshot: RequestPolicySnapshot = {
disabledTools: [],
customModes: [],
}
interface MockTask {
taskId: string
instanceId: string
abort: boolean
dispatchState: DispatchState
pendingWork: PendingWork | null
currentStreamingContentIndex: number
assistantMessageContent: unknown[]
userMessageContent: Anthropic.ToolResultBlockParam[]
didCompleteReadingStream: boolean
didRejectTool: boolean
didAlreadyUseTool: boolean
activeToolContexts: Map<string, unknown>
consecutiveMistakeCount: number
clineMessages: unknown[]
getTaskMode: Mock<() => Promise<string>>
api: { getModel: () => { id: string; info: Record<string, unknown> } }
recordToolUsage: ReturnType<typeof vi.fn>
recordToolError: ReturnType<typeof vi.fn>
toolRepetitionDetector: { check: ReturnType<typeof vi.fn> }
providerRef: {
deref: () =>
| {
getState: ReturnType<typeof vi.fn>
getMcpHub?: () => { findServerNameBySanitizedName: (name: string) => string | undefined }
}
| undefined
}
say: ReturnType<typeof vi.fn>
ask: ReturnType<typeof vi.fn>
pushToolResultToUserContent: ReturnType<typeof vi.fn>
}
describe("presentAssistantMessage - tool usage attribution", () => {
let mockTask: MockTask
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(validateToolUse).mockImplementation(() => undefined)
mockTask = {
taskId: "test-task-id",
instanceId: "test-instance",
abort: false,
dispatchState: DispatchState.IDLE,
pendingWork: null,
currentStreamingContentIndex: 0,
assistantMessageContent: [],
userMessageContent: [],
didCompleteReadingStream: false,
didRejectTool: false,
didAlreadyUseTool: false,
activeToolContexts: new Map(),
consecutiveMistakeCount: 0,
clineMessages: [],
getTaskMode: vi.fn().mockResolvedValue("code"),
api: {
getModel: () => ({ id: "test-model", info: {} }),
},
recordToolUsage: vi.fn(),
recordToolError: vi.fn(),
toolRepetitionDetector: {
check: vi.fn().mockReturnValue({ allowExecution: true }),
},
providerRef: {
deref: () => ({
getState: vi.fn().mockResolvedValue({
mode: "code",
// Poisoned: disagrees with baseSnapshot, so a live
// read here changes validation args and fails tests.
customModes: [{ slug: "poison", name: "Poison", roleDefinition: "", groups: [] }],
disabledTools: ["write_to_file"],
}),
}),
},
say: vi.fn().mockResolvedValue(undefined),
ask: vi.fn().mockResolvedValue({ response: "yesButtonClicked" }),
pushToolResultToUserContent: vi.fn(),
}
mockTask.pushToolResultToUserContent = vi
.fn()
.mockImplementation((toolResult: Anthropic.ToolResultBlockParam) => {
const existingResult = mockTask.userMessageContent.find(
(block) => block.type === "tool_result" && block.tool_use_id === toolResult.tool_use_id,
)
if (existingResult) {
return false
}
mockTask.userMessageContent.push(toolResult)
return true
})
})
it("records exactly one attempt for a normal static tool", async () => {
mockTask.assistantMessageContent = [
{
type: "tool_use",
id: "call_1",
name: "read_file",
params: { path: "test.txt" },
nativeArgs: { path: "test.txt" },
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
expect(mockTask.recordToolUsage).toHaveBeenCalledTimes(1)
expect(mockTask.recordToolUsage).toHaveBeenCalledWith("read_file")
})
it("records a valid dynamic mcp_ tool name as use_mcp_tool", async () => {
mockTask.assistantMessageContent = [
{
type: "tool_use",
id: "call_mcp",
name: "mcp_my_server_do_thing",
params: {},
nativeArgs: {},
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
expect(mockTask.recordToolUsage).toHaveBeenCalledWith("use_mcp_tool")
})
it("records a malformed mcp_ tool name as use_mcp_tool, not the raw name", async () => {
mockTask.assistantMessageContent = [
{
type: "tool_use",
id: "call_mcp_bad",
name: "mcp_",
params: {},
nativeArgs: {},
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
expect(mockTask.recordToolUsage).toHaveBeenCalledWith("use_mcp_tool")
expect(mockTask.recordToolUsage).not.toHaveBeenCalledWith("mcp_")
})
it("validates tools against the task-local mode when provider state differs", async () => {
mockTask.getTaskMode.mockResolvedValue("code")
mockTask.providerRef.deref = () => ({
getState: vi.fn().mockResolvedValue({
mode: "orchestrator",
// Poisoned: a live read would put non-empty customModes and a
// read_file restriction into the validator call.
customModes: [{ slug: "delegated", name: "Delegated", roleDefinition: "", groups: [] }],
disabledTools: ["read_file"],
}),
})
mockTask.assistantMessageContent = [
{
type: "tool_use",
id: "call_task_mode",
name: "read_file",
params: { path: "test.txt" },
nativeArgs: { path: "test.txt" },
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
expect(validateToolUse).toHaveBeenCalledWith(
"read_file",
"code",
[],
{},
{ path: "test.txt" },
undefined,
undefined,
)
})
it("records a safe failure key without leaking the raw tool name when validation fails", async () => {
vi.mocked(validateToolUse).mockImplementation(() => {
throw new Error('Tool "read_file" is not allowed in this mode.')
})
mockTask.assistantMessageContent = [
{
type: "tool_use",
id: "call_bad_mode",
name: "read_file",
params: { path: "test.txt" },
nativeArgs: { path: "test.txt" },
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
// A known static tool that fails validation still maps to its own name
// (it's a real, recognized tool - just disallowed here), never left raw/unmapped.
expect(mockTask.recordToolError).toHaveBeenCalledWith("read_file", expect.any(String))
// No success attempt should be recorded for a validation failure.
expect(mockTask.recordToolUsage).not.toHaveBeenCalled()
})
it("records invalid_tool_call, not the raw name, when an arbitrary unknown tool fails validation", async () => {
vi.mocked(validateToolUse).mockImplementation(() => {
throw new Error('Unknown tool "totally_made_up_tool". This tool does not exist.')
})
mockTask.assistantMessageContent = [
{
type: "tool_use",
id: "call_unknown",
name: "totally_made_up_tool",
params: {},
nativeArgs: {},
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
expect(mockTask.recordToolError).toHaveBeenCalledWith("invalid_tool_call", expect.any(String))
expect(mockTask.recordToolError).not.toHaveBeenCalledWith("totally_made_up_tool", expect.anything())
expect(mockTask.recordToolUsage).not.toHaveBeenCalled()
})
it("captures the legacy read_file telemetry event with the live model id", async () => {
// The model label on this event is a non-policy label read live from the
// api, never sourced from the request snapshot's modelInfo. The doubles
// deliberately disagree (live id vs a snapshot modelInfo carrying no id)
// so a source switch on the payload changes the captured value.
const liveModelId = "live-model-id"
mockTask.api = { getModel: vi.fn().mockReturnValue({ id: liveModelId, info: {} }) }
mockTask.assistantMessageContent = [
{
type: "tool_use",
id: "call_legacy_read",
name: "read_file",
params: { path: "test.txt" },
nativeArgs: { path: "test.txt" },
usedLegacyFormat: true,
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, {
...baseSnapshot,
modelInfo: { contextWindow: 200_000, supportsPromptCache: true },
})
expect(TelemetryService.instance.captureEvent).toHaveBeenCalledWith(
TelemetryEventName.READ_FILE_LEGACY_FORMAT_USED,
{ taskId: mockTask.taskId, model: liveModelId },
)
})
describe("native mcp_tool_use block", () => {
it("records exactly one attempt once the MCP tool's own validation passes", async () => {
mockTask.providerRef = {
deref: () => ({
getState: vi.fn().mockResolvedValue({
mode: "code",
customModes: [],
disabledTools: ["use_mcp_tool"],
}),
getMcpHub: () => ({
findServerNameBySanitizedName: () => "my_server",
getAllServers: () => [
{
name: "my_server",
tools: [{ name: "do_thing", enabledForPrompt: true }],
},
],
}),
}),
}
mockTask.assistantMessageContent = [
{
type: "mcp_tool_use",
id: "call_native_mcp",
name: "mcp_my_server_do_thing",
serverName: "my_server",
toolName: "do_thing",
arguments: {},
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
expect(mockTask.recordToolUsage).toHaveBeenCalledTimes(1)
expect(mockTask.recordToolUsage).toHaveBeenCalledWith("use_mcp_tool")
})
it("records no attempt when the MCP server is not on the mode's allow-list", async () => {
vi.mocked(getModeBySlug).mockReturnValueOnce({
slug: "code",
name: "Code",
roleDefinition: "",
groups: [],
allowedMcpServers: ["some-other-server"],
})
mockTask.providerRef = {
deref: () => ({
getState: vi.fn().mockResolvedValue({
mode: "code",
customModes: [],
disabledTools: ["use_mcp_tool"],
}),
getMcpHub: () => ({
findServerNameBySanitizedName: () => "my_server",
}),
}),
}
mockTask.assistantMessageContent = [
{
type: "mcp_tool_use",
id: "call_native_mcp_disallowed",
name: "mcp_my_server_do_thing",
serverName: "my_server",
toolName: "do_thing",
arguments: {},
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
// The server is disallowed, so the call never reaches onValidated:
// no success attempt is recorded for a call that was never permitted to execute.
expect(mockTask.recordToolUsage).not.toHaveBeenCalled()
})
it("rejects at dispatch when use_mcp_tool is in disabledTools, without invoking the server method", async () => {
const mockHub = {
findServerNameBySanitizedName: () => "my_server",
getAllServers: () => [
{
name: "my_server",
tools: [{ name: "do_thing", enabledForPrompt: true }],
},
],
callTool: vi.fn(),
}
mockTask.providerRef = {
deref: () => ({
getState: vi.fn().mockResolvedValue({ mode: "code" }),
getMcpHub: () => mockHub,
}),
}
vi.mocked(validateToolUse).mockImplementationOnce(() => {
throw new Error('Tool "use_mcp_tool" is not allowed in code mode.')
})
mockTask.assistantMessageContent = [
{
type: "mcp_tool_use",
id: "call_native_mcp_disabled",
name: "mcp_my_server_do_thing",
serverName: "my_server",
toolName: "do_thing",
arguments: {},
partial: false,
},
]
// The policy input reaches the requirements map through the request's
// snapshot, not through provider state.
await presentAssistantMessage(mockTask as unknown as Task, {
...baseSnapshot,
disabledTools: ["use_mcp_tool"],
})
// The decision must come from the shared layer, under the canonical name,
// with the disabledTools entry folded into the requirements map.
const calls = vi.mocked(validateToolUse).mock.calls
expect(calls.length).toBeGreaterThan(0)
expect(calls[calls.length - 1][0]).toBe("use_mcp_tool")
expect(calls[calls.length - 1][3]).toMatchObject({ use_mcp_tool: false })
// Exactly one error tool_result for the block's id; the handler is never
// reached, so the server method is never invoked.
expect(mockTask.userMessageContent).toHaveLength(1)
expect(mockTask.userMessageContent).toContainEqual(
expect.objectContaining({
type: "tool_result",
tool_use_id: "call_native_mcp_disabled",
is_error: true,
content: expect.stringContaining("not allowed in code mode"),
}),
)
expect(mockHub.callTool).not.toHaveBeenCalled()
// No success attribution on rejection; a safe static failure key instead.
expect(mockTask.recordToolUsage).not.toHaveBeenCalled()
expect(mockTask.recordToolError).toHaveBeenCalledWith("use_mcp_tool", expect.any(String))
expect(mockTask.consecutiveMistakeCount).toBe(1)
// The stream must not be interrupted by a validation rejection.
expect(mockTask.didAlreadyUseTool).toBe(false)
})
it("rejects at dispatch when use_mcp_tool is in the model's excludedTools", async () => {
const mockHub = {
findServerNameBySanitizedName: () => "my_server",
getAllServers: () => [
{
name: "my_server",
tools: [{ name: "do_thing", enabledForPrompt: true }],
},
],
callTool: vi.fn(),
}
mockTask.providerRef = {
deref: () => ({
getState: vi.fn().mockResolvedValue({ mode: "code" }),
getMcpHub: () => mockHub,
}),
}
vi.mocked(validateToolUse).mockImplementationOnce(() => {
throw new Error('Tool "use_mcp_tool" is not allowed in code mode.')
})
mockTask.assistantMessageContent = [
{
type: "mcp_tool_use",
id: "call_native_mcp_excluded",
name: "mcp_my_server_do_thing",
serverName: "my_server",
toolName: "do_thing",
arguments: {},
partial: false,
},
]
// excludedTools reaches the requirements map only through
// buildToolRequirements' modelInfo fold, so this pins that input on the
// native path: the model metadata travels in the request's snapshot,
// never through a live getModel() read.
await presentAssistantMessage(mockTask as unknown as Task, {
...baseSnapshot,
modelInfo: { contextWindow: 200_000, supportsPromptCache: true, excludedTools: ["use_mcp_tool"] },
})
const calls = vi.mocked(validateToolUse).mock.calls
expect(calls.length).toBeGreaterThan(0)
expect(calls[calls.length - 1][0]).toBe("use_mcp_tool")
expect(calls[calls.length - 1][3]).toMatchObject({ use_mcp_tool: false })
expect(mockTask.userMessageContent).toHaveLength(1)
expect(mockTask.userMessageContent).toContainEqual(
expect.objectContaining({
type: "tool_result",
tool_use_id: "call_native_mcp_excluded",
is_error: true,
content: expect.stringContaining("not allowed in code mode"),
}),
)
expect(mockHub.callTool).not.toHaveBeenCalled()
expect(mockTask.recordToolUsage).not.toHaveBeenCalled()
expect(mockTask.recordToolError).toHaveBeenCalledWith("use_mcp_tool", expect.any(String))
expect(mockTask.consecutiveMistakeCount).toBe(1)
expect(mockTask.didAlreadyUseTool).toBe(false)
})
it("skips shared-layer validation for partial blocks so streaming never pushes error results", async () => {
// Validating partial blocks would surface one validation error tool_result
// per streamed chunk for the same tool_use_id.
mockTask.providerRef = {
deref: () => ({
getState: vi.fn().mockResolvedValue({
mode: "code",
customModes: [],
}),
getMcpHub: () => ({
findServerNameBySanitizedName: () => "my_server",
}),
}),
}
vi.mocked(validateToolUse).mockImplementationOnce(() => {
throw new Error('Tool "use_mcp_tool" is not allowed in code mode.')
})
mockTask.assistantMessageContent = [
{
type: "mcp_tool_use",
id: "call_native_mcp_partial",
name: "mcp_my_server_do_thing",
serverName: "my_server",
toolName: "do_thing",
arguments: {},
partial: true,
},
]
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
expect(validateToolUse).not.toHaveBeenCalled()
expect(mockTask.userMessageContent).toHaveLength(0)
expect(mockTask.consecutiveMistakeCount).toBe(0)
})
it("rejects with the snapshot's policy inputs when the provider is unavailable", async () => {
// With no provider state the validator must still receive the task-local
// mode plus the snapshot's policy inputs: customModes [] and an empty
// requirements map, rather than the dispatch crashing.
mockTask.providerRef = { deref: () => undefined }
vi.mocked(validateToolUse).mockImplementationOnce(() => {
throw new Error('Tool "use_mcp_tool" is not allowed in code mode.')
})
mockTask.assistantMessageContent = [
{
type: "mcp_tool_use",
id: "call_native_mcp_no_provider",
name: "mcp_my_server_do_thing",
serverName: "my_server",
toolName: "do_thing",
arguments: {},
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
// The validator throws so the handler is never reached — the assertions
// pin the arguments the call site passed from the snapshot alone.
const calls = vi.mocked(validateToolUse).mock.calls
expect(calls.length).toBeGreaterThan(0)
expect(calls[calls.length - 1][0]).toBe("use_mcp_tool")
expect(calls[calls.length - 1][1]).toBe("code")
expect(calls[calls.length - 1][2]).toEqual([])
expect(calls[calls.length - 1][3]).toEqual({})
// The default model info carries no includedTools.
expect(calls[calls.length - 1][6]).toBeUndefined()
expect(mockTask.userMessageContent).toHaveLength(1)
expect(mockTask.userMessageContent).toContainEqual(
expect.objectContaining({
type: "tool_result",
tool_use_id: "call_native_mcp_no_provider",
is_error: true,
content: expect.stringContaining("not allowed in code mode"),
}),
)
expect(mockTask.recordToolUsage).not.toHaveBeenCalled()
expect(mockTask.recordToolError).toHaveBeenCalledWith("use_mcp_tool", expect.any(String))
expect(mockTask.consecutiveMistakeCount).toBe(1)
expect(mockTask.didAlreadyUseTool).toBe(false)
})
it("resolves aliases in the model's includedTools before passing them to the shared layer", async () => {
// A model may advertise tools under alias names; the shared layer compares
// canonical names, so "write_file" must arrive as "write_to_file". The
// model metadata travels in the request's snapshot, not via a live
// getModel() read.
mockTask.providerRef = {
deref: () => ({
getState: vi.fn().mockResolvedValue({
mode: "code",
customModes: [],
}),
getMcpHub: () => ({
findServerNameBySanitizedName: () => "my_server",
}),
}),
}
vi.mocked(validateToolUse).mockImplementationOnce(() => {
throw new Error('Tool "use_mcp_tool" is not allowed in code mode.')
})
mockTask.assistantMessageContent = [
{
type: "mcp_tool_use",
id: "call_native_mcp_alias",
name: "mcp_my_server_do_thing",
serverName: "my_server",
toolName: "do_thing",
arguments: {},
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, {
...baseSnapshot,
modelInfo: { contextWindow: 200_000, supportsPromptCache: true, includedTools: ["write_file"] },
})
const calls = vi.mocked(validateToolUse).mock.calls
expect(calls.length).toBeGreaterThan(0)
expect(calls[calls.length - 1][0]).toBe("use_mcp_tool")
expect(calls[calls.length - 1][6]).toEqual(["write_to_file"])
})
it("pushes no tool_result when the native block omits its id, but still records the rejection", async () => {
// McpToolUse.id is optional; with no tool_use_id there is nothing to
// answer, so the error tool_result is skipped while the rejection is
// still recorded.
mockTask.providerRef = {
deref: () => ({
getState: vi.fn().mockResolvedValue({
mode: "code",
customModes: [],
}),
getMcpHub: () => ({
findServerNameBySanitizedName: () => "my_server",
}),
}),
}
vi.mocked(validateToolUse).mockImplementationOnce(() => {
throw new Error('Tool "use_mcp_tool" is not allowed in code mode.')
})
mockTask.assistantMessageContent = [
{
type: "mcp_tool_use",
name: "mcp_my_server_do_thing",
serverName: "my_server",
toolName: "do_thing",
arguments: {},
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
expect(mockTask.pushToolResultToUserContent).not.toHaveBeenCalled()
expect(mockTask.userMessageContent).toHaveLength(0)
expect(mockTask.recordToolError).toHaveBeenCalledWith("use_mcp_tool", expect.any(String))
expect(mockTask.consecutiveMistakeCount).toBe(1)
expect(mockTask.didAlreadyUseTool).toBe(false)
})
})
describe("undefined provider state", () => {
// The presenter reads only the request snapshot, never live provider state,
// so an unavailable provider must not affect validation: the task-local
// mode and the snapshot's own fields govern the validator call.
it("falls back to empty state when provider is unavailable", async () => {
mockTask.providerRef = { deref: () => undefined }
mockTask.assistantMessageContent = [
{
type: "tool_use",
id: "call_no_state",
name: "read_file",
params: { path: "test.ts" },
nativeArgs: { path: "test.ts" },
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
// validateToolUse must still be called with the task-local mode.
const calls = vi.mocked(validateToolUse).mock.calls
expect(calls.length).toBeGreaterThan(0)
expect(calls[0][1]).toBe("code")
// customModes comes from the snapshot's own customModes field ([] here), not from provider state.
expect(calls[0][2]).toEqual([])
})
})
describe("mode delegation regression", () => {
// Regression for issue #1623.
// Before the fix, validateToolUse received the shared provider mode instead
// of the task-local mode, so a child delegated to "architect" mode would have
// its tools validated against "orchestrator".
it("passes the task-local mode to validateToolUse, not the provider mode", async () => {
// Provider says "orchestrator"; task was delegated to "architect".
mockTask.providerRef = {
deref: () => ({
getState: vi.fn().mockResolvedValue({
mode: "orchestrator",
// Poisoned: a live read would pass these customModes
// to validateToolUse instead of the snapshot's [].
customModes: [{ slug: "delegated", name: "Delegated", roleDefinition: "", groups: [] }],
}),
}),
}
mockTask.getTaskMode = vi.fn().mockResolvedValue("architect")
mockTask.assistantMessageContent = [
{
type: "tool_use",
id: "call_delegation",
name: "read_file",
params: { path: "test.ts" },
nativeArgs: { path: "test.ts" },
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
// The key assertion: task-local mode "architect" was passed, not "orchestrator".
const calls = vi.mocked(validateToolUse).mock.calls
expect(calls.length).toBeGreaterThan(0)
expect(calls[0][0]).toBe("read_file")
expect(calls[0][1]).toBe("architect")
})
it("passes the task-local mode to validateToolUse for a native mcp_tool_use block", async () => {
// The native mcp arm has its own validateToolUse call site and must honor
// the same task-local mode contract as the tool_use arm: provider state
// deliberately reports a different mode than the task's.
mockTask.providerRef = {
deref: () => ({
getState: vi.fn().mockResolvedValue({
mode: "orchestrator",
customModes: [],
}),
getMcpHub: () => ({
findServerNameBySanitizedName: () => "my_server",
}),
}),
}
mockTask.getTaskMode = vi.fn().mockResolvedValue("architect")
// Throw so the handler is never reached — the assertion is on the
// arguments the call site passed to the shared layer.
vi.mocked(validateToolUse).mockImplementationOnce(() => {
throw new Error("Task-local mode check.")
})
mockTask.assistantMessageContent = [
{
type: "mcp_tool_use",
id: "call_delegation_mcp",
name: "mcp_my_server_do_thing",
serverName: "my_server",
toolName: "do_thing",
arguments: {},
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
const calls = vi.mocked(validateToolUse).mock.calls
expect(calls.length).toBeGreaterThan(0)
expect(calls[calls.length - 1][0]).toBe("use_mcp_tool")
// The discriminating assertion: task-local "architect", not provider
// "orchestrator" — the exact pre-delegation bug shape.
expect(calls[calls.length - 1][1]).toBe("architect")
})
})
describe("native mcp_tool_use policy snapshot consumption", () => {
// The native arm must validate against the request's frozen snapshot, never
// a live provider-state re-read. The doubles below deliberately disagree
// with the passed snapshot so any surviving live read flips an observable.
it("enforces the snapshot's disabledTools even when live state allows the tool", async () => {
const mockHub = {
findServerNameBySanitizedName: () => "my_server",
getAllServers: () => [
{
name: "my_server",
tools: [{ name: "do_thing", enabledForPrompt: true }],
},
],
callTool: vi.fn(),
}
// Live state allows use_mcp_tool (empty list); the snapshot disables it.
mockTask.providerRef = {
deref: () => ({
getState: vi.fn().mockResolvedValue({ mode: "code", customModes: [], disabledTools: [] }),
getMcpHub: () => mockHub,
}),
}
vi.mocked(validateToolUse).mockImplementationOnce(() => {
throw new Error('Tool "use_mcp_tool" is not allowed in code mode.')
})
mockTask.assistantMessageContent = [
{
type: "mcp_tool_use",
id: "call_native_mcp_snapshot_disabled",
name: "mcp_my_server_do_thing",
serverName: "my_server",
toolName: "do_thing",
arguments: {},
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, {
...baseSnapshot,
disabledTools: ["use_mcp_tool"],
})
// The requirements map folded the snapshot's disabledTools, not the
// live (empty) list — the policy decision is snapshot-sourced.
const calls = vi.mocked(validateToolUse).mock.calls
expect(calls.length).toBeGreaterThan(0)
expect(calls[calls.length - 1][0]).toBe("use_mcp_tool")
expect(calls[calls.length - 1][3]).toMatchObject({ use_mcp_tool: false })
// Rejection effects: error tool_result, no execution, no success attribution.
expect(mockTask.userMessageContent).toHaveLength(1)
expect(mockTask.userMessageContent[0]).toMatchObject({
type: "tool_result",
tool_use_id: "call_native_mcp_snapshot_disabled",
is_error: true,
})
expect(mockHub.callTool).not.toHaveBeenCalled()
expect(mockTask.recordToolUsage).not.toHaveBeenCalled()
expect(mockTask.recordToolError).toHaveBeenCalledWith("use_mcp_tool", expect.any(String))
})
it("executes when the snapshot allows the tool even though live state disables it", async () => {
const mockHub = {
findServerNameBySanitizedName: () => "my_server",
getAllServers: () => [
{
name: "my_server",
tools: [{ name: "do_thing", enabledForPrompt: true }],
},
],
callTool: vi.fn().mockResolvedValue({ content: [{ type: "text", text: "ok" }] }),
}
// Live state disables use_mcp_tool; the snapshot (the request's policy)
// allows it. Only the snapshot may decide.
mockTask.providerRef = {
deref: () => ({
getState: vi.fn().mockResolvedValue({
mode: "code",
customModes: [],
disabledTools: ["use_mcp_tool"],
}),
getMcpHub: () => mockHub,
}),
}
// Mocked handle keeps the claim scoped to the validation region: the
// observable is the requirements the arm built, without handler noise.
const handleSpy = vi.spyOn(useMcpToolTool, "handle").mockResolvedValue(undefined)
mockTask.assistantMessageContent = [
{
type: "mcp_tool_use",
id: "call_native_mcp_snapshot_allowed",
name: "mcp_my_server_do_thing",
serverName: "my_server",
toolName: "do_thing",
arguments: {},
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
const calls = vi.mocked(validateToolUse).mock.calls
expect(calls.length).toBeGreaterThan(0)
expect(calls[calls.length - 1][0]).toBe("use_mcp_tool")
// The snapshot's empty disabledTools produced an empty requirements map;
// a live read of the disabled list would have folded use_mcp_tool: false.
expect(calls[calls.length - 1][3]).toEqual({})
expect(handleSpy).toHaveBeenCalledTimes(1)
})
it("performs no provider-state read on the native validation path", async () => {
// Handler mocked so the only reachable pre-handler code is the
// validation arm itself; any getState call inside the presenter's
// native path is then a live policy re-read. Reads made by the real
// handler internals are out of this claim by construction.
const getState = vi.fn().mockResolvedValue({
mode: "code",
customModes: [],
disabledTools: ["use_mcp_tool"],
})
mockTask.providerRef = {
deref: () => ({
getState,
getMcpHub: () => ({
findServerNameBySanitizedName: () => "my_server",
}),
}),
}
const handleSpy = vi.spyOn(useMcpToolTool, "handle").mockResolvedValue(undefined)
mockTask.assistantMessageContent = [
{
type: "mcp_tool_use",
id: "call_native_mcp_no_live_read",
name: "mcp_my_server_do_thing",
serverName: "my_server",
toolName: "do_thing",
arguments: {},
partial: false,
},
]
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
// The arm ran (validation reached the shared layer) yet never touched
// provider state: policy came exclusively from the snapshot.
expect(vi.mocked(validateToolUse).mock.calls.length).toBeGreaterThan(0)
expect(handleSpy).toHaveBeenCalledTimes(1)
expect(getState).not.toHaveBeenCalled()
})
})
})