GrepBoard/매뉴얼
605 편 ·

Claude API 400 tool_result 없는 tool_use

·시험 환경 Python 3.13 · Claude Messages API 공식 문서 기준 · 2026-10·시험 범위 ↓·6 단계

tool_use ids were found without tool_result 400 이 날 때, 메시지 배열의 짝 맞춤 규칙과 Claude Code 의 /rewind 복구 방법입니다.

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 가 도구를 부르겠다고 한 답(tool_use)에 대해, 바로 다음 메시지에서 결과(tool_result)를 돌려주지 않았다는 뜻입니다. 이슈 anthropics/claude-code#7796 의 로그를 id 만 줄여 옮겼습니다. messages.12 는 문제가 된 메시지의 위치로 보입니다. 이 번호가 0부터 세는지, 어느 메시지를 가리키는지는 공식 문서에서 확인하지 못했습니다.

[1] 먼저 직접 만든 코드인지 Claude Code 같은 도구인지 가릅니다. 도구가 화면에 이 오류를 계속 내면 6단계로 갑니다. 직접 messages 배열을 만들고 있다면 2~5단계입니다.

[2] 공식 문서가 정한 규칙은 세 가지입니다.

  • tool_result 는 대응하는 tool_use 메시지 바로 다음 user 메시지에 있어야 합니다. 둘 사이에 다른 메시지를 끼울 수 없습니다.
  • 그 user 메시지에서 tool_result 블록이 content 배열의 맨 앞에 와야 합니다. 텍스트는 그 뒤에 둡니다.
  • 같은 assistant 턴이 아직 결과 블록이 없는 서버 도구(server_tool_use)도 불렀다면, user 메시지에는 tool_result 블록만 두고 텍스트를 붙이지 않습니다. 붙이면 400 이 납니다.

문서는 이 오류가 나면 도구 결과의 형식부터 확인하라고 안내합니다.

[3] 한 번에 도구 호출이 여러 개였는지 봅니다. 응답 하나에 tool_use 가 둘이면 user 메시지 하나에 tool_result 도 둘이어야 하고, 각각의 tool_use_id 가 tool_use 의 id 와 같아야 합니다. 하나만 돌려주고 나머지를 빠뜨리는 형태가 대표적입니다.

[4] 배열을 보내기 전에 검사합니다. 아래 스크립트는 API 를 부르지 않고 JSON 파일의 짝만 봅니다. 직접 만든 규칙 검사이며 API 의 검증을 그대로 옮긴 것은 아닙니다. 문제를 하나라도 찾으면 종료 코드 1 로 끝나므로 전송 직전이나 CI 에 끼울 수 있습니다. 짝 누락·텍스트 선행·다음 메시지가 user 가 아닌 경우·중복 tool_use id·짝 없는 tool_result·열린 서버 도구 뒤의 텍스트를 봅니다. tool_result 의 내용 형식이나 앞쪽 대화 전체의 일관성은 보지 않습니다.

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)

일부러 두 군데를 깨뜨린 샘플(도구 둘 중 하나의 결과 누락, 텍스트가 tool_result 앞에 옴)과 고친 샘플로 돌린 결과입니다.

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] 고칩니다. 도구가 실패했거나 시간이 초과돼도 결과 블록은 반드시 돌려줘야 합니다. 실패는 is_error 로 알립니다.

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

에이전트 루프를 직접 쓰기 번거롭다면 문서가 SDK 의 Tool Runner 를 권합니다. 호출 형식·결과 조립·재시도를 SDK 가 맡습니다.

[6] Claude Code 에서 이 오류가 반복되면 대화 기록이 어긋난 것입니다. 공식 오류 문서는 비슷한 변형을 한 항목으로 묶고 /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.
  • Opus 4.7 이나 4.8 을 쓴다면 먼저 claude update 를 실행합니다. 문서에 따르면 v2.1.156 보다 낮은 버전은 평소 도구 사용 중에도 이 오류가 나고, 그때는 /rewind 로 풀리지 않습니다.
  • 그 밖에는 /rewind 를 실행하거나 Esc 를 두 번 눌러, 어긋난 턴 이전의 체크포인트로 돌아가 이어 갑니다.

응답이 max_tokens 에서 잘려 tool_use 가 불완전한 경우는 stop_reason 으로 응답 잘림 확인하기, 다른 Claude Code 오류 문구는 Claude Code 오류 문구별 조치를 봅니다.

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