GrepBoard/Manuals
605 manuals ·

Fix Claude API 400 "tool_use without tool_result"

·Tested on Python 3.13 · Claude Messages API official docs · 2026-10·Test scope ↓·6 steps

Fix the 400 "tool_use ids were found without tool_result blocks immediately after": the message pairing rules, and /rewind recovery in Claude Code.

text
API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"messages.12: `tool_use` ids were found without `tool_result` blocks immediately after: toolu_01..., toolu_01.... Each `tool_use` block must have a corresponding `tool_result` block in the next message."},"request_id":"req_..."}

Claude answered with a tool call (tool_use), and the next message you sent did not carry the result (tool_result) for it. The log above is from issue anthropics/claude-code#7796, with the ids trimmed. messages.12 appears to point at the offending message. The docs do not say whether the number is zero-based or which message it names.

[1] Decide whether you build the request yourself or a tool does. If a tool such as Claude Code keeps printing this error, go to step 6. If you assemble the messages array, follow steps 2 to 5.

[2] The official docs set three rules.

  • The tool_result must be in the user message immediately after the assistant message with the tool_use. No other message may sit between them.
  • In that user message, tool_result blocks must come first in the content array. Any text goes after them.
  • If the same assistant turn also called a server tool (server_tool_use) that has no result block yet, the user message must contain only tool_result blocks. Adding text after them fails with a 400.

For this exact error, the docs tell you to check the formatting of your tool results first.

[3] Count the tool calls in that turn. If one response holds two tool_use blocks, the next user message must hold two tool_result blocks, each tool_use_id equal to the matching id. Returning one result and dropping the rest is a typical shape of this bug.

[4] Check the array before you send it. This script never calls the API; it only looks at the pairs in a JSON file. It is a home-made check of the rules above, not a copy of the API's validation. It exits with code 1 when it finds any problem, so you can put it in front of the send call or in CI. It looks for missing results, text before results, a next message that is not a user message, duplicate tool_use ids, a tool_result with no matching tool_use, and text after an open server tool. It does not check the content format of a result or the consistency of the earlier conversation.

check_pairs.py
import json, sys msgs = json.load(open(sys.argv[1]))bad = 0seen = set()for i, m in enumerate(msgs):    if m["role"] != "assistant" or isinstance(m["content"], str):        continue    blocks = m["content"]    ids = [b["id"] for b in blocks if b["type"] == "tool_use"]    if not ids:        continue    for t in ids:        if t in seen:            print(f"messages.{i}: duplicate tool_use id {t}"); bad += 1        seen.add(t)    nxt_msg = msgs[i + 1] if i + 1 < len(msgs) else {"role": "user", "content": []}    nxt = nxt_msg["content"]    if nxt_msg["role"] != "user":        print(f"messages.{i + 1}: next message is not a user message"); bad += 1        continue    types = [b["type"] for b in nxt] if isinstance(nxt, list) else []    done = {b["tool_use_id"] for b in nxt if b["type"] == "tool_result"} if types else set()    if set(ids) - done:        print(f"messages.{i}: no tool_result in next message for {sorted(set(ids) - done)}"); bad += 1    elif types[: len(done)] != ["tool_result"] * len(done):        print(f"messages.{i + 1}: text comes before tool_result"); bad += 1    elif done - set(ids):        print(f"messages.{i + 1}: tool_result without matching tool_use {sorted(done - set(ids))}"); bad += 1    server = {b["id"] for b in blocks if b["type"] == "server_tool_use"}    answered = {b.get("tool_use_id") for b in blocks if b["type"].endswith("_tool_result")}    if server - answered and len(types) != len(done):        print(f"messages.{i + 1}: server tool still open, so only tool_result blocks may follow"); bad += 1print("" if bad else "OK: every tool_use has its tool_result", end="" if bad else "\n")sys.exit(1 if bad else 0)

Run on a sample with two deliberate breaks (one of two tool results missing, text placed before a tool_result) and on the fixed sample:

console
$ python check_pairs.py broken.json; echo "exit=$?"messages.1: no tool_result in next message for ['toolu_B']messages.6: text comes before tool_resultexit=1$ python check_pairs.py fixed.json; echo "exit=$?"OK: every tool_use has its tool_resultexit=0

[5] Fix it. Even when the tool failed or timed out, still return a result block, and flag the failure with is_error:

json
{"type": "tool_result", "tool_use_id": "toolu_...", "content": "ConnectionError: the weather service API is not available (HTTP 500)", "is_error": true}

If writing the agent loop by hand is a burden, the docs point to the SDK's Tool Runner, which handles the call format, result assembly, and retries.

[6] If Claude Code repeats this error, its stored conversation is out of step. The official error reference groups the close variants in one entry and points to /rewind:

text
API Error: 400 due to tool use concurrency issues. Run /rewind to recover the conversation.API Error: 400 orphaned tool_result in conversation history. Run /rewind to recover the conversation.API Error: 400 duplicate tool_use ID in conversation history. Run /rewind to recover the conversation.
  • On Opus 4.7 or 4.8, run claude update first. According to the docs, versions before v2.1.156 can hit this error during normal tool use, and /rewind does not clear it.
  • Otherwise run /rewind, or press Esc twice, to go back to a checkpoint before the broken turn and continue from there.

For a tool_use cut off by max_tokens, see Check stop_reason to Tell If a Claude Response Was Cut Off. Other Claude Code error messages are in Fix common Claude Code errors by message.

#claude#tool-use#claude-code#troubleshooting