Skip to content

Commit 802554a

Browse files
committed
fix(tools): deduplicate canonical names before ranking
1 parent 5c59d45 commit 802554a

3 files changed

Lines changed: 57 additions & 6 deletions

File tree

‎src/services/tools/ToolRouter.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,16 @@ export class ToolRouter {
4040
// keeping task scopes and changed tool descriptions isolated.
4141
const key = createHash("sha256").update(JSON.stringify(scopedTools)).digest("hex")
4242
if (this.indexedTools?.key !== key) {
43-
this.indexedTools = { key, tools: scopedTools.map((tool) => ({ ...tool })) }
43+
// Canonical names can collide after sanitizing or truncating. Keep the
44+
// first tool per name before ranking so collisions do not use Top-K slots.
45+
const unique = new Map<string, ToolDoc>()
46+
for (const tool of scopedTools) {
47+
const name = buildMcpToolName(tool.serverName, tool.toolName)
48+
if (!unique.has(name)) {
49+
unique.set(name, { ...tool })
50+
}
51+
}
52+
this.indexedTools = { key, tools: [...unique.values()] }
4453
}
4554
this.ranker ??= createRanker()
4655
const ranked = await this.ranker.rank(query, this.indexedTools.tools, Math.floor(k))

‎src/services/tools/__tests__/ToolRouter.integration.spec.ts‎

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as fs from "fs/promises"
22
import * as os from "os"
33
import * as path from "path"
4+
import type { Mock } from "vitest"
45
import type { McpServer } from "@roo-code/types"
56
import type { ClineProvider } from "../../../core/webview/ClineProvider"
67
import { GlobalFileNames } from "../../../shared/globalFileNames"
@@ -13,6 +14,9 @@ vi.mock("../../../core/webview/ClineProvider")
1314
describe("ToolRouter with McpHub", () => {
1415
let directory: string
1516
let hub: McpHub
17+
// The hub holds its provider weakly, so the suite keeps the strong reference.
18+
let provider: Partial<ClineProvider>
19+
let post: Mock<ClineProvider["postMessageToWebview"]>
1620
const router = ToolRouter.getInstance()
1721
const tools = [{ serverName: "github", toolName: "issues", description: "search tickets" }]
1822
function addServer(): McpServer {
@@ -28,10 +32,11 @@ describe("ToolRouter with McpHub", () => {
2832

2933
beforeEach(async () => {
3034
directory = await fs.mkdtemp(path.join(os.tmpdir(), "tool-router-"))
31-
const provider: Partial<ClineProvider> = {
35+
post = vi.fn<ClineProvider["postMessageToWebview"]>().mockResolvedValue(undefined)
36+
provider = {
3237
cwd: directory,
3338
ensureSettingsDirectoryExists: async () => directory,
34-
postMessageToWebview: vi.fn().mockResolvedValue(undefined),
39+
postMessageToWebview: post,
3540
getState: vi.fn().mockResolvedValue({ mcpEnabled: false }),
3641
}
3742
// The hub uses only cwd, settings directory, state, and webview posting.
@@ -117,14 +122,37 @@ describe("ToolRouter with McpHub", () => {
117122
})
118123
const changed = vi.fn()
119124
hub.onServerListChanged(changed)
120-
addServer()
121-
const post = vi.spyOn(hub["providerRef"].deref()!, "postMessageToWebview")
125+
const server = addServer()
126+
post.mockClear()
122127
await expect(hub["notifyWebviewOfServerChanges"]()).resolves.toBeUndefined()
123-
expect(post).toHaveBeenCalled()
128+
expect(post).toHaveBeenCalledWith({ type: "mcpServers", mcpServers: [server] })
124129
expect(changed).toHaveBeenCalledTimes(1)
125130
expect(log).toHaveBeenCalledWith("[McpHub] Server-list change listener failed:", failure)
126131
await expect(hub.dispose()).resolves.toBeUndefined()
127132
expect(changed).toHaveBeenCalledTimes(2)
128133
expect(hub["serverListEvents"].listenerCount("changed")).toBe(0)
129134
})
135+
136+
it("fires the event before the settings read can fail", async () => {
137+
await fs.writeFile(path.join(directory, GlobalFileNames.mcpSettings), "{ not json")
138+
const changed = vi.fn()
139+
hub.onServerListChanged(changed)
140+
addServer()
141+
await expect(hub["notifyWebviewOfServerChanges"]()).rejects.toThrow()
142+
expect(changed).toHaveBeenCalledTimes(1)
143+
})
144+
145+
it("fires the event and keeps going when the webview post rejects", async () => {
146+
const failure = new Error("post failed")
147+
const log = vi.spyOn(console, "error").mockImplementation(() => {})
148+
const changed = vi.fn()
149+
hub.onServerListChanged(changed)
150+
addServer()
151+
post.mockClear()
152+
post.mockRejectedValueOnce(failure)
153+
await expect(hub["notifyWebviewOfServerChanges"]()).resolves.toBeUndefined()
154+
expect(post).toHaveBeenCalledTimes(1)
155+
expect(changed).toHaveBeenCalledTimes(1)
156+
expect(log).toHaveBeenCalledWith("[McpHub] Error calling targetProvider.postMessageToWebview:", failure)
157+
})
130158
})

‎src/services/tools/__tests__/ToolRouter.spec.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,20 @@ describe("ToolRouter", () => {
5454
).toEqual(["mcp--github--issues", "mcp--jira--issues"])
5555
})
5656

57+
it.each(["attachInitial", "search"] as const)("%s drops colliding canonical names before Top-K", async (method) => {
58+
const result = await ToolRouter.getInstance()[method](
59+
"tickets",
60+
[
61+
{ serverName: "a b", toolName: "t", description: "tickets" },
62+
{ serverName: "a_b", toolName: "t", description: "tickets" },
63+
{ serverName: "other", toolName: "u", description: "tickets" },
64+
],
65+
2,
66+
)
67+
expect(result).toHaveLength(2)
68+
expect(result).toEqual(expect.arrayContaining(["mcp--a_b--t", "mcp--other--u"]))
69+
})
70+
5771
it.each(["attachInitial", "search"] as const)("%s validates and floors limits", async (method) => {
5872
const router = ToolRouter.getInstance()
5973
for (const limit of [NaN, Infinity, -Infinity, -1, 0, 0.5]) {

0 commit comments

Comments
 (0)