Claude Tool Errors: Repair the tool_result Contract

The first Claude request succeeds. Your application receives two tool calls, one downstream service fails, and the continuation receives a 400 response. The incident looks like a model or gateway outage until somebody inspects the actual message array. The application has replaced a structured failure with a friendly sentence and accidentally left a tool call unanswered.

This article reviews an illustrative broken integration, repairs its continuation contract, and defines the evidence needed before trying the same workflow through an API relay. The tools, identifiers, and customer records below are synthetic. No production incident, live request, or performance result is being reported.

The scope is ordinary, application-defined client tools in Claude's Messages API. Before a Treerouter pilot, confirm that your account and selected route support the required native message blocks and error behavior. A successful text request does not establish that support. The Claude gateway purchasing guide provides a useful place to record the exact model, protocol, and account configuration.

Exhibit A: a plausible continuation that is broken

Imagine a support assistant comparing an order's delivery status with its return eligibility. Claude returns two calls. The order lookup succeeds, while the policy service times out. A developer tries to be helpful by adding an explanation before the surviving result:

{
  "role": "user",
  "content": [
    {"type": "text", "text": "The policy service failed; use what we have."},
    {"type": "tool_result", "tool_use_id": "call_order_new",
     "content": "Order is in transit."}
  ]
}

Assume the actual calls had IDs call_order and call_policy. Three separate mistakes are visible: text precedes the result, the surviving result has a rewritten identifier, and the failed call has disappeared. Fixing only the timeout will leave the continuation malformed.

The official result-handling contract requires a user message directly after the assistant tool-call message, matching tool_use_id values, and result blocks before ordinary text. Execution failures can be represented with is_error: true. For this review, use a results-only continuation; it makes the boundary simpler to inspect.

Do not infer execution from the presence of a tool call. As Anthropic's execution overview explains, application-defined tools run in your application. Claude receives the definition and returned output, not your implementation. The application therefore owns the difference between “requested,” “started,” “completed,” and “failed.”

Review comment 1: preserve the assistant evidence

Start with the response that requested the work. Save its content blocks as received, using the SDK's supported serialization when necessary, then append that assistant content to history. Avoid rebuilding an assistant message from the tool names you remember. Doing so makes it easy to discard a second call, supporting text, or a block that a newer model needs preserved.

The subsequent user message belongs to that exact assistant response. Maintain a mapping from call ID to execution outcome. Names are useful for dispatch, but they are insufficient for correlation: the model can call the same lookup twice with different inputs. An order lookup for one record must not accidentally satisfy another lookup merely because the names match.

During review, compare three artifacts: the raw response, your executor's outcome map, and the serialized continuation leaving the application. If each looks correct separately, compare them together. Many failures occur in a serializer or middleware layer after the executor has produced the right answer.

A harness migration can introduce precisely this seam. The agent harness integration guide is relevant when the same loop originally spoke another provider's protocol. Review how that adapter maps results instead of assuming its generic “tool message” abstraction retains Claude's structure.

Review comment 2: failed work still needs an outcome

A failed lookup is a result of executing a requested operation. It is not permission to erase that request from history. If two calls were requested, return two outcomes, even when one is an application failure or was intentionally skipped.

The parallel-tool documentation specifies one result per call, returned together in the next user message. It also distinguishes scheduling from serialization: your application chooses concurrent or sequential execution. A skipped operation can receive an error result explaining why it did not run.

That distinction matters for dependent work. Suppose a write fails and the application suppresses a subsequent notification. An honest result says the notification was not executed because the preceding operation failed. It must not claim that the notification service itself rejected the message. Precision gives the model a useful basis for its next response and gives operators a truthful incident record.

For the illustrative lookup, useful failure content would say that the policy service timed out, no eligibility decision was obtained, and the application cannot infer eligibility from delivery status. Avoid returning a raw exception containing credentials, private URLs, or unrelated customer data. The model needs the actionable outcome, while detailed diagnostics can remain in your secured operational records.

Review comment 3: distinguish three kinds of failure

Reviewers should label the failing boundary before recommending a retry:

BoundaryEvidenceAppropriate next action
Messages request rejectedHTTP error and provider error bodyRepair or investigate the request before replaying it
Client tool execution failedValid tool request, failed application operationReturn a correlated error result and apply application policy
Operation outcome uncertainTimeout after a potentially completed writeReconcile business state before attempting the write again

The Claude API error reference documents HTTP error categories and request identifiers. Record the actual error type and message; a status code alone does not identify the broken field. Conversely, a valid tool_result with is_error is conversation content reporting your tool's outcome, not an HTTP error from the model API.

For uncertain writes, an identifier supplied by the model is not automatically a business idempotency key. Your application should own deduplication and reconciliation. The discussion of user operations versus network attempts in preventing duplicate API requests offers relevant background, although its example application uses a different model.

A small offline repair fixture

This Python example constructs the continuation from recorded outcomes and rejects missing, foreign, or duplicate call IDs. It performs no network requests and requires no endpoint, model name, or API key. The IDs are deliberately synthetic fixture values.

from copy import deepcopy


