A search tool starts timing out halfway through a task. The agent reads the error, concludes its query was probably too narrow, rephrases it and calls the tool again. The next result is an empty list, so it rephrases again. Each step looks reasonable on its own. Eventually the run hits a step limit, if someone configured one. If not, the first sign of trouble is a bill, or a user asking why the assistant never answered.
Retry logic in your HTTP client does not help here. The code is not deciding to retry. The model is, one plausible step at a time.
The fix is a pattern microservices teams already know, the circuit breaker, with two changes for agents. It has to live outside the model, in the orchestration code. And it has to trip on behaviour as well as on errors, because a stuck agent's calls often succeed: they return HTTP 200, so an error counter never sees them.
1. Why a failing tool turns into a runaway loop
In a tool-using agent, the model is the control flow. It reads each result and picks the next action. An error message is just more text in the context. Nothing in it forces the model to stop, and a model tuned to be helpful and persistent can read "Request failed: upstream timeout" as a reason to rephrase and try again. That is a plausible failure mode to test for, not a measured rate.
Each attempt also costs more than the last. Every step re-sends the conversation so far, and a loop appends a new call and a new error on each pass, so per-step input grows linearly and the run's total input grows roughly with the square of the step count. Prompt caching bills a repeated prefix at a fraction of the input price, which lowers the curve without flattening it. See the unit economics of an agent.
Then there is the retry logic you already have. Client libraries often retry by default: Anthropic's Python SDK, for example, retries timeouts, rate limits and server errors on its own API calls twice, with exponential backoff. If the HTTP client behind a tool behaves the same way, its retries sit underneath the model's and multiply them. Put the breaker outside the retrying client, count one failure per exhausted retry sequence, and keep client retries for brief transient faults.
Anthropic's guidance on agents notes that their autonomy means higher costs and compounding errors, and recommends guardrails.
2. The failures an error counter never sees
A classic circuit breaker, as Martin Fowler describes it following Michael Nygard's Release It!, wraps a protected call and counts failures. Once they reach a threshold it trips, and later calls fail immediately without reaching the dependency. That works because a failing service dependency usually announces itself.
Agents usually fail more quietly. These are the patterns I'd watch for:
- Repeated identical calls. The same tool with the same arguments, over and over, each call succeeding with a result the model misreads or doesn't trust.
- Successful but useless results. A search comes back empty, and the model keeps reformulating.
- Oscillation. The agent alternates between two tools, such as fetching a record and validating it, and each result sends it back to the other.
- Steps that change nothing. The agent's state, plan or draft answer is the same after a step as before it.
Each is a success from the downstream service's point of view, so dashboards stay green and an error-counting breaker never trips.
None of these signals needs the model's help to detect. For repeated calls, hash the tool name with normalised arguments (sorted keys, trimmed whitespace) and count each hash per run. For lack of progress, compare the agent's state or draft between steps and flag the steps where nothing changed. Budget burn is arithmetic: track tokens or estimated spend per run against a healthy run of the same kind of task.
3. Closed, open, half-open, adapted for an agent
The per-tool breaker keeps all three classic states. Closed is normal operation: calls pass through while the breaker counts the tool's errors. Open short-circuits: a call returns a structured "unavailable" result at once, and the tool is never invoked. Half-open tests recovery: after a cool-down, a trial call goes through, and success closes the breaker while failure restarts the wait.
Count failures over a rolling window rather than only consecutively, so intermittent faults still trip it, and admit one trial call at a time in half-open. What changes for agents is the wiring: tool errors feed a per-tool breaker, and the behavioural signals feed a separate per-run breaker, because a tool that keeps timing out and an agent that keeps asking the same question need different responses.
The per-tool breaker, shared across runs, answers "is this dependency unhealthy?" It trips on errors aggregated over many runs, counting only those that reflect the tool's health, such as timeouts, 5xx responses or, for MCP tools, a failed or timed-out call rather than an isError result, which can just mean bad arguments, and recovers through half-open trials. Validation errors the model caused belong to the per-run breaker; otherwise one confused run trips a healthy tool for everyone.
The per-run breaker answers "is this agent behaving badly?" It trips on the behavioural signals and needs only closed and open. When either one blocks a tool, keep it blocked until that run ends, even if the shared breaker later closes for new runs. A tool that flickers back mid-run just restarts the loop.
flowchart LR
subgraph T[Per-tool breaker, shared]
C[Closed] -->|error threshold in window| O[Open]
O -->|cooldown elapsed| H[Half-open]
H -->|health probe ok| C
H -->|probe fails| O
end
subgraph R[Per-run breaker]
RC[Closed] -->|repeat calls, no progress, budget burn| RO[Open until run ends]
endHalf-open needs one more rule. The trial call must not come from the stuck run, and for tools with side effects it must not be a real action. Probe a read-only health check; if a side-effecting tool has none, keep it open until someone confirms recovery rather than testing with a real email or ticket.
4. Placing the breaker around each tool, outside the model
The breaker belongs in the orchestration code, between the tool executor and each tool. The executor receives the model's tool-call request, validates the arguments and invokes the tool through that tool's breaker, so every call passes through it whether or not the model is behaving sensibly.
It is tempting to write the rule into the system prompt instead: "If a tool fails three times, stop calling it." The model may follow it, miscount, or decide this case is an exception. A prompt can explain the policy; it cannot enforce it.
Make it per tool, because failures are local. Thresholds differ too: a cheap, idempotent read can tolerate more retries than a slow paid call, and tools with side effects, such as sending an email or creating a ticket, need the strictest thresholds, because a repeated call does damage on its own.
When an agent calls tools on an MCP server, the breaker belongs on the client side, in the runtime you control. The current MCP tools specification puts rate limiting on the server and asks clients to implement timeouts for tool calls. Those limits protect the server, which has no view of the run's budget or progress.
The breaker is one ring in a set of nested controls:
flowchart TB
subgraph OUTER["Wall-clock timeout + human escalation"]
subgraph RUN["Run-level step limit + token/cost budget"]
M["Model"] -->|"tool-call request"| E["Tool executor"]
D["Per-run loop detector: repeated calls, no progress, spend rate"] -.->|"watches every step"| E
subgraph B1["Per-tool breaker"]
T1["Search tool client (retry + backoff)"]
end
subgraph B2["Per-tool breaker"]
T2["Database lookup client (retry + backoff)"]
end
subgraph B3["Per-tool breaker"]
T3["Remote MCP tool client (retry + backoff)"]
end
E -->|"invoke"| T1
E -->|"invoke"| T2
E -->|"invoke"| T3
E -->|"result or open-breaker message"| M
end
endI treat the executor as the natural enforcement point: every model decision becomes a real action there, and it is code you own while prompts, frameworks and models change.
5. What the agent is told when the breaker is open
The agent still needs a response to its tool call. I wouldn't throw an exception: depending on the framework, it either crashes the run or lands in the context as a stack trace the model will try to interpret. Return a structured tool result with the same shape as any other and a clear status. For MCP tools, shape it like a tool execution error with isError: true, so the model sees it the way it sees any other failed call.
The content should tell the model four things:
- the tool is unavailable
- it stays unavailable until this task ends
- the tool should not be called again
- where relevant, a retry-after hint for a scheduler or a later run
Where possible, also say what the model can do instead: a fallback tool, a partial answer from what it already has, or a question for the user. For example: "web_search is unavailable for the rest of this task. Do not call it again. Answer from the documents already retrieved, or tell the user which part you could not verify."
Wording matters. "Temporary error, please try again" invites a retry. "Unavailable for this task" removes the reason to keep trying and points at the paths that remain. Test your wording against your evaluation set.
The message is guidance, so don't make it the only control. When the breaker opens, short-circuit any call that still arrives, so a model that ignores the message can't get through. You can also drop the tool from the list sent on the next step, but tool definitions sit at the start of the cached prompt, so removing one rewrites the cache at write prices.
When no viable path remains, end the run deliberately and explain what was done and what wasn't, or escalate to a human.
6. The layers that catch what a breaker misses
Anthropic notes that agents commonly include stopping conditions such as a maximum number of iterations, and frameworks expose one. Don't assume the default protects you: LangGraph's Python docs put the default recursion_limit at 10,007 super-steps from version 1.1.4, which is no cost limit at all once input grows with every step, so check your framework's default and set your own. A graph workflow without cycles also caps the step count.
No single layer catches everything:
| Layer | Catches | Misses | Cost |
|---|---|---|---|
| Client retry with backoff | Transient network faults and brief upstream blips | Persistent outages and every behavioural failure; multiplies the model's retries | Low to build; adds latency and load on a failing dependency |
| Per-tool circuit breaker | A dependency that keeps failing; stops calls early and tells the model why | Loops across healthy tools, and quiet failures if it only counts errors | Moderate; needs thresholds, state and a designed open-breaker message |
| Per-run loop detector | Repeated identical calls, oscillation and no-progress steps | Loops that keep varying their arguments; polling and pagination need exemptions | Moderate to high; "no progress" is hard to define well |
| Step/recursion limit | Any run that goes on too long, whatever the cause | The waste before the limit; gives no diagnosis | Very low, but only if you set it |
| Token/cost budget | Runaway spend from any cause | Cheap loops that waste time; explains nothing | Low; needs per-run accounting |
| Wall-clock timeout | Hung tools, slow loops, users left waiting | Fast, expensive loops that finish inside the window | Very low; can cut off legitimate long tasks |
Limits and budgets stop a run only after the waste, and neither says why. The breaker can stop early with a signal the model can act on, but only for failures it was built to detect. So combine them: the budget as the hard backstop nothing gets past, the breaker as the early, informative stop that can end many bad runs sooner, and the step limit and timeout as cheap insurance for what you didn't anticipate.
7. False trips, shared state and tuning thresholds
Behavioural breakers produce false positives. Polling a job status repeats the same request until the job finishes, and pagination looks repetitive if the cursor isn't part of the hash. These need per-tool exemptions, or progress-aware detection that counts a changed response as progress even when the request didn't change.
"No progress" is harder than it sounds: diffing output is noisy, explicit state changes need a structured agent state, and a judge model adds cost and can be wrong itself.
An in-process breaker is simple, but each replica learns about a failing tool on its own. Shared state in something like Redis gives every replica the same view, at the price of a network hop on every tool call and a decision about what happens when that store is down.
Thresholds start as guesses, so emit every trip as telemetry (signal, tool, run, step count) and tune from observed runs.
8. Where I'd start in an existing agent
I'd start with a hard per-run budget and an explicit step limit: cheap, and neither depends on getting detection right. Next, a per-tool breaker on errors, plus a per-run counter for repeated identical calls, the most valuable behavioural signal and the easiest to detect: one hash and one counter per run.
Then the open-breaker message and a graceful exit. No-progress detection and shared state can wait until telemetry shows you need them.
The model can take part in the recovery. It can choose a fallback, write a partial answer or ask the user. It cannot be the component that decides to stop.






