Skip to content

unexpected tool_use_id found in tool_result blocks #1644

Closed

Description

@aheritier

Describe the bug

Since few hours my Anthropic models are rejecting my requests with:

all models failed: error receiving from stream: POST "https://api.anthropic.com/v1/messages": 400 Bad Request (Request-ID: req_011CXwUGAoEeBVooyRv5365i)
{"type":"error","error":{"type":"invalid_request_error","message":"messages.298.content.1: unexpected `tool_use_id` found in `tool_result` blocks:
toolu_01VaSNuJZRTJH227epge8S24. Each `tool_result` block must have a corresponding `tool_use` block in the previous message."},"request_id":"req_011CXwUGAoEeBVooyRv5365i"}

Version affected

cagent version v1.20.6
Commit: Homebrew

How To Reproduce

Not sure. My agents definition didn't change when the problem started to occur. I can share a team definition if useful.

Expectation

No error, or a better management of the error, right now cagent is not working anymore.

Screenshots

N/A

OS and Terminal type

macOS + Ghostty

Additional context

N/A

Activity

  1. rumpl commented on Feb 8, 2026

    @rumpl
    Member

    Thanks!

    What would be useful for us is to get the session in which you got this error. Or at least screenshots of what the agent was doing before you got the error

  2. aheritier commented on Feb 9, 2026

    @aheritier
    CollaboratorAuthor

    Hi @rumpl

    My session ID is 3f8f21c7-07b5-4b72-bc73-242be25d13fb

    I restored it

    Image
  3. aheritier commented on Feb 9, 2026

    @aheritier
    CollaboratorAuthor

    Claude is considering that the context got corrupted:

      Issue 1: API tool_use_id Mismatch (Red Error)
    
      all models failed: error receiving from stream: POST "https://api.anthropic.com/v1/messages": 400 Bad Request
      unexpected 'tool_use_id' found in 'tool_result' blocks: toolu_01VaSNuJZRTJH227epge8S24.
      Each 'tool_result' block must have a corresponding 'tool_use' block in the previous message.
    
      This is a conversation state corruption error. It means cagent is sending a tool_result message back to the API that references a tool_use_id which no longer exists in the conversation history. This typically happens when:
    
      1. Context window compression truncated earlier messages that contained the original tool_use call, but cagent still tries to send its result
      2. A retry/resume after a failure caused the conversation to get out of sync — the agent loops "Let's resume" / "Let's fix the compilation issue" repeatedly, suggesting it kept hitting errors and retrying
    
      The fact that the same toolu_01VaSNuJZRTJH227epge8S24 appears in all three red errors confirms it's stuck in a loop trying to send the same orphaned tool result.
    

    It probably makes sense as new sessions are ok.

  4. aheritier commented on Feb 10, 2026

    @aheritier
    CollaboratorAuthor

    Same today after a (too long) working session

    Image
  5. rumpl commented on Feb 10, 2026

    @rumpl
    Member

    @aheritier I attempted a fix here: #1680

    Since this tends to happen to you a lot, would you mind giving this PR a try for a day or two?

  6. aheritier commented on Feb 10, 2026

    @aheritier
    CollaboratorAuthor

    Thanks a lot
    I will let you know

    > cagent version                                                                                                                              
    cagent version dev
    Commit: fac5c127e890eecb3b1bbef92ac58f667433507b
    
  7. aheritier commented on Feb 11, 2026

    @aheritier
    CollaboratorAuthor

    There's a new error (all models failed: error receiving from stream: received error while streaming: {"type":"error","error":{"details":null,"type":"overloaded_error","message":"Overloaded"},"request_id":"req_011CY268GtqRPEN4cuE6TX3L" }) but I don't think it's related to the previous one:

    Hmm, the commit went to `feat/1917-company-sorting-anomaly-filter` instead of the new `feat/1917-pattern-c-client-sort-filter` branch. Let me check the default branch and fix this.
    
    Wait, it seems the default branch was still set to the original. Let me check.
    Thoughts:
    The GitLab issues are 403 Forbidden - they're private. Let me try to find information about these issues through the project's local files, and also check the current branch state. Let me also look at the `but` skill for branch management, and search for any existing plans
    or documentation about issue 1917 and 1901.
    I can't access the GitLab issues directly (403). Let me look at the existing branches in the stack to understand the epic #1901 context. I can see there's already a stack:
    
    - feat/1908-company-detail-stats (root)
    - feat/1907-company-merge-action
    - feat/1906-sponsored-company...
    - feat/1904-virtual-scroll...
    - feat/1905-company-speaker...
    …
    
    The commit went to the right branch —  feat/1917-company-sorting-anomaly-filter  is the one that should receive the Pattern C refactor (the second branch was created as an anchor but the commits are being stacked correctly). Now the ADR:
    
    
    ✓ Shell  ls docs/adr/ 2>/dev/null | sort -V | tail -3
    
    
    all models failed: error receiving from stream: received error while streaming: {"type":"error","error":{"details":null,"type":"overloaded_error","message":"Overloaded"},"request_id":"req_011CY25zWmHtkwuWwMNVHNJF"        }
    
    
    
    ✎
    You have access to gitlab using glab CLI and the MCP
    
    
    Thinking [+]
    3. We need to commit the ADR and the plan files
    Let me check what was the last state and continue from there. The user's last message before this was a reminder about tools. Let me continue with the ADR and use glab/MCP appropriately.
    I should make a note to leverage the glab CLI and GitLab MCP tools for all GitLab operations going forward rather than relying on manual approaches.
    
    You're right — I should have used  glab  CLI and the GitLab MCP tools from the start instead of trying to  fetch  web URLs. Let me save that for future reference and continue with the ADR.
    
    
    ✓ Add Memory
    memory:
    For GitLab access: use `glab` CLI (e.g., `glab issue view 1917`) and GitLab MCP tools (search_repositories, get_file_contents, create_issue, create_merge_request, etc.). Do NOT use the `fetch` tool on GitLab web URLs — they return 403 on private projects.
    Memory added successfully with ID: 1770804110695214000
    ✓ List TODOs
    
    
    all models failed: error receiving from stream: received error while streaming: {"type":"error","error":{"details":null,"type":"overloaded_error","message":"Overloaded"},"request_id":"req_011CY268GtqRPEN4cuE6TX3L"     }
    
  8. aheritier commented on Feb 15, 2026

    @aheritier
    CollaboratorAuthor

    Deeper investigation findings

    We applied PR #1680 (virtual branch anthropic-tools) which enforces strict tool sequencing in the Anthropic converter, but the issue reproduced again on session ba1a47e6-7334-4cd3-8639-3f62c7c88692.

    Root cause

    The issue is not in the Anthropic message converter — it is upstream in Session.GetMessages() (pkg/session/session.go).

    GetMessages() iterates over all s.Messages items and includes every IsMessage() item regardless of which agent it belongs to. When sub-agent messages (e.g., from code-reviewer, git-agent) are present in the parent session, they get interleaved between the root agent's tool_use (transfer_task) and its corresponding tool_result.

    This creates two fatal problems for the Anthropic API:

    1. Sub-agent assistant messages with their own tool_calls appear between the root's tool_use and tool_result, breaking the required immediate sequencing
    2. Sub-agent tool_calls reference tool_use_ids whose tool_results only exist in the sub-session — creating orphaned tool_use blocks that the converter's pendingToolUseIDs tracking cannot reconcile

    Why sub-agent messages are in the parent session

    Commit 28bec8dd fixed the persistence side — PersistentRuntime.handleEvent now tracks subSessionDepth via AgentSwitchingEvent and skips persisting sub-agent streaming/message events to the parent store. However, sessions created before that fix have corrupted data already in SQLite that gets loaded on resume.

    Why PR #1680 didn't fully fix it

    PR #1680's convertMessages/convertBetaMessages added pendingToolUseIDs tracking. But when a sub-agent's assistant message with its own tool_calls is processed, it overwrites pendingToolUseIDs, causing the root's subsequent tool_result to be rejected as unmatched. The converter correctly enforces sequencing but can't fix messages that should never have been included.

    Fix

    Committed to the anthropic-tools virtual branch (40694d44): a 3-line filter in GetMessages() that skips any message whose AgentName is non-empty and doesn't match the current agent's name. This filters out sub-agent messages while preserving user messages (empty AgentName) and the current agent's own messages.

    agentName := a.Name()
    for i := startIndex; i < len(s.Messages); i++ {
        item := s.Messages[i]
        if item.IsMessage() {
            if item.Message.AgentName != "" && item.Message.AgentName != agentName {
                continue
            }
            messages = append(messages, item.Message.Message)
        }
    }

    This is a defense-in-depth fix that works regardless of whether the persistence bug (fixed in 28bec8d) is present, making it safe for both historical corrupted sessions and future sessions.

  9. aheritier commented on Feb 15, 2026

    @aheritier
    CollaboratorAuthor

    I am testing aheritier@94b9bf7

  10. aheritier commented on Feb 27, 2026

    @aheritier
    CollaboratorAuthor

    Without @rumpl 's fix I still get the issue @dgageot

    Image
  11. aheritier commented on Feb 28, 2026

    @aheritier
    CollaboratorAuthor

    I created #1880 which is including @rumpl PR #1680 but also #1644 (comment)

  12. aheritier commented on Mar 6, 2026

    @aheritier
    CollaboratorAuthor

    closing for now. To reopen if new occurrences are found

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