Skip to content

Commit 200d2aa

Browse files
authored
fix(telemetry): record tool usage once centrally, sanitize raw tool names (#1073)
* fix(telemetry): record tool usage once centrally, sanitize raw tool names * fix(telemetry): defer native MCP usage recording until validation passes * fix(telemetry): narrow UseMcpToolTool callback, harden test mocks, close coverage gaps * test(telemetry): complete native MCP mock so validateToolExists runs the real path
1 parent 2fcfe90 commit 200d2aa

20 files changed

Lines changed: 588 additions & 50 deletions

‎packages/types/src/tool.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ export const toolNames = [
4646
"skill",
4747
"generate_image",
4848
"custom_tool",
49+
"invalid_tool_call",
4950
] as const
5051

5152
export const toolNamesSchema = z.enum(toolNames)

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,17 @@ vi.mock("@roo-code/core", () => ({
2323
},
2424
}))
2525

26+
// presentAssistantMessage records tool usage through TelemetryService.instance.
27+
vi.mock("@roo-code/telemetry", () => ({
28+
TelemetryService: {
29+
instance: {
30+
captureToolUsage: vi.fn(),
31+
captureConsecutiveMistakeError: vi.fn(),
32+
captureEvent: vi.fn(),
33+
},
34+
},
35+
}))
36+
2637
import { customToolRegistry } from "@roo-code/core"
2738

