← Blog

Anthropic Tool Result Order Validation Before the Next Message

Parminder Singh
Parminder Singh··6 min read
Summarize with AI

Anthropic requires client tool results to appear in the user message immediately after the assistant tool-use turn. Every tool_result block must precede any text in that message and point to the matching tool_use ID. This guide defines an order validator for single and parallel calls, unresolved server tools, retries, audit records, and destructive fixtures.

Platform & Architectureai-securityllm-securityagentic-aipolicy-enforcementarchitectureaudit
Anthropic Tool Result Order Validation Before the Next Message

Anthropic's Messages API places client tool results inside a user message. That message must immediately follow the assistant turn containing the corresponding tool_use blocks, and every tool_result must appear before any text in its content array. A serializer that gets either order wrong can turn a valid tool execution into a rejected model request.

I want the adapter to validate the conversation as a sequence, rather than checking each JSON object in isolation. The defect usually sits in the gap between two messages.

TL;DR

  • Put the user tool-result message immediately after the assistant turn that requested the tools.
  • Return one tool_result for every client tool_use, matched by the exact tool_use_id.
  • Place all tool-result blocks before any text in that user message. Parallel results belong together.
  • Reject missing, duplicated, unknown, or misplaced results before sending the next Messages request.

Adjacency is part of the Anthropic contract

Anthropic's tool-call handling guide gives the sequence explicitly. Keep the earlier history. Copy Claude's response content unchanged into the assistant turn. The next user message contains one tool_result for each client tool_use.

This is a conversation-level invariant. Validating that the current object has role: user and a content array misses the message inserted between the two turns. A progress note, tracing annotation, or copied user sentence in its own message breaks adjacency even when every result block is otherwise well formed.

Validate the previous assistant message and the next user message as one pair. Record their positions, the assistant response ID if the application retains it, and a digest of both content arrays. The wider Anthropic API gateway pattern supplies the routed request path around that pair.

Result blocks come before text

The same Anthropic guide requires every tool_result block to come first in the user message's content array. Text can follow after all client results. Text placed before a result violates the documented format.

The validator can implement this without guessing intent. Scan the user content from left to right. Once the first non-result block appears, reject any later tool_result. Preserve the offending indices in the validation record. A compact result such as results_after_text: [2] gives an engineer the exact location without copying sensitive tool output into an alert.

Keep ordering separate from content authorization. The text after the result blocks may still require route policy, and each result may carry regulated data. This gate answers one narrow question: does the message preserve Anthropic's required block order?

I would block any adapter that silently sorts the array after application code builds it. Silent sorting hides the producer defect and can detach a human explanation from the result it was meant to describe.

Every client call needs one matched result

A tool_use block carries an id. The corresponding tool_result uses that exact value as tool_use_id. Build the expected set from the unchanged assistant content, then build the observed set from the immediately following user message.

Reject these cases before dispatch:

  • an expected client tool-use ID has no result
  • a result points to an ID absent from the assistant turn
  • the same tool_use_id appears twice
  • a result uses the tool name or array position as its join key
  • the assistant content was normalized and lost a tool-use block

The Anthropic handle-tool-calls reference says to return a result even when the tool failed. A failed or invalid call belongs in a tool_result with is_error: true; omitting it leaves the requested call unresolved.

This is provider correlation, not proof of local execution. The AI response tool-call validation guide owns authorization and executor checks before an application acts.

Parallel calls return as one result message

Claude may produce several tool_use blocks in one assistant turn. Anthropic's parallel tool use guide says the application may execute them concurrently, sequentially, or in a mixed strategy. The API ordering rule stays fixed: return one result per call, all together in the next user message, with every result before any text.

Completion order should therefore stay out of the join. Suppose calls toolu_A and toolu_B run in parallel and B finishes first. The application can assemble both results only after its chosen completion policy has settled. It then matches by ID. If sequential execution stops after A fails, Anthropic says B still needs a result with is_error: true and a brief explanation.

