Your Agent Can't Recover Because Your Tool Errors Are Shaped Wrong
A tool call fails, and your agent stops, loops, or invents a result. The error was there the whole time.
An error that said everything and meant nothing
A team I was helping ran an agent that scheduled internal resources: rooms, equipment, a few shared test rigs. It worked in the demo and worked for a week, and then it started quietly refusing to finish jobs. The logs were full of errors, so on paper nothing was hidden. The problem was what the errors looked like by the time the model saw them.
A booking call would fail, and the tool handed back the raw thing it caught: a long requests traceback ending in a 409 Conflict, the body a blob of JSON with a code field three levels deep. The model received that as a wall of text, produced a polite sentence about being unable to complete the booking, and stopped. Sometimes it did worse. It read the conflict as a sign the slot was taken, invented a different time that was never confirmed, and reported the booking as done. The error was accurate. It was also useless to the one reader that mattered, because that reader was a language model, and nothing in the blob told it that a 409 here meant the slot needed a fresh availability check and a retry.
The fix was not a better model and not a retry loop. It was deciding, on purpose, what a failed tool call says to the model and where it says it. That decision is a contract, and once the team wrote it down the same model started recovering from the same failures.
Why the shape of the error decides the recovery
A model does not perceive your system. It does not see the exception class, the status code, or the log line. It sees the tokens you chose to put back into its context after the tool ran. So a tool error is not a log entry, it is a message to the model, and like any message its effect depends on how it is written.
This is not a soft claim about prompting style. A 2026 study, Same Error, Different Recovery, isolated the delivery problem by holding the error text fixed and varying only how it reached the model: where it was placed, whether guidance was attached, whether the failed exchange stayed in the history, how the turn was structured. Across thirteen models the next action changed with delivery alone. A new user turn that kept the failed exchange avoided a severe stopping failure that showed up when that exchange was removed, and on a tool benchmark the better delivery raised success on explicit errors by double digit points. Same information, different shape, different outcome.
That is the whole argument for a contract. If the way you hand back a failure can swing an agent between repairing it and abandoning it, then the handback is an interface you are already designing, whether you admit it or not. Most teams design it by accident, by passing through whatever the HTTP client threw. The accident is the bug. This is the same lesson as retrying on a clean context rather than the poisoned one: what you carry forward after a failure is a design choice, and the default choice is usually wrong.
The error contract: three fields the model can act on
The contract is small. Every failed tool call returns the same three things, always, in language aimed at the model and not at a dashboard.
The first is what failed, in plain terms tied to the action, not the transport. Not HTTPStatusError 409 but "the 2pm slot for room B is already booked." The second is why, as a category the agent can route on: transient, bad argument, not allowed, or terminal. The third is the next action, a concrete suggestion the model can turn into a tool call: "call check_availability for room B after 2pm, then book the first free slot." A raw stack trace has none of these. It has a cause buried in a format built for a human reading logs at 2am, which is not the reader you have.
from dataclasses import dataclass
from enum import Enum
class ErrorClass(str, Enum):
TRANSIENT = "transient" # wait and retry the same call
BAD_ARGUMENT = "bad_argument" # the model can repair the inputs
NOT_ALLOWED = "not_allowed" # policy or auth; the model cannot self-fix
TERMINAL = "terminal" # stop and report; retrying will not help
@dataclass
class ToolError:
what: str # "the 2pm slot for room B is already booked"
why: ErrorClass # the category the agent routes on
try_next: str # "check availability for room B after 2pm, then book"
# kept for logs and the orchestrator, NOT shown to the model verbatim:
raw: str = ""
The raw field matters for a reason worth stating. You still keep the traceback, the status code, and the body, because your on call engineer needs them and your traces need them. You just stop putting them in the model's context. The model gets what, why, and try_next. The orchestrator gets everything.
Classify, then shape: one path per failure class
The contract leans on classification, which is a job you may already do to decide how to recover from a failed tool call: map the raw failure to a category, then let the recovery logic fall out of it. The contract adds a second output to that same step. Classification decides what the orchestrator does. Shaping decides what the model is told. They share the switch statement.
The shaping is where care pays off. For a bad argument, the message is the correction and nothing else, the same discipline as distilling a failure into one corrective sentence instead of replaying the broken call. For a not allowed failure, the message says so plainly and offers no retry, because inviting the model to try again against a permission wall just burns steps. For a terminal failure, the message ends the line cleanly so the model reports rather than guesses.
def to_contract(tool: str, err: Exception) -> ToolError:
cls = classify(err) # your existing transient/bad-arg/auth/terminal switch
if cls is ErrorClass.BAD_ARGUMENT:
field, reason = explain_validation(err) # "start_time", "must be ISO 8601"
return ToolError(
what=f"{tool} rejected the input: {field} {reason}",
why=cls,
try_next=f"fix {field} ({reason}) and call {tool} again",
raw=repr(err),
)
if cls is ErrorClass.NOT_ALLOWED:
return ToolError(
what=f"{tool} is not permitted for this request",
why=cls,
try_next="do not retry; report that this action needs approval",
raw=repr(err),
)
if cls is ErrorClass.TRANSIENT:
return ToolError(
what=f"{tool} was temporarily unavailable",
why=cls,
try_next="the system will retry automatically; wait",
raw=repr(err),
)
return ToolError(what=f"{tool} failed and cannot be completed",
why=ErrorClass.TERMINAL,
try_next="stop and report the failure to the user",
raw=repr(err))
Notice that the transient case tells the model to wait, because the orchestrator, not the model, owns the backoff. You do not want the agent spending a reasoning step deciding whether to retry a 503; that is code's job, and leaving it to the model is how you get an agent hammering a dead endpoint. When retries on a class are exhausted, the honest move is to stop calling it, which is what a circuit breaker around the tool is for, and the contract then flips that tool's class to terminal so the model reports instead of waiting forever.
Deliver the error where the model will act on it
Shape is half of it. The other half is placement, and this is the part the delivery study makes concrete. An error folded into the same assistant turn as the failed call, or stripped out of the history entirely before the next turn, lands differently from the same error presented as a fresh turn that keeps the failed exchange visible. The models that stopped most often were the ones handed a history with the failed exchange removed, as if the failure never happened. Keeping the exchange and adding a new turn that carries the correction is what let them recover.
In practice that means the tool result goes back as a distinct, well marked message, with the failed call still in the transcript above it, and the try_next guidance attached rather than left implicit. You are not rewriting history to hide the failure. You are presenting the failure as the current state of the world and pointing at the next move.
def deliver(messages: list, call, error: ToolError) -> list:
# keep the failed call visible; do not strip it from history
messages.append({"role": "assistant", "content": None, "tool_calls": [call]})
# the result comes back as its own turn, shaped, with guidance attached
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": f"FAILED ({error.why.value}): {error.what}\nNext: {error.try_next}",
})
return messages
There is a bound to keep. Delivery improves recovery on failures the model can see and name, and it does far less for silent corruption, where the tool returned something plausible but wrong. The study found its clearest gains on explicit errors and little on quietly corrupted state, which is the next problem to worry about and not one placement solves.
Make silent failures loud
The dangerous failures are the ones that never reach the contract because nothing classified them as failures at all. A tool returns a 200 with an empty list, a write that matched no rows, a schema valid argument that was simply wrong. None of that raises an exception, so none of it becomes a ToolError, and the model reasons on top of a result that looks fine.
The cost here is measured, not hypothetical. In a 2026 study that re-scored thirty three thousand agent traces with a deterministic validator instead of a text match, injecting a single schema valid but wrong argument into the first tool call raised the error rate by twenty two points, and by more than forty where the corrupted call still executed cleanly. The call succeeded. The run failed. This is the same family as agents that fail silently while the tests stay green, and the contract only helps if you first turn these quiet wrongs into declared failures.
The move is to validate the result against the intent before you hand it back, and raise a BAD_ARGUMENT or TERMINAL contract when it does not match, so a silent wrong becomes a loud, shaped error. This is close to reading the changed state back before you believe the action is done: a result the tool calls success is a claim, and a claim that fails its check is an error the model deserves to see, written in the same three field shape as any other.
The parts that bite
A contract can mislead as confidently as a raw trace if the try_next is wrong. If you suggest a retry on a failure that will never succeed, you have built a loop with better manners. Keep the suggestions honest, pair them with a hard attempt budget, and lean on a no-progress guard that stops the agent when it stops advancing, because a polite loop is still a loop.
Over shaping is the opposite trap. If you rewrite every error into a cheerful hint, you can erase the signal that something is genuinely terminal, and the model keeps trying because you keep implying it should. Not allowed and terminal errors need to read as walls, not as puzzles. Say stop, and mean it.
There is a transport decision underneath all of this. The MCP specification separates a tool execution error, reported inside the result with an isError flag, from a protocol level error for a malformed or unknown call. That line is the contract in miniature: execution errors reach the model because the model can act on them, protocol errors go to the orchestrator because it cannot. If you flatten the two, you either hide recoverable failures from the model or dump infrastructure noise into its context. Match your transport to the distinction and the rest of the contract has somewhere to live.
Last, do not let the contract swallow the raw error. The model gets the shaped three fields; your logs, traces, and on call engineer get the full traceback, status, and body. A contract that throws away the raw cause to look tidy trades a debuggable incident for a clean one, and you will want the mess the night something breaks.
The takeaway
Your agent's ability to recover from a failed tool call is mostly an interface you are designing without noticing. The model cannot see your exceptions or your logs, only the text you place in its context, so a tool error is a message to the model, and its shape and placement decide whether the agent repairs the failure, abandons it, or papers over it with a guess. Give every failure the same small contract: what failed in plain terms, why in a class the agent can route on, and a concrete next action, delivered as a visible turn that keeps the failed exchange in view.
Classify in code, shape for the model, validate silent results into loud errors, and keep the raw cause for yourself. It is a modest amount of wrapper code and a change of stance: the error is not a log line you emit, it is a sentence the agent reads next. If your agents stop or fabricate more than they recover, that handback is where the fix is hiding, and it is worth a short conversation before the next quiet booking lands at the wrong time.
Questions this essay answers
01What is a tool error contract for an AI agent?
A tool error contract is the fixed shape every failed tool call returns to the model: what failed, why it failed in a category the agent can route on, and a concrete next action to try. Instead of handing back a raw stack trace or an opaque status code, the wrapper around each tool translates the failure into that shape. The point is to give the model something it can act on in the next step, because the model never sees your logs or your exception type, it only sees the text you place in its context.
02Why does my agent give up or fabricate after a tool call fails?
Because the error it received did not tell it what to do next. A model produces the most plausible continuation of its context, and after an opaque failure the most plausible continuation is often an apology and a stop, or a confident guess that papers over the gap. Research in 2026 shows the same error delivered two ways leads to different actions: a failure the model can read and locate in the conversation gets repaired, while the identical text buried or stripped of guidance gets abandoned. The shape and placement of the error drive the behavior.
03How is this different from classifying and retrying tool failures?
Classification decides what you do: retry, repair, refresh, or stop. The error contract decides what the model is told so it can do the repair itself when that is the right path. They work together. You classify the failure in code, then shape the message you hand back to match the class, with the specific correction for a bad argument and a plain stop for an unrecoverable one. Classification without a good message leaves the model guessing; a good message without classification shapes the wrong failures.
04Should I use the MCP isError flag or a protocol error?
Use isError for failures the model should see and reason about, such as a bad argument or a business rule rejection, because the result still reaches the model's context where it can act on it. Reserve protocol level JSON-RPC errors for failures in the call itself, like an unknown tool or malformed request, which the orchestrator handles and the model cannot fix. The MCP specification draws exactly this line, and matching your transport to it keeps recoverable errors in front of the model and infrastructure errors out of its way.
