claude-code
claude-code copied to clipboard
Compaction error: orphaned tool_result in messages array despite valid conversation history
Bug Description
When attempting to compact a conversation or send new messages, the API returns an error about an orphaned tool_result block, even though the conversation history file (.jsonl) contains valid tool_use/tool_result pairs.
Error Message
API Error: 400
{
"type":"error",
"error":{
"type":"invalid_request_error",
"message":"messages.46.content.1: unexpected \`tool_use_id\` found in \`tool_result\` blocks: toolu_013wP4cwYMUPJRzJUGbGK6Hk. Each \`tool_result\` block must have a corresponding \`tool_use\` block in the previous message."
},
"request_id":"req_011CWAQnVkF8hCQgQ6AVRi16"
}
Steps to Reproduce
- Have a long conversation with multiple MCP tool calls
- Update MCP server code (removed some tools, renamed others)
- Update
.claude/settings.local.jsonto reflect new tool names - Restart MCP server and reconnect
- Try to run
/compactor send a new message
Investigation Results
Analysis of the conversation file shows:
-
Session ID:
dfacfd99-2f7c-45e3-9ebb-063176dc459e -
Conversation file:
~/.claude/projects/-Users-songym-cursor-projects-grok-downloaded-video-local-organizer/dfacfd99-2f7c-45e3-9ebb-063176dc459e.jsonl -
File integrity: All
tool_resultblocks in the.jsonlfile have correspondingtool_useblocks - No orphaned tool_results found when analyzing the file sequentially
Root Cause Hypothesis
The .jsonl conversation history file is valid, but when Claude Code constructs the messages array to send to the Anthropic API (during compaction or new message), it appears to:
- Filter, transform, or drop some messages
- This process creates a mismatch where a
tool_resultis included but its correspondingtool_useis not - The API correctly rejects this malformed request
Context
- Claude Code version: 2.0.70
- Platform: macOS (Darwin 25.1.0)
- MCP server: Custom project MCP server that was recently updated
-
Settings file:
.claude/settings.local.jsonwas updated to remove old tool names
Expected Behavior
Either:
- Claude Code should ensure that when constructing the messages array, tool_use/tool_result pairs remain intact
- If a tool_use is filtered out, its corresponding tool_result should also be filtered out
- Or provide a way to repair/reset conversation state when this occurs
Workaround
Currently the only workaround is to start a new conversation, which loses all conversation context.
Additional Notes
This issue occurred after:
- Initial error: "Tool names must be unique" (caused by stale tool names in settings.local.json)
- Fixed settings.local.json to remove old tool names
- Restarted Claude Code
- Error changed to the orphaned tool_result error described above
The conversation is now stuck in an unrecoverable state.