fix(llm): accept offered Claude SDK tools without the MCP prefix

Local dev repairs for #2539, #2686. Regression checks cover reported symptoms and compatibility boundaries.
This commit is contained in:
Bingxi Zhao (Frank)
2026-11-15 00:44:10 +08:00
parent be4f36c166
commit ea67eb00cb
3 changed files with 106 additions and 9 deletions

View File

@@ -57,6 +57,7 @@ class _SessionTurn:
prompt: _Prompt
on_content_delta: Callable[[str], Awaitable[None]] | None
future: asyncio.Future[LLMResponse]
tool_names: frozenset[str] = frozenset()
@dataclass
@@ -119,6 +120,7 @@ class _ClaudeCodeSession:
on_content_delta=turn.on_content_delta,
interrupt=_no_interrupt,
label=_LABEL,
tool_names=turn.tool_names,
)
if not turn.future.done():
turn.future.set_result(response)
@@ -143,12 +145,18 @@ class _ClaudeCodeSession:
self,
prompt: _Prompt,
on_content_delta: Callable[[str], Awaitable[None]] | None,
tool_names: frozenset[str] = frozenset(),
) -> LLMResponse:
if not self.alive:
raise RuntimeError("Claude Code session owner is not running")
future: asyncio.Future[LLMResponse] = asyncio.get_running_loop().create_future()
await self._ops.put(
_SessionTurn(prompt=prompt, on_content_delta=on_content_delta, future=future)
_SessionTurn(
prompt=prompt,
on_content_delta=on_content_delta,
future=future,
tool_names=tool_names,
)
)
return await future
@@ -249,7 +257,10 @@ class ClaudeCodeProvider(LLMProvider):
stream = sdk.query(prompt=_sdk_prompt(_prompt_input(conversation)), options=options)
try:
return await _consume_messages(
stream, on_content_delta=on_content_delta, label=_LABEL
stream,
on_content_delta=on_content_delta,
label=_LABEL,
tool_names=_offered_tool_names(tools),
)
finally:
close = getattr(stream, "aclose", None)
@@ -294,7 +305,9 @@ class ClaudeCodeProvider(LLMProvider):
)
prompt = _prompt_input(_incremental_messages(session, conversation))
session.messages = deepcopy(conversation)
response = await session.run_turn(prompt, on_content_delta)
response = await session.run_turn(
prompt, on_content_delta, _offered_tool_names(tools)
)
session.last_response = response.content or ""
return response
except BaseException:
@@ -543,6 +556,17 @@ def _build_options(
)
def _offered_tool_names(tools: list[dict[str, Any]] | None) -> frozenset[str]:
names: set[str] = set()
for schema in tools or []:
function = schema.get("function") if isinstance(schema, dict) else None
if isinstance(function, dict):
name = str(function.get("name") or "").strip()
if name:
names.add(name)
return frozenset(names)
def _build_tool_options(sdk: ModuleType, tools: list[dict[str, Any]] | None) -> dict[str, Any]:
sdk_tools: list[Any] = []
allowed: list[str] = []

View File

