/ai-agent-skills:agent-tool-call-loop-diagnosis-and-circuit-breakingfrom ai-agent-skills
Diagnoses active or recurring agent tool-call loops and stops them safely with bounded retry policies and hard ceilings. Use when an agent repeatedly calls the same tool, needs circuit-breaking, or someone proposes raising iteration limits without addressing root cause.
Ships in ai-agent-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
A runaway tool-call loop — an agent calling the same tool repeatedly, or oscillating between two or three calls, without making progress — is one of the most common and most expensive agent failure modes in production: it burns tokens and API quota, can hammer a downstream system, and often goes unnoticed until a bill or a rate-limit alert fires. Preventing loops at design time (a hard iteration cap, stall detection in the dispatcher) is covered in agent-architecture-design and agent-tool-use-patterns; this skill is the operational companion — what to do when a loop is actually happening or has already happened: how to confirm it's really a loop and not a legitimate long-running task, how to stop an in-flight session safely, how to root-cause the trigger, and how to design a bounded retry with a hard ceiling rather than the reflexive, unsafe fix of just raising the existing limit. Raising a limit without addressing the cause doesn't stop the loop — it makes the loop more expensive before it stops.
MAX_ITERATIONS" or "just increase the
retry count" as the fix, and you need to evaluate whether that's masking
the real problem.Confirm it's actually a loop before treating it as one. Pull the session's tool-call history and check for genuine repetition, not just "many calls" — a legitimately long task (paginating through a large result set, retrying a transient network blip a bounded number of times) can also produce a high call count. The distinguishing signal is whether each call carries new information toward the goal:
def is_loop(call_history, window=5):
recent = call_history[-window:]
signatures = [(c.tool_name, json.dumps(c.arguments, sort_keys=True)) for c in recent]
return len(recent) == window and len(set(signatures)) <= 2 # near-total repetition
Classify the loop type — the fix differs by type:
search(x) → search(y) → search(x) → ...) — usually the model
re-trying variations without converging, often because neither result
satisfies an implicit precondition the prompt never stated.Stop the in-flight session at a safe boundary, not mid-call. Before force-killing a session, check whether any tool currently executing (or just completed but not yet acknowledged) is a reversible-write or irreversible-write action per its risk classification — killing a process mid-write can leave a partial state (a half-applied update, a sent-but-unlogged message) that's harder to clean up than the loop itself. Prefer a cooperative cancellation (set a flag the loop checks between tool calls) over a hard process kill wherever the runtime supports it; reserve a hard kill for cases where the loop is read-only or already confirmed stalled with no side effects in flight.
Distinguish "still worth retrying" from "already proven futile" before designing the breaker. A transient error (network timeout, momentary 429) is reasonably retried a small, bounded number of times with backoff. An error that is deterministic given the current arguments (a 404 on an ID that doesn't exist, a validation error on malformed input) will not succeed on retry with the same arguments — retrying it anyway is pure waste and the fix belongs in surfacing that distinction to the model, not retrying harder.
Implement a bounded retry with an explicit hard ceiling, not just a backoff schedule. Backoff alone (exponential delay between attempts) without a hard cap on total attempts still allows an unbounded total cost if nothing ever forces a stop; a hard ceiling is the actual safety property.
class CircuitBreaker:
def __init__(self, max_attempts_per_signature=3, max_total_calls=25,
cooldown_seconds=30):
self.max_attempts_per_signature = max_attempts_per_signature
self.max_total_calls = max_total_calls # hard ceiling, session-wide
self.cooldown_seconds = cooldown_seconds
self._attempts = collections.Counter()
self._total_calls = 0
self._tripped_signatures = set()
def before_call(self, tool_name, arguments):
signature = (tool_name, json.dumps(arguments, sort_keys=True))
if signature in self._tripped_signatures:
raise CircuitOpen(f"{tool_name} already failed {self.max_attempts_per_signature}x with these arguments")
if self._total_calls >= self.max_total_calls:
raise CircuitOpen("session tool-call ceiling reached — hard stop, not a retryable condition")
self._total_calls += 1
return signature
def after_call(self, signature, result):
if result.is_error:
self._attempts[signature] += 1
if self._attempts[signature] >= self.max_attempts_per_signature:
self._tripped_signatures.add(signature) # this exact call is now permanently blocked this session
The critical property: max_total_calls is a hard ceiling the
session cannot exceed under any circumstance, independent of and in
addition to per-signature retry limits — it's the backstop that catches
oscillation and cost-without-progress loops that per-signature counting
alone would miss.
Warning: Raising
max_attempts_per_signatureormax_total_callsin response to a loop incident, without fixing the underlying trigger (step 6) and without keeping some hard ceiling in place, is not a fix — it is choosing to pay more before the same failure stops. Every ceiling raise should come with a stated reason tied to a legitimate use case (e.g. "this workflow genuinely needs up to 40 calls for large result sets"), not "the loop kept hitting the old limit."
Root-cause the underlying trigger once the loop is contained. Common
triggers: a tool schema that doesn't tell the model a precondition
(e.g. "call stop_instance before resize_instance"), a tool that
returns an ambiguous or malformed error the model can't act on, or the
model misreading a tool result as incomplete when it was actually
final. This overlaps with
agent-bad-response-triage-and-root-cause-classification
when the loop also produced a bad final answer rather than just wasted
cost.
Add the trapped case to the eval suite (see agent-evaluation-and-guardrails) so a fix to the tool schema, error message, or prompt can be validated against the exact scenario that caused the loop, not just spot-checked.
Add session-level alerting on tool-call count and distinct-signature ratio, not just on total cost or latency — a loop is visible in call count and repetition well before it shows up as a cost anomaly large enough to alert on its own (see agent-cost-and-latency-spike-investigation).
Verify the fix by replaying the original trigger against the patched tool/prompt with the circuit breaker still active — the breaker should not trip on the fixed path, and should still trip if the same bug is reintroduced later.
max_total_calls ceiling generously above legitimate peak usage,
but always set one.failed, not a
silent truncation that looks like a normal stop.Symptom: An on-call engineer raises MAX_ITERATIONS from 12 to 100
during an incident to "unblock" a stuck workflow, the workflow completes
once, and the same loop recurs at higher cost the following week.
Fix: Treat a raised ceiling as a temporary, tracked exception with an
explicit expiry and a linked root-cause ticket, not a permanent
configuration change — the underlying trigger (step 6) still needs
fixing regardless of the ceiling's value.
Symptom: A hard kill of a stuck agent session leaves a database
record half-updated or a message partially sent, because the kill
happened mid-tool-execution rather than between calls.
Fix: Use cooperative cancellation that only stops the loop at a safe
boundary (between tool calls), and check the risk classification of any
in-flight call before a hard kill; reserve hard kills for sessions
confirmed to have no reversible/irreversible action in flight.
Symptom: The circuit breaker's exact-signature matching never trips
because the model varies one argument slightly on every call (a
timestamp, a retry counter, a slightly reworded query string), so the
session keeps looping under a "different" signature each time.
Fix: Add a session-wide hard ceiling (max_total_calls) that trips
independent of signature matching, and consider a looser signature
(ignore volatile fields like timestamps when hashing arguments) for the
per-signature check specifically for oscillation detection.
Symptom: A tool call fails with a generic "error" the dispatcher passes back to the model verbatim, the model retries the identical call believing a retry might succeed, and this repeats until the ceiling trips. Fix: This is a dispatcher problem, not a model problem — return a structured, specific error (see agent-tool-use-patterns) that distinguishes "transient, retry may help" from "deterministic failure, retrying with the same arguments cannot succeed," so the model (and the breaker's own logic) can react appropriately.
Symptom: Cost/latency monitoring only alerts on aggregate spend, so a loop that runs cheap, fast tool calls thousands of times goes unnoticed until a downstream rate limit or quota is exhausted. Fix: Alert on tool-call count and distinct-signature ratio per session directly, not only on aggregate dollar cost — a loop is visible in call volume long before it's visible in a cost dashboard.
Scenario: A cloud-ops agent given list_instances, stop_instance,
and resize_instance tools is asked to "resize the checkout-api fleet to
a larger machine type." Tool-call logs show 40+ calls to resize_instance
with the same instance_id, each failing with a bare "error": "invalid state".
Diagnosis:
(resize_instance, {"instance_id": "i-0abc...", "new_machine_type": "large"}).resize_instance requires a stopped
instance per its schema description — see
agent-tool-use-patterns), and
the dispatcher's "invalid state" message gives the model no
actionable detail to self-correct.max_attempts=3) should have tripped at attempt 3, but the breaker
wasn't wired into this dispatcher yet — the session is killed at the
next safe boundary (no resize_instance call was actually in flight
mid-execution, all had already returned an error, so a hard stop is
safe here).resize_instance failures into a generic "invalid state" string
instead of the specific precondition failure.{"error": "resize_instance requires the instance to be stopped first; call stop_instance(instance_id) then retry"},
and the circuit breaker from step 5 of the guidance above is added to
the dispatcher with max_attempts_per_signature=3 and
max_total_calls=25 for this agent's sessions.stop_instance after the first
resize_instance failure and completes successfully in 3 tool calls;
a new eval case captures this exact sequence
(resize before stop → expect stop_instance next) per
agent-evaluation-and-guardrails.tool_call_count > 15 for this
agent type is added, so a future recurrence pages before running to the
ceiling silently.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
agent-loop, circuit-breaker, retry-policy, runaway-agent, cost-control
npx claudepluginhub selvarajmurugesan90/ops-engineering-skills --plugin ai-agent-skills20 skills in this plugin
/agent-architecture-designGuides designing the control loop, state/memory model, and tool boundaries for an LLM-driven agent. Use when a user asks to "design an agent architecture," choose between a ReAct loop / plan-and-execute / finite-state agent, decide on single-agent vs multi-agent decomposition, define how an agent should manage state and memory across turns, or review whether an existing agent's control flow is safe to run unattended.
/agent-bad-response-triage-and-root-cause-classificationGuides triaging a single reported bad, wrong, or harmful agent response: reproducing it deterministically and classifying the root cause into one of five buckets — prompt issue, tool failure, retrieval issue, model behavior change, or genuine edge case — so the fix targets the actual cause instead of the symptom. Use when a user asks to "investigate this bad agent response," "why did the agent say/do that," "triage this reported hallucination/harmful output," "figure out if this is a prompt bug or a model regression," or files an incident about a single problematic agent interaction that needs root-causing before a fix ships.
/agent-cost-and-latency-spike-investigationGuides rapidly triaging a sudden cost or latency spike affecting one specific agent workflow — scoping it, correlating it against recent changes, and applying a fast, safe stopgap — before launching a full optimization pass. Use when a user asks "why did our LLM bill jump overnight," "this one workflow got slow/expensive all of a sudden," "investigate a cost/latency spike," or reports an alert/invoice surprise for a single agent or task type, as distinct from a deliberate, scheduled effort to reduce baseline cost or latency.
/agent-evaluation-and-guardrailsGuides building evaluation harnesses, regression test suites, and runtime guardrails for LLM agents. Use when a user asks to "evaluate this agent," "write test cases for a prompt change," "set up an eval harness," "add guardrails to prevent unsafe output," "detect prompt injection at runtime," or needs to know whether a prompt/model/tool change made an agent better or worse before shipping it.
/agent-tool-use-patternsGuides designing safe, reliable tool/function-calling interfaces and loops for LLM agents. Use when a user asks to "design tool schemas," fix an agent that hallucinates tool calls or arguments, prevent infinite tool-call loops, decide how much autonomy to give an agent's tool use, handle untrusted tool output safely, or add confirmation gates before destructive tool actions.
/code-knowledge-graph-tools-for-ai-agentsCompares GitNexus, Graphify, and CodeGraph — tools that precompute a structural knowledge graph of a codebase and expose it to AI coding agents via MCP, replacing repeated grep/file-read exploration with direct impact-radius, call-chain, and dependency queries. Use when a user asks to "give my coding agent a code graph," "reduce how many tool calls/tokens my agent burns exploring the repo," "set up GitNexus/Graphify/CodeGraph," "find an MCP tool for codebase structure," or is choosing between these three tools based on license, language coverage, or query model.
Other plugins' skills for the same job