Idempotent tool calls: making agent retries safe on the tool side
Agents repeat tool calls more often than you'd think. Here's how to build the tool end so a repeat is harmless, using MCP's annotations, RFC 9110's definition of idempotent, and the key-and-record pattern Stripe and AWS run in production.
Some links are affiliate links; we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases. Disclosure
An agent will call the same tool twice. Usually it's boring: your HTTP client retries a request that timed out, or the loop retries after a 502. The weirder case is the model asking for the same action again because the earlier result got trimmed out of context during compaction, or because a resumed run replays a step it already finished. A read tool shrugs this off. A create_refund tool pays the customer twice.
Our earlier piece on handling tool errors covered the caller's half: make the idempotency key in your tool wrapper and reuse it for transport retries. This one is about the other half, the tool itself. If you write MCP servers or function-calling backends, here's how to build them so a repeat call doesn't do anything new and still hands the agent a useful answer.
What idempotent actually means
The cleanest definition is in RFC 9110, the HTTP semantics spec. Section 9.2.2 calls a method idempotent "if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request." Of the methods the RFC defines, PUT, DELETE and the safe methods qualify. The RFC also says the property only covers what the user asked for. The server is still free to log every request separately.
The useful part for agent builders is the retry rule right after that. The RFC says a client should not automatically retry a request with a non-idempotent method unless it has some way to know the request really is idempotent, or some way to detect that the original request was never applied. Your agent loop is that client. A tool call looks the same on the wire whether it reads a file or wires money, so the method can't tell the client which calls are safe to repeat. The tool has to tell it, and then actually behave that way.
MCP annotations say what a tool claims, not what it does
MCP has a place to make that claim. The 2026-07-28 schema gives every tool an optional annotations object with readOnlyHint, destructiveHint, idempotentHint and openWorldHint. idempotentHint: true means "calling the tool repeatedly with the same arguments will have no additional effect on its environment," and it only means something when readOnlyHint is false. The defaults are worth memorizing because they're conservative: readOnlyHint defaults to false, destructiveHint to true and idempotentHint to false. A tool with no annotations is treated as a possibly destructive, non-idempotent write.
A refund tool that's been built to handle repeats would declare itself like this:
{
"name": "create_refund",
"description": "Refund part or all of an order. Safe to retry with the same request_id.",
"inputSchema": {
"type": "object",
"properties": {
"order_id": { "type": "string" },
"amount_cents": { "type": "integer" },
"request_id": { "type": "string" }
},
"required": ["order_id", "amount_cents", "request_id"]
},
"annotations": { "readOnlyHint": false, "destructiveHint": false, "idempotentHint": true }
}
The schema is blunt about what that buys you. All annotation properties "are hints," they are "not guaranteed to provide a faithful description of tool behavior," and clients should never make tool use decisions based on annotations from untrusted servers. The tools page puts it in RFC language: clients MUST consider annotations untrusted unless they come from trusted servers. So setting idempotentHint: true makes a promise. It doesn't make anything happen. If you set it, the server has to back it up with the machinery below, and a client deciding whether to auto-retry should only believe it from servers it already trusts.
Where the key comes from
MCP's tools/call has no idempotency field, and you can't lean on the JSON-RPC request id either. The tools page even says the id must be different when a client retries a call with input responses. So the key has to travel in the arguments, like request_id above, or in whatever side channel your client and server agree on.
Who fills it in matters. If the model writes the key, it may invent a fresh one on every attempt, which defeats the point. Have the client or your wrapper inject it, and keep it out of the schema the model sees if you can. A good key is derived from the run and the step: hash the run id, the step number and the tool call id, and you get the same key every time that exact step is replayed, including after a crash and resume. Stripe's guide suggests V4 UUIDs or another random string with enough entropy, caps keys at 255 characters, and warns against putting sensitive data like email addresses in them. A hash of internal ids stays far under that cap and carries nothing personal, and it's still unique per step.
Don't build the key from the arguments alone. The AWS Builders' Library article Making retries safe with idempotent APIs walks through exactly this shortcut: treat any two identical requests from the same caller as duplicates. It notes that two identical requests to launch an EC2 instance might really mean the caller wants two identical instances. An agent that refunds $20 on two different orders, or sends the same reminder to the same person a week apart, has the same problem. Amazon's preferred design is a unique client request id in the API contract, which also leaves an audit trail.
Run-and-step keys catch transport retries and resumed runs. They won't catch the model deciding, three steps later, to "make sure" the refund went through by issuing it again. That's a new step with a new key. For that case you want a business rule in the tool too, such as one open refund per order, or a check of current state before acting.
Record the key and the effect together
On the server, the core is a small table: key, a fingerprint of the arguments, status, and the saved response. The AWS article makes the hard requirement explicit. Recording the token and all the mutating work for the request has to be one atomic, all-or-nothing operation. Otherwise you can record the token and fail to create the resource, or create the resource and fail to record the token, and either way the next retry does the wrong thing.
Here's a rough sketch in Python against Postgres, with the refund and the idempotency row written in one transaction:
def create_refund(order_id, amount_cents, request_id):
fp = sha256(f"{order_id}:{amount_cents}".encode()).hexdigest()
with db.transaction():
row = db.fetchone(
"INSERT INTO idem (key, fingerprint, status) VALUES (%s, %s, 'running') "
"ON CONFLICT (key) DO NOTHING RETURNING key", (request_id, fp))
if row is None: # seen this key before
prior = db.fetchone("SELECT fingerprint, status, response FROM idem WHERE key = %s", (request_id,))
if prior.fingerprint != fp:
return tool_error("request_id was already used with different arguments")
if prior.status == "running":
return tool_error("this refund is still in progress; retry in a few seconds")
return prior.response # same answer as the first time
refund = payments.refund(order_id, amount_cents, idempotency_key=request_id)
response = {"refund_id": refund.id, "status": refund.status}
db.execute("UPDATE idem SET status = 'done', response = %s WHERE key = %s", (json.dumps(response), request_id))
return response
The payment call still goes outside your database, so the snippet passes the same key downstream. Every hop that has a side effect should get the key, or the chain breaks at the first one that doesn't.
The two error branches match what the big APIs do. Stripe compares incoming parameters against the original request and errors if they differ, and the AWS article returns a parameter-mismatch validation error for the same reason: a reused key with new arguments probably means a different intent. For a request that's still running, Stripe doesn't save a result when a request conflicts with one executing concurrently, so the caller can retry it later. Returning that as a plain tool error gives the model something it can act on.
Return the original result, not "already exists"
The last branch, return prior.response, is the one people skip. It's tempting to answer a duplicate with "refund already exists." The AWS article explains why that hurts. Technically there's no side effect, but the caller can't tell whether its own request created the resource or an earlier one did, and the different return code changes the caller's flow. Amazon's answer is a semantically equivalent response for the same request id, so the client can retry blindly and handle whatever comes back.
For an agent this matters even more. A model that reads "already exists" may decide something went wrong, apologize to the user, or try a workaround. A model that gets back the same refund_id and succeeded just moves on. Stripe's v1 API goes all the way: it saves the status code and body of the first request once the endpoint starts executing and replays it on retries, 500 errors included. Its v2 API instead finishes failed or partially failed work when it can and returns an updated response. Either is fine for a tool. Pick one and document it in the description.
How long to remember
Keys can't live forever. Stripe says v1 keys can be pruned once they're at least 24 hours old, and a key reused after pruning is treated as a new request. AWS ties the window for EC2 to the lifetime of the resource plus an interval after which late requests would either have arrived or no longer be valid, and it still returns the equivalent response to a late retry even after the instance is terminated.
For agent tools, size the window from your own runs, not from a default. If runs can pause for human approval or sit in a durable queue for two days before resuming, a 24-hour window will let a resumed step run its side effect a second time. Keep keys at least as long as your longest possible run plus its resume time, and expire them on a schedule so the table stays small.
If you want the wider production picture these patterns sit inside, AI Engineering by Chip Huyen covers building and running LLM applications end to end. For the tool itself, the work is mostly that one table plus passing the key to everything downstream. Until both are in place, leave idempotentHint at its default of false.