@@ -6,7 +6,7 @@ translates prompts, streamed messages and DeepTutor-owned MCP tool calls.
from __future__ import annotations
from collections.abc import Awaitable, Callable
from collections.abc import Awaitable, Callable, Collection
import logging
from typing import Any
@@ -23,10 +23,15 @@ async def _consume_messages(
on_content_delta: Callable[[str], Awaitable[None]] | None,
interrupt: Callable[[], Awaitable[None]] | None = None,
label: str = "CodeBuddy",
tool_names: Collection[str] | None = None,
) -> LLMResponse:
tracked = _SDKResultMessages(messages)
response = await _consume_sdk_messages(
tracked, on_content_delta=on_content_delta, interrupt=interrupt, label=label
tracked,
on_content_delta=on_content_delta,
interrupt=interrupt,
label=label,
tool_names=tool_names,
)
response.usage = tracked.usage
return response
@@ -38,6 +43,7 @@ async def _consume_sdk_messages(
on_content_delta: Callable[[str], Awaitable[None]] | None,
interrupt: Callable[[], Awaitable[None]] | None = None,
label: str = "CodeBuddy",
tool_names: Collection[str] | None = None,
) -> LLMResponse:
chunks: list[str] = []
pending_result_text = ""
@@ -53,7 +59,7 @@ async def _consume_sdk_messages(
continue
rejected_tool_errors.extend(_tool_result_errors(message))
tool_calls = _assistant_tool_calls(message)
tool_calls = _assistant_tool_calls(message, tool_names)
text = _assistant_text(message)
if text:
chunks.append(text)
@@ -152,7 +158,9 @@ def _result_usage(message: Any) -> dict[str, int]:
}
def _assistant_tool_calls(message: Any) -> list[ToolCallRequest]:
def _assistant_tool_calls(
message: Any, tool_names: Collection[str] | None = None
) -> list[ToolCallRequest]:
content = getattr(message, "content", None)
if content is None and isinstance(message, dict):
content = message.get("content")
@@ -173,9 +181,12 @@ def _assistant_tool_calls(message: Any) -> list[ToolCallRequest]:
arguments = getattr(block, "input", None)
if block_type not in {"tool_use", "tooluse"} and not block_type.endswith("tooluseblock"):
continue
if not name.startswith(_MCP_TOOL_PREFIX):
if name.startswith(_MCP_TOOL_PREFIX):
tool_name = name[len(_MCP_TOOL_PREFIX) :]
elif tool_names and name in tool_names:
tool_name = name
else:
continue
tool_name = name[len(_MCP_TOOL_PREFIX) :]
if not tool_name:
continue
calls.append(

View File

@@ -270,6 +270,68 @@ async def test_session_tool_call_drains_without_interrupt_and_sends_only_new_tai
assert client.disconnected
@pytest.mark.asyncio
async def test_bare_name_tool_call_matching_an_offered_tool_is_executed(monkeypatch) -> None:
_install_fake_sdk(monkeypatch)
FakeClient.script = [
[
FakeAssistantMessage([FakeToolUseBlock("toolu_1", "get_weather", {"city": "Hanoi"})]),
FakeResultMessage("max turns", is_error=True),
],
]
provider = ClaudeCodeProvider()
messages = [
{"role": "system", "content": "Use tools."},
{"role": "user", "content": "Weather in Hanoi?"},
]
response = await provider.chat(messages, tools=[WEATHER_TOOL], deeptutor_session_id="s1")
assert response.finish_reason == "tool_calls"
assert [(c.name, c.arguments) for c in response.tool_calls] == [
("get_weather", {"city": "Hanoi"})
]
await provider.aclose()
@pytest.mark.asyncio
async def test_bare_name_that_was_not_offered_is_still_ignored(monkeypatch) -> None:
_install_fake_sdk(monkeypatch)
FakeClient.script = [
[
FakeAssistantMessage([FakeToolUseBlock("toolu_1", "Bash", {"command": "ls"})]),
FakeResultMessage("max turns", is_error=True),
],
]
provider = ClaudeCodeProvider()
messages = [{"role": "user", "content": "Weather in Hanoi?"}]
response = await provider.chat(messages, tools=[WEATHER_TOOL], deeptutor_session_id="s1")
assert not response.tool_calls
assert response.finish_reason == "error"
await provider.aclose()
@pytest.mark.asyncio
async def test_error_result_without_text_names_the_subtype(monkeypatch) -> None:
_install_fake_sdk(monkeypatch)
result = FakeResultMessage(None, is_error=True)
result.result = None
result.subtype = "error_max_turns"
FakeClient.script = [[result]]
provider = ClaudeCodeProvider()
response = await provider.chat(
[{"role": "user", "content": "hi"}], tools=[WEATHER_TOOL], deeptutor_session_id="s1"
)
assert response.finish_reason == "error"
assert "Error calling Claude Code:" in response.content
assert "maximum number of turns (error_max_turns)" in response.content
await provider.aclose()
@pytest.mark.asyncio
async def test_missing_login_is_reported_as_error_response(monkeypatch) -> None:
async def fake_query(**kwargs):