def build_results(assistant, outcomes):
    if assistant.get("role") != "assistant":
        raise ValueError("Expected an assistant message")
    calls = [b for b in assistant["content"] if b["type"] == "tool_use"]
    ids = [b["id"] for b in calls]
    if not ids or len(ids) != len(set(ids)):
        raise ValueError("Missing calls or duplicate call IDs")
    if set(outcomes) != set(ids):
        raise ValueError("Every call needs exactly one recorded outcome")
    blocks = []
    for call in calls:
        outcome = outcomes[call["id"]]
        if type(outcome["ok"]) is not bool:
            raise ValueError("Outcome ok must be boolean")
        if not isinstance(outcome["text"], str):
            raise ValueError("This fixture accepts text results only")
        blocks.append({
            "type": "tool_result",
            "tool_use_id": call["id"],
            "content": outcome["text"],
            "is_error": not outcome["ok"],
        })
    return deepcopy(assistant), {"role": "user", "content": blocks}


assistant = {"role": "assistant", "content": [
    {"type": "tool_use", "id": "call_order",
     "name": "lookup_order", "input": {"order_id": "DEMO-1"}},
    {"type": "tool_use", "id": "call_policy",
     "name": "lookup_policy", "input": {"order_id": "DEMO-1"}},
]}
outcomes = {
    "call_order": {"ok": True, "text": "Order is in transit."},
    "call_policy": {"ok": False, "text": "Policy lookup timed out; eligibility unknown."},
}
original, reply = build_results(assistant, outcomes)
assert original == assistant and original is not assistant
assert [b["tool_use_id"] for b in reply["content"]] == ["call_order", "call_policy"]
assert reply["content"][1]["is_error"] is True
assert all(b["type"] == "tool_result" for b in reply["content"])
for bad in ({"call_order": outcomes["call_order"]},
            {**outcomes, "foreign_id": {"ok": True, "text": "Wrong call"}}):
    try:
        build_results(assistant, bad)
    except ValueError:
        pass
    else:
        raise AssertionError("Invalid correlation was accepted")
print("offline continuation fixture passed")

The fixture intentionally handles only text results for ordinary user-defined tools. It does not validate tool input schemas, execute operations, assemble streamed input, implement persistence, or handle specialized computer/browser toolset fields. It also does not prove that a gateway accepts the resulting body. Its purpose is to make a narrow invariant executable before integration testing.

Preserving call order in this output is an application choice that makes reviews easier. Correlation depends on IDs, and scheduling can differ. If your executor finishes the policy lookup first, store that outcome under its ID and let the message builder assemble the final group only after every requested call has a recorded disposition.

Review comment 4: make correction possible without promising it

An error description should separate a correctable input problem from a dependency outage. “Date must use YYYY-MM-DD” gives a different next step from “policy service unavailable.” A generic “tool failed” forces the next model turn to guess whether different arguments would help.

The tool-definition guide explains the role of names, descriptions, and input schemas. Use those definitions to establish what a tool does, then use runtime errors to describe what happened on this invocation. Do not compensate for an ambiguous tool contract by writing an increasingly long error message after every failure.

An error result allows the conversation to continue; it does not guarantee a successful retry or authorize a new operation. Define a finite attempt budget in application code. Decide whether the assistant may retry a read, must request missing information, or should stop and explain an unavailable dependency. Review these decisions against the business operation, especially when correcting an argument could change the target customer or account.

If the model response was cut off before a complete call arrived, do not feed partial arguments into this path. That is a different input condition. The truncated-response investigation guide helps separate incomplete generation from a completed call whose execution subsequently failed.

The replay decision reviewers often miss

Suppose the executor completed both lookups, built the correct result message, and then lost the connection while sending the continuation. Restarting the entire application turn would perform the lookups again. For this example they are reads, but the same control flow may later dispatch writes. A code review should identify which stage is being retried rather than approving a single generic retry wrapper around the whole loop.

Keep an execution ledger separate from conversation history. The ledger can record the application operation ID, assistant response ID when available, tool call ID, execution state, and the sanitized outcome that should be returned. Conversation history describes what the model has seen; the ledger describes what your system has done. They serve different purposes and should not silently overwrite each other.

After a restart, inspect the ledger before rerunning a tool. If a result was durably recorded, reuse that result for the same pending continuation. If execution started but completion was not recorded, reconcile the operation with its owning service. If nothing started, normal dispatch remains possible. These are application design recommendations, not guarantees supplied by the model API.

Finally, keep an attempted model continuation distinct from an accepted one. A failed request should not cause your history builder to append another copy of the same assistant response on every retry. Use the pending turn as a stable unit of work, and commit the next model response once. This makes the incident reproducible: the reviewer can see one requested operation, its execution outcomes, and the attempts to deliver them.

The acceptance evidence for a route

A reviewable pilot contains more than a successful final sentence. Use a read-only tool and inject a deterministic failure in your own executor. Retain the requested IDs, the returned outcomes, the outgoing continuation, and the next model response. Confirm that the assistant distinguishes the available information from the unavailable information rather than presenting both as established facts.

Then exercise a two-call turn where only one operation fails. The important observation is whether both IDs survive through your adapter and whether the error flag reaches the continuation unchanged. Add a malformed local fixture to prove your validator rejects a missing result before it sends a request. Keep these artifacts scrubbed of secrets and real customer records.

These are proposed acceptance cases, not reported Treerouter test results. The methodology in model API acceptance testing can help organize the evidence, while the actual native Claude contract remains the authority for this workflow.

For a Treerouter evaluation, first confirm account and route support for native client-tool continuation, including tool_use, tool_result, and is_error. If support is confirmed, register and run one controlled read-only round trip before connecting business operations. A useful first success is a complete, correctly correlated conversation, including an honest failure response when the tool cannot finish.

Learn more: Treerouter.