Skip to content

Commit 57fce8f

Browse files
PierrunoYTclaude
andcommitted
fix(mcp): keep over-long MCP tool names out of API history
buildMcpToolName cut names at 64 characters, so models called the full name instead; Zoo Code resolved it but wrote the over-long name to history, which Bedrock and Azure OpenAI reject on every later request. Shorten with a hash suffix, resolve called names against the declared names, write history under the declared name, and rename over-long names already in history when building a request. Fixes #2065 Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
1 parent 16425bc commit 57fce8f

11 files changed

Lines changed: 320 additions & 22 deletions

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

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,14 @@ import type {
1616
ApiStreamToolCallDeltaChunk,
1717
ApiStreamToolCallEndChunk,
1818
} from "../../api/transform/stream"
19-
import { MCP_TOOL_PREFIX, MCP_TOOL_SEPARATOR, parseMcpToolName, normalizeMcpToolName } from "../../utils/mcp-name"
19+
import {
20+
MAX_TOOL_NAME_LENGTH,
21+
MCP_TOOL_PREFIX,
22+
MCP_TOOL_SEPARATOR,
23+
buildMcpToolName,
24+
parseMcpToolName,
25+
normalizeMcpToolName,
26+
} from "../../utils/mcp-name"
2027

2128
/**
2229
* Helper type to extract properly typed native arguments for a given tool.
@@ -1141,8 +1148,13 @@ export class NativeToolCallParser {
11411148
const result: McpToolUse = {
11421149
type: "mcp_tool_use" as const,
11431150
id: toolCall.id,
1144-
// Keep the original tool name (e.g., "mcp--serverName--toolName") for API history
1145-
name: toolCall.name,
1151+
// Keep the original tool name (e.g., "mcp--serverName--toolName") for API history.
1152+
// A name over the provider limit can only be the uncut name; providers reject it in
1153+
// history, so record it under the name that was declared to the model instead.
1154+
name:
1155+
toolCall.name.length > MAX_TOOL_NAME_LENGTH
1156+
? buildMcpToolName(serverName, toolName)
1157+
: toolCall.name,
11461158
serverName,
11471159
toolName,
11481160
arguments: args,
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { buildMcpToolName } from "../../../utils/mcp-name"
2+
import { NativeToolCallParser } from "../NativeToolCallParser"
3+
4+
const SERVER = "company-gateway-tools"
5+
const TOOL = "confluence-confluence_get_space_page_tree"
6+
7+
describe("NativeToolCallParser.parseDynamicMcpTool name for API history", () => {
8+
it("records an over-long uncut name under the declared name", () => {
9+
const result = NativeToolCallParser.parseDynamicMcpTool({
10+
id: "toolu_1",
11+
name: `mcp--${SERVER}--${TOOL}`,
12+
arguments: "{}",
13+
})
14+
15+
expect(result?.name).toBe(buildMcpToolName(SERVER, TOOL))
16+
expect(result?.name.length).toBeLessThanOrEqual(64)
17+
})
18+
19+
it("keeps the declared name the model returned", () => {
20+
const declared = buildMcpToolName(SERVER, TOOL)
21+
22+
const result = NativeToolCallParser.parseDynamicMcpTool({ id: "toolu_2", name: declared, arguments: "{}" })
23+
24+
expect(result?.name).toBe(declared)
25+
})
26+
27+
it("keeps a short name verbatim", () => {
28+
const result = NativeToolCallParser.parseDynamicMcpTool({
29+
id: "toolu_3",
30+
name: "mcp--weather--get_forecast",
31+
arguments: "{}",
32+
})
33+
34+
expect(result).toMatchObject({ name: "mcp--weather--get_forecast", serverName: "weather" })
35+
})
36+
})

‎src/core/assistant-message/__tests__/presentAssistantMessage-auto-deny.spec.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,10 @@ interface MockTask {
8888
providerRef: {
8989
deref: () => {
9090
getState: ReturnType<typeof vi.fn>
91-
getMcpHub?: () => { findServerNameBySanitizedName: (name: string) => string | undefined }
91+
getMcpHub?: () => {
92+
findServerNameBySanitizedName: (name: string) => string | undefined
93+
getAllServers: () => Array<{ name: string; tools?: Array<{ name: string }> }>
94+
}
9295
}
9396
}
9497
say: ReturnType<typeof vi.fn>
@@ -368,7 +371,7 @@ describe("presentAssistantMessage - automatic (policy) denials", () => {
368371
mockTask.providerRef = {
369372
deref: () => ({
370373
getState: vi.fn().mockResolvedValue({ mode: "code", customModes: [] }),
371-
getMcpHub: () => ({ findServerNameBySanitizedName: () => undefined }),
374+
getMcpHub: () => ({ findServerNameBySanitizedName: () => undefined, getAllServers: () => [] }),
372375
}),
373376
}
374377

@@ -428,7 +431,7 @@ describe("presentAssistantMessage - automatic (policy) denials", () => {
428431
mockTask.providerRef = {
429432
deref: () => ({
430433
getState: vi.fn().mockResolvedValue({ mode: "code", customModes: [] }),
431-
getMcpHub: () => ({ findServerNameBySanitizedName: () => undefined }),
434+
getMcpHub: () => ({ findServerNameBySanitizedName: () => undefined, getAllServers: () => [] }),
432435
}),
433436
}
434437

@@ -541,7 +544,7 @@ describe("presentAssistantMessage - automatic (policy) denials", () => {
541544
mockTask.providerRef = {
542545
deref: () => ({
543546
getState: vi.fn().mockResolvedValue({ mode: "code", customModes: [] }),
544-
getMcpHub: () => ({ findServerNameBySanitizedName: () => undefined }),
547+
getMcpHub: () => ({ findServerNameBySanitizedName: () => undefined, getAllServers: () => [] }),
545548
}),
546549
}
547550

@@ -581,7 +584,7 @@ describe("presentAssistantMessage - automatic (policy) denials", () => {
581584
mockTask.providerRef = {
582585
deref: () => ({
583586
getState: vi.fn().mockResolvedValue({ mode: "code", customModes: [] }),
584-
getMcpHub: () => ({ findServerNameBySanitizedName: () => undefined }),
587+
getMcpHub: () => ({ findServerNameBySanitizedName: () => undefined, getAllServers: () => [] }),
585588
}),
586589
}
587590

@@ -642,7 +645,7 @@ describe("presentAssistantMessage - automatic (policy) denials", () => {
642645
mockTask.providerRef = {
643646
deref: () => ({
644647
getState: vi.fn().mockResolvedValue({ mode: "code", customModes: [] }),
645-
getMcpHub: () => ({ findServerNameBySanitizedName: () => undefined }),
648+
getMcpHub: () => ({ findServerNameBySanitizedName: () => undefined, getAllServers: () => [] }),
646649
}),
647650
}
648651

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,7 @@ describe("presentAssistantMessage - Custom Tool Recording", () => {
491491
}),
492492
getMcpHub: () => ({
493493
findServerNameBySanitizedName: () => "test-server",
494+
getAllServers: () => [],
494495
executeToolCall: vi.fn().mockResolvedValue({ content: [{ type: "text", text: "result" }] }),
495496
}),
496497
}),

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

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { getModeBySlug } from "../../../shared/modes"
99
import type { Task } from "../../task/Task"
1010
import type { RequestPolicySnapshot } from "../../prompts/tools/effective-tool-policy"
1111
import { useMcpToolTool } from "../../tools/UseMcpToolTool"
12+
import { buildMcpToolName, parseMcpToolName } from "../../../utils/mcp-name"
1213

1314
vi.mock("../../task/Task")
1415
vi.mock("../../../shared/modes", async (importOriginal) => {
@@ -80,7 +81,10 @@ interface MockTask {
8081
deref: () =>
8182
| {
8283
getState: ReturnType<typeof vi.fn>
83-
getMcpHub?: () => { findServerNameBySanitizedName: (name: string) => string | undefined }
84+
getMcpHub?: () => {
85+
findServerNameBySanitizedName: (name: string) => string | undefined
86+
getAllServers: () => Array<{ name: string; tools?: Array<{ name: string }> }>
87+
}
8488
}
8589
| undefined
8690
}
@@ -379,6 +383,7 @@ describe("presentAssistantMessage - tool usage attribution", () => {
379383
}),
380384
getMcpHub: () => ({
381385
findServerNameBySanitizedName: () => "my_server",
386+
getAllServers: () => [],
382387
}),
383388
}),
384389
}
@@ -548,6 +553,7 @@ describe("presentAssistantMessage - tool usage attribution", () => {
548553
}),
549554
getMcpHub: () => ({
550555
findServerNameBySanitizedName: () => "my_server",
556+
getAllServers: () => [],
551557
}),
552558
}),
553559
}
@@ -638,6 +644,7 @@ describe("presentAssistantMessage - tool usage attribution", () => {
638644
}),
639645
getMcpHub: () => ({
640646
findServerNameBySanitizedName: () => "my_server",
647+
getAllServers: () => [],
641648
}),
642649
}),
643650
}
@@ -680,6 +687,7 @@ describe("presentAssistantMessage - tool usage attribution", () => {
680687
}),
681688
getMcpHub: () => ({
682689
findServerNameBySanitizedName: () => "my_server",
690+
getAllServers: () => [],
683691
}),
684692
}),
685693
}
@@ -787,6 +795,7 @@ describe("presentAssistantMessage - tool usage attribution", () => {
787795
}),
788796
getMcpHub: () => ({
789797
findServerNameBySanitizedName: () => "my_server",
798+
getAllServers: () => [],
790799
}),
791800
}),
792801
}
@@ -932,6 +941,43 @@ describe("presentAssistantMessage - tool usage attribution", () => {
932941
expect(handleSpy).toHaveBeenCalledTimes(1)
933942
})
934943

944+
it("resolves a hash-shortened MCP tool name to its server and tool before executing", async () => {
945+
const serverName = "company-gateway-tools"
946+
const realToolName = "confluence-confluence_get_space_page_tree"
947+
const declaredName = buildMcpToolName(serverName, realToolName)
948+
const mockHub = {
949+
findServerNameBySanitizedName: () => serverName,
950+
getAllServers: () => [{ name: serverName, tools: [{ name: realToolName, enabledForPrompt: true }] }],
951+
}
952+
mockTask.providerRef = {
953+
deref: () => ({
954+
getState: vi.fn().mockResolvedValue({ mode: "code", customModes: [], disabledTools: [] }),
955+
getMcpHub: () => mockHub,
956+
}),
957+
}
958+
const handleSpy = vi.spyOn(useMcpToolTool, "handle").mockResolvedValue(undefined)
959+
// The parser can only recover a cut tool name from the shortened one.
960+
const parsed = parseMcpToolName(declaredName)!
961+
mockTask.assistantMessageContent = [
962+
{
963+
type: "mcp_tool_use",
964+
id: "call_hashed_name",
965+
name: declaredName,
966+
serverName: parsed.serverName,
967+
toolName: parsed.toolName,
968+
arguments: {},
969+
partial: false,
970+
},
971+
]
972+
973+
await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot)
974+
975+
expect(handleSpy).toHaveBeenCalledTimes(1)
976+
expect(handleSpy.mock.calls[0][1]).toMatchObject({
977+
nativeArgs: { server_name: serverName, tool_name: realToolName },
978+
})
979+
})
980+
935981
it("performs no provider-state read on the native validation path", async () => {
936982
// Handler mocked so the only reachable pre-handler code is the
937983
// validation arm itself; any getState call inside the presenter's
@@ -947,6 +993,7 @@ describe("presentAssistantMessage - tool usage attribution", () => {
947993
getState,
948994
getMcpHub: () => ({
949995
findServerNameBySanitizedName: () => "my_server",
996+
getAllServers: () => [],
950997
}),
951998
}),
952999
}

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

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ import { codebaseSearchTool } from "../tools/CodebaseSearchTool"
4444

4545
import { formatResponse } from "../prompts/responses"
4646
import { sanitizeToolUseId } from "../../utils/tool-id"
47+
import { resolveMcpToolByName, toolNamesMatch } from "../../utils/mcp-name"
4748

4849
/**
4950
* Maps a raw, potentially model-controlled tool name to a safe analytics key.
@@ -329,6 +330,25 @@ async function presentAssistantMessageBlock(cline: Task, policySnapshot: Request
329330
}
330331
}
331332

333+
// A name shortened to fit the provider limit cannot be parsed back into its tool, so
334+
// when the parsed names match nothing, look the called name up among the declared ones.
335+
let resolvedToolName = mcpBlock.toolName
336+
if (mcpHub && !mcpBlock.partial) {
337+
const servers = mcpHub.getAllServers()
338+
const parsedServer = servers.find((server) => server.name === resolvedServerName)
339+
const parsedToolExists = parsedServer?.tools?.some((tool) =>
340+
toolNamesMatch(tool.name, resolvedToolName),
341+
)
342+
343+
if (!parsedToolExists) {
344+
const resolved = resolveMcpToolByName(servers, mcpBlock.name)
345+
if (resolved) {
346+
resolvedServerName = resolved.serverName
347+
resolvedToolName = resolved.toolName
348+
}
349+
}
350+
}
351+
332352
// Execute the MCP tool using the same handler as use_mcp_tool
333353
// Create a synthetic ToolUse block that the useMcpToolTool can handle
334354
const syntheticToolUse: ToolUse<"use_mcp_tool"> = {
@@ -337,13 +357,13 @@ async function presentAssistantMessageBlock(cline: Task, policySnapshot: Request
337357
name: "use_mcp_tool",
338358
params: {
339359
server_name: resolvedServerName,
340-
tool_name: mcpBlock.toolName,
360+
tool_name: resolvedToolName,
341361
arguments: JSON.stringify(mcpBlock.arguments),
342362
},
343363
partial: mcpBlock.partial,
344364
nativeArgs: {
345365
server_name: resolvedServerName,
346-
tool_name: mcpBlock.toolName,
366+
tool_name: resolvedToolName,
347367
arguments: mcpBlock.arguments,
348368
},
349369
}

‎src/core/task/Task.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@ import { type AutoDenyDetail, AutoApprovalHandler, checkAutoApproval } from "../
140140
import { MessageManager } from "../message-manager"
141141
import { validateAndFixToolResultIds } from "./validateToolResultIds"
142142
import { mergeConsecutiveApiMessages } from "./mergeConsecutiveApiMessages"
143+
import { capMcpToolUseNames } from "./capMcpToolUseNames"
143144
import { prepareApiConversationMessage } from "./apiConversationHistory"
144145
import { shouldAddUserMessageToHistory } from "./messageCounting"
145146
import { type TaskExecutionContext } from "./providerHandoff"
@@ -5845,7 +5846,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
58455846
// For API only: merge consecutive user messages (excludes summary messages per
58465847
// mergeConsecutiveApiMessages implementation) without mutating stored history.
58475848
const mergedForApi = mergeConsecutiveApiMessages(messagesSinceLastSummary, { roles: ["user"] })
5848-
const messagesWithoutImages = maybeRemoveImageBlocks(mergedForApi, this.api)
5849+
const messagesWithoutImages = maybeRemoveImageBlocks(capMcpToolUseNames(mergedForApi), this.api)
58495850
const cleanConversationHistory = this.buildCleanConversationHistory(
58505851
messagesWithoutImages as ApiMessage[],
58515852
requestModelInfo,
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import type { Anthropic } from "@anthropic-ai/sdk"
2+
3+
import type { ApiMessage } from "../../task-persistence"
4+
import { buildMcpToolName } from "../../../utils/mcp-name"
5+
import { capMcpToolUseNames } from "../capMcpToolUseNames"
6+
7+
type Block = Anthropic.Messages.ContentBlockParam
8+
9+
const SERVER = "company-gateway-tools"
10+
const TOOL = "confluence-confluence_get_space_page_tree"
11+
const UNCUT = `mcp--${SERVER}--${TOOL}`
12+
13+
const use = (name: string): Block => ({ type: "tool_use", id: "toolu_1", name, input: {} })
14+
const assistant = (...content: Block[]): ApiMessage => ({ role: "assistant", content })
15+
16+
describe("capMcpToolUseNames", () => {
17+
it("renames an over-long MCP tool_use to the declared name", () => {
18+
const [message] = capMcpToolUseNames([assistant({ type: "text", text: "calling" }, use(UNCUT))])
19+
20+
expect(message.content).toEqual([{ type: "text", text: "calling" }, use(buildMcpToolName(SERVER, TOOL))])
21+
})
22+
23+
it("leaves short names, non-MCP names and other roles untouched", () => {
24+
const messages: ApiMessage[] = [
25+
{ role: "user", content: "hi" },
26+
assistant(use("read_file"), use("mcp--weather--get_forecast")),
27+
]
28+
29+
expect(capMcpToolUseNames(messages)).toEqual(messages)
30+
})
31+
32+
it("leaves an over-long name it cannot parse as an MCP tool", () => {
33+
const name = "x".repeat(70)
34+
35+
expect(capMcpToolUseNames([assistant(use(name))])[0].content).toEqual([use(name)])
36+
})
37+
38+
it("does not mutate its input", () => {
39+
const input = [assistant(use(UNCUT))]
40+
const snapshot = structuredClone(input)
41+
42+
capMcpToolUseNames(input)
43+
44+
expect(input).toEqual(snapshot)
45+
})
46+
})
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { Anthropic } from "@anthropic-ai/sdk"
2+
3+
import type { ApiMessage } from "../task-persistence"
4+
import { MAX_TOOL_NAME_LENGTH, buildMcpToolName, parseMcpToolName } from "../../utils/mcp-name"
5+
6+
/**
7+
* Rewrites MCP `tool_use` names longer than the provider limit to the name that was declared
8+
* to the model. Providers such as Bedrock Converse and Azure OpenAI reject over-long names in
9+
* history, so a task that already recorded one would otherwise fail on every retry.
10+
*
11+
* Used for API request shaping only; stored history is not mutated.
12+
*/
13+
export function capMcpToolUseNames(messages: ApiMessage[]): ApiMessage[] {
14+
return messages.map((message) => {
15+
if (message.role !== "assistant" || !Array.isArray(message.content)) return message
16+
17+
const needsRename = message.content.some(
18+
(block) => block.type === "tool_use" && block.name.length > MAX_TOOL_NAME_LENGTH,
19+
)
20+
if (!needsRename) return message
21+
22+
return {
23+
...message,
24+
content: message.content.map((block): Anthropic.Messages.ContentBlockParam => {
25+
if (block.type !== "tool_use" || block.name.length <= MAX_TOOL_NAME_LENGTH) return block
26+
27+
const parsed = parseMcpToolName(block.name)
28+
return parsed ? { ...block, name: buildMcpToolName(parsed.serverName, parsed.toolName) } : block
29+
}),
30+
}
31+
})
32+
}

0 commit comments

Comments
 (0)