API Error: orphaned tool_result blocks after context truncation
Resolved 💬 3 comments Opened Dec 14, 2025 by ksawaneh Closed Dec 18, 2025
Bug Description
Getting a 400 error from the Claude API due to orphaned tool_result blocks in the conversation history:
API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"messages.12.content.4: unexpected `tool_use_id` found in `tool_result` blocks: toolu_01NTC5Dcxuc9LdQFXHLeUMW7. Each `tool_result` block must have a corresponding `tool_use` block in the previous message."},"request_id":"req_011CW6srrMDmuwnnoYQSVLUU"}
Root Cause
This appears to happen when context truncation or summarization removes a tool_use block from an assistant message, but the corresponding tool_result block in the following user message is preserved. The Claude API then rejects the request because the tool_use_id reference is dangling.
Suggested Fix
Add a sanitization function that runs before every API call to:
- Collect all
tool_use_idvalues fromtool_useblocks in assistant messages - Remove any
tool_resultblocks from user messages whosetool_use_iddoesn't have a matchingtool_useblock in the immediately preceding assistant message
Environment
- Claude Code CLI
- Error occurs during normal conversation flow after extended usage
This issue has 3 comments on GitHub. Read the full discussion on GitHub ↗