2839
describe("presentAssistantMessage - Custom Tool Recording", () => {
Lines changed: 319 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,319 @@
1+
// npx vitest src/core/assistant-message/__tests__/presentAssistantMessage-tool-usage-attribution.spec.ts
2+
3+
import type { Anthropic } from "@anthropic-ai/sdk"
4+
import { describe, it, expect, beforeEach, vi } from "vitest"
5+
import { presentAssistantMessage } from "../presentAssistantMessage"
6+
import { validateToolUse } from "../../tools/validateToolUse"
7+
import { getModeBySlug } from "../../../shared/modes"
8+
import type { Task } from "../../task/Task"
9+
10+
vi.mock("../../task/Task")
11+
vi.mock("../../../shared/modes", async (importOriginal) => {
12+
const actual = await importOriginal<typeof import("../../../shared/modes")>()
13+
return {
14+
...actual,
15+
getModeBySlug: vi.fn(actual.getModeBySlug),
16+
}
17+
})
18+
// isValidToolName is left as the real implementation (only validateToolUse is
19+
// mocked): it has its own independent mcp_ prefix carve-out, and a hand-rolled
20+
// mock allowlist here would mask a regression in toTelemetryToolName's
21+
// ordering relative to isValidToolName.
22+
vi.mock("../../tools/validateToolUse", async (importOriginal) => {
23+
const actual = await importOriginal<typeof import("../../tools/validateToolUse")>()
24+
return {
25+
...actual,
26+
validateToolUse: vi.fn(),
27+
}
28+
})
29+
30+
vi.mock("@roo-code/core", () => ({
31+
customToolRegistry: {
32+
has: vi.fn(() => false),
33+
get: vi.fn(),
34+
},
35+
}))
36+
37+
vi.mock("@roo-code/telemetry", () => ({
38+
TelemetryService: {
39+
instance: {
40+
captureToolUsage: vi.fn(),
41+
captureConsecutiveMistakeError: vi.fn(),
42+
captureEvent: vi.fn(),
43+
},
44+
},
45+
}))
46+
47+
import { TelemetryService } from "@roo-code/telemetry"
48+
49+
interface MockTask {
50+
taskId: string
51+
instanceId: string
52+
abort: boolean
53+
presentAssistantMessageLocked: boolean
54+
presentAssistantMessageHasPendingUpdates: boolean
55+
currentStreamingContentIndex: number
56+
assistantMessageContent: unknown[]
57+
userMessageContent: Anthropic.ToolResultBlockParam[]
58+
didCompleteReadingStream: boolean
59+
didRejectTool: boolean
60+
didAlreadyUseTool: boolean
61+
consecutiveMistakeCount: number
62+
clineMessages: unknown[]
63+
api: { getModel: () => { id: string; info: Record<string, unknown> } }
64+
recordToolUsage: ReturnType<typeof vi.fn>
65+
recordToolError: ReturnType<typeof vi.fn>
66+
toolRepetitionDetector: { check: ReturnType<typeof vi.fn> }
67+
providerRef: {
68+
deref: () => {
69+
getState: ReturnType<typeof vi.fn>
70+
getMcpHub?: () => { findServerNameBySanitizedName: (name: string) => string | undefined }
71+
}
72+
}
73+
say: ReturnType<typeof vi.fn>
74+
ask: ReturnType<typeof vi.fn>
75+
pushToolResultToUserContent: ReturnType<typeof vi.fn>
76+
}
77+
78+
describe("presentAssistantMessage - tool usage attribution", () => {
79+
let mockTask: MockTask
80+
81+
beforeEach(() => {
82+
vi.clearAllMocks()
83+
vi.mocked(validateToolUse).mockImplementation(() => undefined)
84+
85+
mockTask = {
86+
taskId: "test-task-id",
87+
instanceId: "test-instance",
88+
abort: false,
89+
presentAssistantMessageLocked: false,
90+
presentAssistantMessageHasPendingUpdates: false,
91+
currentStreamingContentIndex: 0,
92+
assistantMessageContent: [],
93+
userMessageContent: [],
94+
didCompleteReadingStream: false,
95+
didRejectTool: false,
96+
didAlreadyUseTool: false,
97+
consecutiveMistakeCount: 0,
98+
clineMessages: [],
99+
api: {
100+
getModel: () => ({ id: "test-model", info: {} }),
101+
},
102+
recordToolUsage: vi.fn(),
103+
recordToolError: vi.fn(),
104+
toolRepetitionDetector: {
105+
check: vi.fn().mockReturnValue({ allowExecution: true }),
106+
},
107+
providerRef: {
108+
deref: () => ({
109+
getState: vi.fn().mockResolvedValue({
110+
mode: "code",
111+
customModes: [],
112+
}),
113+
}),
114+
},
115+
say: vi.fn().mockResolvedValue(undefined),
116+
ask: vi.fn().mockResolvedValue({ response: "yesButtonClicked" }),
117+
pushToolResultToUserContent: vi.fn(),
118+
}
119+
120+
mockTask.pushToolResultToUserContent = vi
121+
.fn()
122+
.mockImplementation((toolResult: Anthropic.ToolResultBlockParam) => {
123+
const existingResult = mockTask.userMessageContent.find(
124+
(block) => block.type === "tool_result" && block.tool_use_id === toolResult.tool_use_id,
125+
)
126+
if (existingResult) {
127+
return false
128+
}
129+
mockTask.userMessageContent.push(toolResult)
130+
return true
131+
})
132+
})
133+
134+
it("records exactly one attempt for a normal static tool", async () => {
135+
mockTask.assistantMessageContent = [
136+
{
137+
type: "tool_use",
138+
id: "call_1",
139+
name: "read_file",
140+
params: { path: "test.txt" },
141+
nativeArgs: { path: "test.txt" },
142+
partial: false,
143+
},
144+
]
145+
146+
await presentAssistantMessage(mockTask as unknown as Task)
147+
148+
expect(mockTask.recordToolUsage).toHaveBeenCalledTimes(1)
149+
expect(mockTask.recordToolUsage).toHaveBeenCalledWith("read_file")
150+
expect(TelemetryService.instance.captureToolUsage).toHaveBeenCalledTimes(1)
151+
expect(TelemetryService.instance.captureToolUsage).toHaveBeenCalledWith(mockTask.taskId, "read_file")
152+
})
153+
154+
it("records a valid dynamic mcp_ tool name as use_mcp_tool", async () => {
155+
mockTask.assistantMessageContent = [
156+
{
157+
type: "tool_use",
158+
id: "call_mcp",
159+
name: "mcp_my_server_do_thing",
160+
params: {},
161+
nativeArgs: {},
162+
partial: false,
163+
},
164+
]
165+
166+
await presentAssistantMessage(mockTask as unknown as Task)
167+
168+
expect(mockTask.recordToolUsage).toHaveBeenCalledWith("use_mcp_tool")
169+
expect(TelemetryService.instance.captureToolUsage).toHaveBeenCalledWith(mockTask.taskId, "use_mcp_tool")
170+
})
171+
172+
it("records a malformed mcp_ tool name as use_mcp_tool, not the raw name", async () => {
173+
mockTask.assistantMessageContent = [
174+
{
175+
type: "tool_use",
176+
id: "call_mcp_bad",
177+
name: "mcp_",
178+
params: {},
179+
nativeArgs: {},
180+
partial: false,
181+
},
182+
]
183+
184+
await presentAssistantMessage(mockTask as unknown as Task)
185+
186+
expect(mockTask.recordToolUsage).toHaveBeenCalledWith("use_mcp_tool")
187+
expect(mockTask.recordToolUsage).not.toHaveBeenCalledWith("mcp_")
188+
})
189+
190+
it("records a safe failure key without leaking the raw tool name when validation fails", async () => {
191+
vi.mocked(validateToolUse).mockImplementation(() => {
192+
throw new Error('Tool "read_file" is not allowed in this mode.')
193+
})
194+
195+
mockTask.assistantMessageContent = [
196+
{
197+
type: "tool_use",
198+
id: "call_bad_mode",
199+
name: "read_file",
200+
params: { path: "test.txt" },
201+
nativeArgs: { path: "test.txt" },
202+
partial: false,
203+
},
204+
]
205+
206+
await presentAssistantMessage(mockTask as unknown as Task)
207+
208+
// A known static tool that fails validation still maps to its own name
209+
// (it's a real, recognized tool - just disallowed here), never left raw/unmapped.
210+
expect(mockTask.recordToolError).toHaveBeenCalledWith("read_file", expect.any(String))
211+
// No success attempt should be recorded for a validation failure.
212+
expect(mockTask.recordToolUsage).not.toHaveBeenCalled()
213+
})
214+
215+
it("records invalid_tool_call, not the raw name, when an arbitrary unknown tool fails validation", async () => {
216+
vi.mocked(validateToolUse).mockImplementation(() => {
217+
throw new Error('Unknown tool "totally_made_up_tool". This tool does not exist.')
218+
})
219+
220+
mockTask.assistantMessageContent = [
221+
{
222+
type: "tool_use",
223+
id: "call_unknown",
224+
name: "totally_made_up_tool",
225+
params: {},
226+
nativeArgs: {},
227+
partial: false,
228+
},
229+
]
230+
231+
await presentAssistantMessage(mockTask as unknown as Task)
232+
233+
expect(mockTask.recordToolError).toHaveBeenCalledWith("invalid_tool_call", expect.any(String))
234+
expect(mockTask.recordToolError).not.toHaveBeenCalledWith("totally_made_up_tool", expect.anything())
235+
expect(mockTask.recordToolUsage).not.toHaveBeenCalled()
236+
})
237+
238+
describe("native mcp_tool_use block", () => {
239+
it("records exactly one attempt once the MCP tool's own validation passes", async () => {
240+
mockTask.providerRef = {
241+
deref: () => ({
242+
getState: vi.fn().mockResolvedValue({
243+
mode: "code",
244+
customModes: [],
245+
}),
246+
getMcpHub: () => ({
247+
findServerNameBySanitizedName: () => "my_server",
248+
getAllServers: () => [
249+
{
250+
name: "my_server",
251+
tools: [{ name: "do_thing", enabledForPrompt: true }],
252+
},
253+
],
254+
}),
255+
}),
256+
}
257+
258+
mockTask.assistantMessageContent = [
259+
{
260+
type: "mcp_tool_use",
261+
id: "call_native_mcp",
262+
name: "mcp_my_server_do_thing",
263+
serverName: "my_server",
264+
toolName: "do_thing",
265+
arguments: {},
266+
partial: false,
267+
},
268+
]
269+
270+
await presentAssistantMessage(mockTask as unknown as Task)
271+
272+
expect(mockTask.recordToolUsage).toHaveBeenCalledTimes(1)
273+
expect(mockTask.recordToolUsage).toHaveBeenCalledWith("use_mcp_tool")
274+
expect(TelemetryService.instance.captureToolUsage).toHaveBeenCalledTimes(1)
275+
expect(TelemetryService.instance.captureToolUsage).toHaveBeenCalledWith(mockTask.taskId, "use_mcp_tool")
276+
})
277+
278+
it("records no attempt when the MCP server is not on the mode's allow-list", async () => {
279+
vi.mocked(getModeBySlug).mockReturnValueOnce({
280+
slug: "code",
281+
name: "Code",
282+
roleDefinition: "",
283+
groups: [],
284+
allowedMcpServers: ["some-other-server"],
285+
})
286+
287+
mockTask.providerRef = {
288+
deref: () => ({
289+
getState: vi.fn().mockResolvedValue({
290+
mode: "code",
291+
customModes: [],
292+
}),
293+
getMcpHub: () => ({
294+
findServerNameBySanitizedName: () => "my_server",
295+
}),
296+
}),
297+
}
298+
299+
mockTask.assistantMessageContent = [
300+
{
301+
type: "mcp_tool_use",
302+
id: "call_native_mcp_disallowed",
303+
name: "mcp_my_server_do_thing",
304+
serverName: "my_server",
305+
toolName: "do_thing",
306+
arguments: {},
307+
partial: false,
308+
},
309+
]
310+
311+
await presentAssistantMessage(mockTask as unknown as Task)
312+
313+
// The server is disallowed, so the call never reaches onValidated:
314+
// no success attempt is recorded for a call that was never permitted to execute.
315+
expect(mockTask.recordToolUsage).not.toHaveBeenCalled()
316+
expect(TelemetryService.instance.captureToolUsage).not.toHaveBeenCalled()
317+
})
318+
})
319+
})

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

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,10 @@ describe("presentAssistantMessage - Unknown Tool Handling", () => {
101101
// Verify consecutiveMistakeCount was incremented
102102
expect(mockTask.consecutiveMistakeCount).toBe(1)
103103

104-
// Verify recordToolError was called
104+
// Verify recordToolError was called with a safe static key, never the
105+
// raw model-controlled tool name.
105106
expect(mockTask.recordToolError).toHaveBeenCalledWith(
106-
"nonexistent_tool",
107+
"invalid_tool_call",
107108
expect.stringContaining("Unknown tool"),
108109
)
109110

@@ -135,8 +136,9 @@ describe("presentAssistantMessage - Unknown Tool Handling", () => {
135136
// Verify consecutiveMistakeCount was incremented
136137
expect(mockTask.consecutiveMistakeCount).toBe(1)
137138

138-
// Verify recordToolError was called
139-
expect(mockTask.recordToolError).toHaveBeenCalled()
139+
// Verify recordToolError was called with a safe static key, never the
140+
// raw model-reported tool name ("fake_tool_that_does_not_exist").
141+
expect(mockTask.recordToolError).toHaveBeenCalledWith("invalid_tool_call", expect.anything())
140142

141143
// Verify error message was shown to user
142144
expect(mockTask.say).toHaveBeenCalledWith("error", expect.anything())

0 commit comments

Comments
 (0)