A useful ledger has one assistant-turn row and child rows for expected calls. Each child carries the tool-use ID, original output index, execution disposition, result index, error flag, and content digest. The user-message row closes only when its expected and observed ID sets match.

Unresolved server tools change the allowed shape

Anthropic documents an edge case where an assistant turn contains a client tool_use and a server_tool_use whose result has yet to arrive. In that state, the next user message should contain only the client tool_result blocks. Text after those results can end the turn early, and a direct server-tool call may then fail with a 400 response naming the unresolved server tool.

The validator needs to classify assistant blocks before applying the ordinary "results, then optional text" rule. If an unresolved server-tool block is present, set the allowed user-message shape to results only. Keep the same tools array on the next request, as Anthropic directs.

Leave the server call to the provider's response lifecycle, which supplies its result block. The application's client results answer only the client calls it owns.

Anthropic's stop-reason guidance should drive the state transition after the next response. A generic chat-message validator lacks enough state for this branch.

Validation belongs before retry scheduling

A 400 caused by message order is deterministic for the same request body. Retrying identical bytes wastes capacity and obscures the producer defect. Run sequence validation before dispatch and classify failures as local contract errors. Use distinct reason codes for broken adjacency, text placement, and ID coverage.

If a connection fails after dispatch, retain the exact request digest and attempt record. A retry may be appropriate under the route's operation policy, but the serializer should produce the same validated message pair. Rebuilding from mutable in-memory state can reorder completed parallel results or insert another message.

Persist the validated request artifact or an immutable assembly manifest before transport. The manifest should identify the prior assistant turn, expected tool-use IDs, user-message index, ordered block types, observed result IDs, and validator version. The AI audit log schema provides identity, route, policy, timestamp, and outcome fields around that artifact.

A destructive fixture should move one block at a time

Start with an assistant turn containing two client tool_use blocks. Build the next user message with two matching results followed by one short text block. The validator should accept the pair. On a narrow terminal view, the block-type line should read tool_result, tool_result, text.

Then mutate one property per case. Insert a user message between the assistant turn and the results. Move the text block to index zero. Delete one result, duplicate another, substitute an unknown ID, and split parallel results across two user messages. Add a failed execution represented by is_error: true and confirm it still satisfies the one-result requirement.

Finally, add an unresolved server-tool block to the assistant turn and leave text after the client results. That case should fail under the stricter results-only branch. Preserve the validator reason and the observed block sequence for every fixture. No case should reach the provider mock after a local rejection.

DeepInspect

DeepInspect can validate Anthropic message ordering on authenticated user or agent HTTP traffic deliberately routed through its proxy. It can compare the assistant tool-use turn with the next user message, enforce adjacency and result-first ordering, check exact tool-use ID coverage, and record the decision before the request reaches Anthropic.

The application owns tool execution, parallel scheduling, local retries, and construction of the conversation history. Provider traffic that bypasses the proxy remains outside DeepInspect's evidence. The routed decision covers the Messages request observed at the HTTP boundary.

Book a technical deep dive at deepinspect.ai.

Frequently asked questions

Must tool results immediately follow the assistant tool-use message?

Yes. Anthropic requires the user message containing client tool results to immediately follow the assistant message containing the corresponding tool-use blocks. An intervening message breaks the documented conversation sequence.

Can text appear in the same user message as tool results?

Text can follow all client tool_result blocks in the ordinary client-tool flow. Its valid position is after the complete result group. When the assistant turn also has an unresolved server tool, Anthropic documents a stricter next message containing only client tool-result blocks.

Does result order have to match tool-use array order?

Anthropic requires exact matching through tool_use_id and requires all results together in the next user message. The application chooses the execution order for parallel calls. Preserve original positions for evidence, but use IDs for the join rather than completion order.

What should the application send when a client tool fails?

Send a tool_result for the requested call with the exact tool_use_id and set is_error to true. A brief error explanation can go in the result content. Omitting the result leaves the call unresolved.