Skip to content

[Bug]: Anthropic stream_chat: server-tool input_json_delta after a completed client tool_use block overwrites the finished client tool call's arguments #23459

Open

Description

@BlueX888

Bug Description

Anthropic.stream_chat (and astream_chat) in llama-index-llms-anthropic never reset cur_tool_call / cur_tool_json when a content block closes. In a streamed turn that contains a client tool_use block followed by a server-side tool block (web_search / MCP, enabled via the documented tools=[{"type": "web_search_20250305", ...}] or mcp_servers=[...] constructor args), the server tool's input_json_delta falls into the else branch of the delta handler: cur_tool_call still points at the finished client ToolUseBlock, so the guard for server-tool deltas does not fire, and the delta's partial_json is appended to the stale cur_tool_json and written back via cur_tool_call.input = argument_dict. The completed client tool call's arguments are silently replaced with the server tool's arguments, so an agent built on the streaming path executes the client tool with the wrong arguments. When the client tool has its own arguments, the concatenated JSON fails to parse and except ValueError: pass masks the corruption; when the client tool has no arguments (empty cur_tool_json), the replacement is silent.

Expected behaviour: a server tool's input delta must never mutate a client tool call. The code's own guard states this intent — base.py:562-566 (elif isinstance(r.delta, InputJSONDelta) and not isinstance(cur_tool_call, ToolUseBlock): # TODO: handle server-side tool calls) exists precisely so these deltas never touch a client tool call — and the non-streaming sibling _get_blocks_and_tool_calls_and_thinking (base.py:434-441) emits each ToolUseBlock.input exactly as the API delivered it. The Anthropic SDK's own streaming accumulator (src/anthropic/lib/streaming/_messages.py: TRACKS_TOOL_INPUT = (ToolUseBlock, ServerToolUseBlock), with per-block json_bufs[event.index]) routes each input_json_delta to the block whose event.index it carries, so a server tool's delta belongs to the server block only.

Root cause: llama-index-integrations/llms/llama-index-llms-anthropic/llama_index/llms/anthropic/base.py:612-614 (sync generator) and base.py:869-871 (async generator): on ContentBlockStopEvent the finished cur_tool_call is appended to cur_tool_calls, but neither cur_tool_call nor cur_tool_json is reset; ContentBlockStartEvent (base.py:608-611 / base.py:865-868) only reassigns them for ToolUseBlock, not for a server tool block, and the delta handler (base.py:567-579) has no content-block index tracking, so the server tool's InputJSONDelta is appended to the stale client block's JSON buffer.

Version

llama-index-llms-anthropic 0.12.0 (run-llama/llama_index commit fd4a517ad6490f0c8464a13fdf133760b696434a), Python 3.13.15, anthropic SDK 1.2.0, macOS 15 (arm64).

Steps to Reproduce

  1. Install llama-index-llms-anthropic==0.12.0 and anthropic.
  2. Run the script below. It mocks the event order the Messages API streams for a client tool_use block with no arguments followed by a server_tool_use block, so no API key is needed:
from unittest.mock import MagicMock

from anthropic.types import (
    ContentBlockStartEvent,
    ContentBlockStopEvent,
    ContentBlockDeltaEvent,
    InputJSONDelta,
    Message,
    RawMessageStartEvent,
    RawMessageDeltaEvent,
    MessageStopEvent,
    ToolUseBlock,
    ServerToolUseBlock,
)

from llama_index.core.base.llms.types import ChatMessage, MessageRole, ToolCallBlock
from llama_index.llms.anthropic import Anthropic

client_tool = ToolUseBlock(
    id="client-tool-1", name="get_current_time", input={}, type="tool_use"
)
server_tool = ServerToolUseBlock(
    id="srv-tool-1", name="web_search", input={}, type="server_tool_use"
)


def gen():
    yield MagicMock(
        spec=RawMessageStartEvent,
        message=MagicMock(spec=Message, usage=None),
    )
    yield ContentBlockStartEvent(
        index=0, content_block=client_tool, type="content_block_start"
    )
    yield ContentBlockStopEvent(index=0, type="content_block_stop")
    yield ContentBlockStartEvent(
        index=1, content_block=server_tool, type="content_block_start"
    )
    yield ContentBlockDeltaEvent(
        index=1,
        delta=InputJSONDelta(
            partial_json='{"query": "weather in London"}', type="input_json_delta"
        ),
        type="content_block_delta",
    )
    yield ContentBlockStopEvent(index=1, type="content_block_stop")
    yield MagicMock(spec=RawMessageDeltaEvent)
    yield MagicMock(spec=MessageStopEvent)


llm = Anthropic(model="claude-sonnet-4-5", api_key="sk-test")
mock_client = MagicMock()
mock_client.messages.create.return_value = gen()
llm._client = mock_client

chunks = list(
    llm.stream_chat(
        [
            ChatMessage(
                role=MessageRole.USER,
                content="What time is it? Search the web for the weather in London.",
            )
        ]
    )
)

final = None
for ch in chunks:
    for b in ch.message.blocks:
        if isinstance(b, ToolCallBlock):
            final = b

print("FINAL tool call in the streamed message:")
print(
    f"tool_call: id='{final.tool_call_id}' name='{final.tool_name}' "
    f"kwargs={final.tool_kwargs}"
)
if final.tool_kwargs == {}:
    print("RESULT: OK - client tool call untouched")
else:
    print(
        "RESULT: BUG - client tool call's kwargs were overwritten by server-tool input"
    )

Relevant Logs/Tracebacks

Output of the script above on pristine 0.12.0 — the finished client tool call get_current_time now carries the server tool's arguments:

FINAL tool call in the streamed message:
tool_call: id='client-tool-1' name='get_current_time' kwargs={'query': 'weather in London'}
RESULT: BUG - client tool call's kwargs were overwritten by server-tool input

Independent reproductions against the live API event order confirm the same, with two control cases:

FINAL tool calls in the streamed message:
tool_call: id='toolu_client_01' name='get_current_time' kwargs={'query': 'weather in London'}
RESULT: BUG - client tool call's kwargs were overwritten by server-tool input
CONTROL 1 (non-stream chat(), same turn): kwargs={} — sibling is correct
CONTROL 2 (client tool WITH args): kwargs={'timezone': 'UTC'} — ValueError masks corruption, as claimed

With the one-line fix (reset cur_tool_call = None; cur_tool_json = "" in the ContentBlockStopEvent branch of both generators), the same script prints kwargs={}, and the package's test suite passes both before and after the change (48 passed, 15 skipped).

Happy to open a PR with that approach (reset in the ContentBlockStopEvent branch of the sync and async generators in base.py) if that's welcome.

No existing issue or PR covers this; the only open PRs touching base.py (#23336, tool_choice for newer models, and #22359, instance-level thinking config) are unrelated to tool-call streaming state.

Activity

  1. BlueX888 commented on Oct 11, 2026

    @BlueX888
    Author

    Reproduced this. Root cause: llama-index-integrations/llms/llama-index-llms-anthropic/llama_index/llms/anthropic/base.py:612-614 appends the finished tool call on ContentBlockStopEvent but never resets cur_tool_call, so the following server tool block's InputJSONDelta falls into the client tool branch and its partial JSON overwrites the completed call's input (async twin at base.py:869-871).

    Minimal reproduction:

    python3 repro_anthropic_stream_stale_tool.py  # the mocked-stream script from the issue body
    

    Observed output:

    FINAL tool call in the streamed message:
    tool_call: id='client-tool-1' name='get_current_time' kwargs={'query': 'weather in London'}
    RESULT: BUG - client tool call's kwargs were overwritten by server-tool input
    

    Fix is ready on BlueX888:fix/prep-anthropic-stream-stale-tool-call-corrupted-by-server-tool-delta (commit 390b7da2). Resets cur_tool_call = None when the tool block stops in both generators, so the existing server-side tool guard (base.py:562-566) recognizes web_search/MCP input deltas and ignores them.
    Verified with: uv run -- pytest (in llama-index-integrations/llms/llama-index-llms-anthropic) — 50 passed, 15 skipped

    Happy to open the PR once you confirm the approach or assign this to me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions