entry
No. 13
date

updated
filed under
tool use, agents, debugging
checked against
9 sources

Agent Tool Retries: Timeouts, Backoff and Idempotency Keys

Agent tool retries are safe when you follow a few rules. Give every attempt its own timeout. Retry only errors that might succeed next time, such as timeouts, dropped connections, 429s and 5xx responses, with a capped exponential backoff and random jitter. And never repeat a call with side effects unless the tool is idempotent, either by nature or through an idempotency key the server uses to recognize the repeat. When a call with side effects times out and you can't prove it didn't run, stop and tell the model the outcome is unknown instead of trying again.

This post explains each rule, shows a small Python wrapper that applies them to any tool, and covers what the Model Context Protocol, Stripe and AWS say about the details. The code was run on Python 3.13 and needs 3.11 or later for asyncio.timeout().

Why agents make retries riskier

A plain API client retries a request it built itself. An agent adds two more places where a call can be repeated: your tool wrapper, and the model, which reads an error and often calls the same tool again. A refund tool that times out can be retried by the HTTP library, by your wrapper and then by the model on its next turn. If the first attempt actually went through, the customer gets three refunds.

The AWS Builders' Library article on timeouts and retries describes the load side of this. Retries are "selfish": each one asks the server for more of its capacity. In its example, a stack five layers deep that retries three times at every layer can multiply the load on the database by 243, "making it unlikely to ever recover." Its advice for that case is to retry at a single point in the stack.

For an agent, pick that point on purpose. If you call a model through the Anthropic Python SDK, the docs say it already retries connection errors, 408, 409, 429 and 500-plus responses twice by default, with a short exponential backoff, and requests time out after 10 minutes unless you set timeout. Your own loop around that client should not retry the same errors again. If it does, as when you fall back to a second model after a 529, keep the SDK's own retries low; Claude API 529 overloaded_error shows that setup. For tools, the wrapper below is the single point, and the model is told when retrying is not safe.

Rule 1: every attempt gets a timeout

A tool call with no timeout can hold an agent run open until something else kills it. The MCP specification lists "Implement timeouts for tool calls" among the things clients should do, in both the 2025-11-25 and 2026-07-28 revisions.

The AWS article gives a method for choosing the number: pick an acceptable rate of false timeouts, such as 0.1%, and set the timeout at the matching latency percentile of the thing you call, p99.9 in that example. Too low and healthy calls time out and get retried, which adds load. Too high and the agent waits on calls that are never coming back. If you trace your tools as described in agent observability tracing, the execute_tool span durations give you that percentile per tool.

In Python, asyncio.timeout() cancels the work when the deadline passes and raises TimeoutError, which the docs note can only be caught outside the context manager. A timeout on your side does not stop work already sent to a remote server. The server may finish the request after you gave up. That is why the next two rules exist.

Rule 2: retry only errors that can succeed next time

The AWS article draws the line this way: client errors "should not be retried with the same request because they aren't going to succeed later," while server errors "may succeed on subsequent tries." The AWS SDKs follow the same split. Their retry documentation treats request timeouts, connection resets, DNS failures and 500, 502, 503 and 504 responses as transient, retries throttling errors with a longer base delay, and does not retry errors such as ValidationException or AccessDeniedException.

For agent tools that gives two classes:

  • Retryable: timeouts, connection errors, 429 rate limits, 5xx responses. Retry with backoff, a few times at most.
  • Permanent: bad arguments, 4xx responses other than 408 and 429, business-rule rejections such as "order already refunded." Don't retry. Return the error to the model so it can change its arguments.

The second class matters more for agents than for ordinary clients, because the model can fix it. The MCP tools spec separates protocol errors from tool execution errors, which are returned in the result with isError: true and contain "actionable feedback that language models can use to self-correct and retry with adjusted parameters." It says clients should pass tool execution errors to the model. A clear message such as "amount_cents must be positive" turns a dead end into a corrected call. Vague errors push the model toward calling the wrong tool or repeating itself, which is how runs end up in the loops that never stop.

Rule 3: back off with jitter, and cap it

Retrying immediately hits a struggling service at the moment it is least able to answer. Exponential backoff spaces the attempts out, and jitter adds randomness so many clients don't retry in lockstep. In Marc Brooker's 2015 AWS Architecture Blog post comparing approaches, "The no-jitter exponential backoff approach is the clear loser," and jittered backoff "should be considered a standard approach for remote clients."

The AWS SDK documentation for the SDKs' updated retry behavior, which is opt-in until it becomes the default, gives the full-jitter formula in one line: delay = random(0, 1) × min(20,000 ms, base_delay × 2^retry), with a 50 ms base for transient errors and 1,000 ms for throttling, and no single delay over 20 seconds. The SDKs default to 3 total attempts, meaning one request and up to two retries.

The SDKs also keep a retry budget. Each retry spends tokens from a bucket, successes put tokens back, and when the bucket is empty the SDK stops retrying and returns errors directly. The AWS Builders' Library article recommends the same local token bucket. For an agent that runs many tool calls at once, a budget like this stops a failing dependency from turning every run into a retry storm.

Rule 4: idempotency decides what is safe to repeat

An operation is idempotent when doing it twice has the same effect as doing it once. Reading a record is. Setting a field to a value is. Creating a refund, sending an email or posting a message is not. The AWS article is direct about it: "APIs with side effects aren't safe to retry unless they provide idempotency."

Idempotency keys make a non-idempotent operation safe to retry. Stripe's API reference describes how it works for its API v1:

  • The client sends an Idempotency-Key header, up to 255 characters. Stripe suggests V4 UUIDs or another random string with enough entropy, and says not to use sensitive data such as email addresses as keys.
  • Stripe saves the status code and body of the first request with that key once the endpoint starts executing. Retries with the same key return the saved response, including 500 errors.
  • Keys can be pruned after they are at least 24 hours old, and a key reused after pruning creates a new request.
  • If the parameters differ from the original request, Stripe returns an error.
  • If a request fails validation or collides with a concurrent request, nothing is saved, and it can be retried.

The pattern carries over to your own tools. The tool's backend stores the result under the key and returns it on a repeat. The caller generates one key per logical action and reuses it on every retry of that action. A new key on each attempt defeats the point.

MCP gives servers a way to say which tools are safe to repeat. ToolAnnotations includes idempotentHint: "If true, calling the tool repeatedly with the same arguments will have no additional effect on its environment." It defaults to false, and only means something when readOnlyHint is false. The schema also says all annotations are hints that "are not guaranteed to provide a faithful description of tool behavior," and that clients should never make tool use decisions based on annotations from untrusted servers. Treat the hint as a default for servers you run, not as proof. If you build an MCP server in Python, set it honestly on each tool.

A retry wrapper for agent tools

The wrapper below applies the four rules to any async tool. Each tool gets a policy: a per-attempt timeout, a maximum number of attempts, backoff settings and whether it is idempotent. The wrapper creates one idempotency key per logical call and passes it to the tool on every attempt.

"""Retries, timeouts and idempotency keys for agent tool calls."""
import asyncio
import random
import uuid
from dataclasses import dataclass


class RetryableError(Exception):
    """Worth another try: timeouts, dropped connections, 429s, 5xx."""


class PermanentError(Exception):
    """Same request will fail again: bad input, 4xx, business-rule rejections."""


@dataclass
class ToolPolicy:
    timeout_s: float = 10.0      # per attempt
    max_attempts: int = 3        # including the first try
    base_delay_s: float = 0.2
    max_delay_s: float = 5.0
    idempotent: bool = False     # safe to repeat with the same arguments?


def backoff(retry: int, policy: ToolPolicy) -> float:
    """Full jitter: a random delay between 0 and the capped exponential."""
    return random.uniform(0, min(policy.max_delay_s, policy.base_delay_s * 2 ** retry))


async def call_tool(fn, args: dict, policy: ToolPolicy) -> dict:
    """Run one logical tool call. Returns a result or an error the model can read."""
    # One key per logical call, reused on every retry of that call.
    key = str(uuid.uuid4())
    for attempt in range(policy.max_attempts):
        try:
            async with asyncio.timeout(policy.timeout_s):
                result = await fn(**args, idempotency_key=key)
            return {"ok": True, "result": result, "attempts": attempt + 1}
        except PermanentError as exc:
            return {"ok": False, "retryable": False, "error": str(exc)}
        except (RetryableError, TimeoutError) as exc:
            timed_out = isinstance(exc, TimeoutError)
            if timed_out and not policy.idempotent:
                # The side effect may have happened. Don't guess: tell the model.
                return {"ok": False, "retryable": False, "outcome": "unknown",
                        "error": "Timed out after the request was sent. It may have "
                                 "succeeded. Check its status before trying again."}
            if attempt + 1 == policy.max_attempts:
                return {"ok": False, "retryable": True,
                        "error": f"Gave up after {policy.max_attempts} attempts: {exc or 'timeout'}"}
            await asyncio.sleep(backoff(attempt, policy))

To test it, a fake refund API stores each result under its idempotency key and, on the first call, does the work and then drops the response, the case that causes double refunds. A second fake tool sends email slowly and has no key support:

import asyncio

from tool_retries import PermanentError, RetryableError, ToolPolicy, call_tool

charges = {}          # idempotency_key -> refund, the server's saved results
calls = {"n": 0}

async def create_refund(order_id: str, amount_cents: int, idempotency_key: str) -> dict:
    calls["n"] += 1
    if amount_cents <= 0:
        raise PermanentError("amount_cents must be positive")
    if idempotency_key in charges:          # a repeat of a request it already ran
        return charges[idempotency_key]
    refund = {"refund_id": f"re_{len(charges) + 1}", "order_id": order_id,
              "amount_cents": amount_cents}
    charges[idempotency_key] = refund
    if calls["n"] == 1:
        raise RetryableError("connection reset before response")
    return refund

async def slow_email(to: str, idempotency_key: str) -> dict:
    await asyncio.sleep(1)
    return {"sent": True}

async def main():
    p = ToolPolicy(timeout_s=0.5, base_delay_s=0.01, idempotent=True)
    print(await call_tool(create_refund, {"order_id": "A-1001", "amount_cents": 2500}, p))
    print("refunds created:", len(charges), "server calls:", calls["n"])
    print(await call_tool(create_refund, {"order_id": "A-1001", "amount_cents": 0}, p))
    print(await call_tool(slow_email, {"to": "[email protected]"},
                          ToolPolicy(timeout_s=0.2, idempotent=False)))

asyncio.run(main())

The output shows one refund after two server calls, a permanent error returned without a retry, and an unknown outcome for the email:

{'ok': True, 'result': {'refund_id': 're_1', 'order_id': 'A-1001', 'amount_cents': 2500}, 'attempts': 2}
refunds created: 1 server calls: 2
{'ok': False, 'retryable': False, 'error': 'amount_cents must be positive'}
{'ok': False, 'retryable': False, 'outcome': 'unknown', 'error': 'Timed out after the request was sent. It may have succeeded. Check its status before trying again.'}

A few choices in the wrapper are deliberate:

  • Tools decide what is retryable. Raise RetryableError only when the request can safely run again: the tool is idempotent, or the server rejected the request before doing any work, as with a 429. Everything else should be PermanentError with a message the model can act on.
  • Timeouts on non-idempotent tools are not retried. The wrapper reports outcome: unknown. Give the agent a read-only status tool, such as "get refund for order", so it can check before acting again. For a high-stakes action, route the decision to a person, as in human in the loop agents.
  • Errors go back as data. The model sees retryable and the message, the same idea as MCP's isError results. On the Claude API every call needs a result even when it fails, or the next request is rejected, as covered in tool_use ids without tool_result blocks.

When the model retries on its own

The wrapper's key covers retries inside one tool call. It does not cover the model calling the tool a second time after a failure, because that is a new logical call with a new key. Two ways to close that gap:

  1. Tell the model what happened. An outcome: unknown error that says "check its status before trying again" works better than a bare "timeout", and a status tool makes the check possible.
  2. Derive the key from the action, not the attempt. For actions that should happen at most once per run, build the key from the run ID and the business identifiers, for example run_42:refund:A-1001. A repeated call from the model then lands on the same key and gets the saved result. Keep the limits in mind: Stripe compares parameters and returns an error if a reused key arrives with different ones, keys can expire after 24 hours, and Stripe advises against putting sensitive data in keys.

Count retries in your traces, too. A tool whose calls usually need two attempts is a dependency problem worth fixing before it becomes a cost problem.

Checklist

  • Set a per-attempt timeout on every tool, based on its measured latency.
  • Retry timeouts, connection errors, 429s and 5xx only. Return 4xx and validation errors to the model.
  • Use exponential backoff with full jitter, a delay cap and a small attempt limit.
  • Retry at one layer. Don't stack your retries on top of the SDK's.
  • Keep a retry budget so a failing dependency can't multiply load.
  • Mark which tools are idempotent. Give the rest idempotency keys, one per logical action.
  • Never auto-retry a timed-out call with side effects. Report the outcome as unknown.
  • Give the agent a read-only status tool for every action it can't safely repeat.
  • Treat MCP annotations from servers you don't control as hints, not guarantees.

FAQ

How many times should an agent retry a tool call?

Few. The AWS SDKs default to three total attempts, one request and up to two retries, and the Anthropic Python SDK retries twice by default. More attempts mostly add load and latency, and the model can still try a different approach after you return the error.

What is an idempotency key?

A unique value the client sends with a request so the server can recognize a repeat. Stripe saves the first response for a key and returns it to later requests with the same key, so a retry doesn't create a second object.

Should a tool timeout be retried?

Only if the tool is idempotent or uses an idempotency key the server honors. A timeout doesn't tell you whether the server did the work, so retrying a non-idempotent call can do it twice.

What does idempotentHint mean in MCP?

It is a tool annotation that, when true, says calling the tool again with the same arguments has no additional effect. It defaults to false, applies only to tools that aren't read-only, and is a hint that clients shouldn't trust from untrusted servers.

Which errors should not be retried?

Errors that will fail the same way next time: invalid arguments, permission errors and business-rule rejections. Return them to the model with a clear message so it can change its arguments.

Sources

Next in the notebook

  1. No. 2AI Agent Calling the Wrong Tool? 7 Causes and How to Fix Them

    A debugging checklist for tool-calling agents: overlapping tools, vague descriptions, ambiguous parameters, noisy output and bad errors, with a fix for each.

  2. No. 7Agent Infinite Loop: How to Debug Agents That Never Stop

    Why AI agents get stuck in infinite loops, and how to stop them: turn caps, token budgets, repeated-call detection, better tool errors and clear stop rules.

  3. No. 11Agent Observability Tracing: What to Log on Every Step

    Trace an AI agent with OpenTelemetry: one span per run, model call and tool call, which gen_ai attributes to record, and how to keep prompts out of traces.