← cartapi.io blog

MCP tool idempotency: stop agents double-buying

Published 2026-11-18 · Last updated 2026-11-18 · 8 min read · agent commerce
TL;DR

An MCP tool that buys something is safe to retry only if the server makes it so. Add an idempotency_key argument to every tool that creates an order or charges a card. Derive the key from the purchase, not from the call. Enforce it with a unique index, pass the same key to Stripe and to the fulfilment provider, dedupe webhooks by event ID, and make the "paid → delivering" transition atomic. Set idempotentHint only once all of that is true. The MCP spec itself guarantees none of it.

Agents retry more than human users do. A request times out and the client tries again. The model reads an ambiguous result and calls the tool a second time. The user says "that didn't work, try again" when it did work. For a search tool, a repeat call costs a few milliseconds. For a tool that buys a gift card or tops up a phone, it can mean two orders. This checklist is how to stop that, with the patterns we use in cartapi's checkout code and the places where we haven't finished yet.

Why MCP doesn't solve this for you

An MCP tools/call request carries a tool name and an arguments object. Nothing in the 2025-11-25 schema deduplicates repeated calls. The closest thing is the idempotentHint tool annotation, defined as meaning that "calling the tool repeatedly with the same arguments will have no additional effect on its environment". It defaults to false.

The same schema warns that every property in ToolAnnotations is a hint that isn't guaranteed to describe the tool's behaviour, and that clients should never base tool-use decisions on annotations from untrusted servers. So the annotation tells a client what you claim. Your database and payment calls are what make the claim true.

Where a retry turns into a second purchase

A purchase passes through several layers, and each one can duplicate it on its own. Guarding only the first layer isn't enough.

LayerHow it duplicatesGuard
Tool callClient or model calls the purchase tool twiceidempotency_key argument, stable across retries
Order rowTwo inserts for the same intentUnique index on the key, upsert that returns the existing row
PaymentTwo Checkout Sessions or two PaymentIntentsSame key passed as Stripe's idempotency key
WebhookStripe redelivers an event, or two event types both trigger fulfilmentDedupe on event ID; one event type owns fulfilment
FulfilmentWorker retries a provider call that actually succeededOrder's key passed to the provider; atomic status transition

The checklist: nine steps

1. Accept an idempotency key on every purchase tool

Add an optional idempotency_key string to the input schema of every tool that creates an order, charges a saved card or requests a refund. Say in the description what it does: "Pass the same key when retrying this purchase. A repeated key returns the original order instead of creating a new one." Models follow instructions in tool descriptions, so this is how the agent learns to reuse the key.

2. Derive the key from the purchase, not the call

The most common mistake is generating a random UUID inside the tool handler. That key is new on every call, so a retry looks like a new purchase. The key must be identical on every attempt at the same purchase. There are two workable sources:

import { createHash } from 'node:crypto';

// Same inputs, same key: a retry maps onto the original order.
function purchaseKey(sessionId, productId, recipient, amountCents) {
  return createHash('sha256')
    .update([sessionId, productId, recipient, amountCents].join(':'))
    .digest('hex');
}

A derived key has a cost: a person who really wants two identical gift cards in one session gets one. Handle that with an explicit quantity, or a purchase_note field the agent changes for a deliberate repeat. Don't put raw email addresses in the key itself. Stripe's docs advise against sensitive data in idempotency keys, which is why the example hashes them.

3. Enforce it with a unique index and an upsert

Checking "does an order with this key exist?" and then inserting is a race. Two concurrent retries both pass the check. Let the database decide:

CREATE UNIQUE INDEX idx_orders_idempotency
  ON orders (buyer_email, product_id, idempotency_key)
  WHERE idempotency_key IS NOT NULL;

INSERT INTO orders (...) VALUES (...)
ON CONFLICT (buyer_email, product_id, idempotency_key)
  WHERE idempotency_key IS NOT NULL
DO UPDATE SET updated_at = now()
RETURNING *;

This is the shape of cartapi's orders table. The DO UPDATE exists so that RETURNING gives back the original row on a repeat, rather than nothing.

4. Pass the same key to Stripe

Creating the Checkout Session or PaymentIntent is a second write that can be duplicated on its own. Pass the order's key as the request's idempotency key. Stripe's idempotent requests reference describes three behaviours worth knowing:

Because of the 24-hour window, Stripe's key is a second line of defence, not your only one. The unique index in step 3 has no expiry.

5. Pass the order's key to the fulfilment provider

Fulfilment workers retry too. A provider call can succeed on their side and still time out on yours. Most digital-goods APIs have a field for this. Use the order's key, not a new one per attempt. In cartapi's adapters, the same order key goes out as Reloadly's customIdentifier for top-ups and gift cards, as an Idempotency-Key header where the eSIM provider accepts one, and as the transaction ID for another. Where a provider has no idempotency field at all, record the attempt before calling it and look the order up by your reference before retrying.

6. Deduplicate webhooks by event ID, and watch for NULLs

Stripe can deliver the same event more than once. Store each event's ID under a unique constraint before processing, and skip events you've already seen. One trap: if the unique index spans several columns and one of them can be NULL (for example a provider_id that's empty for Stripe's own events), PostgreSQL won't treat two rows as duplicates. Its unique-index docs say null values aren't considered equal by default. Use NULLS NOT DISTINCT, a non-null sentinel value, or an index on the event ID alone.

7. Let one event type own fulfilment

A hosted Checkout payment produces more than one event, for example checkout.session.completed and payment_intent.succeeded. If both handlers call "fulfil order", they can race. Pick one owner per payment path. Make the others record state only.

8. Make the status transition atomic

"Read the order, check it isn't delivered, then fulfil" has the same race as step 3. Claim the order in one statement, and fulfil only if you won:

UPDATE orders SET status = 'provisioning'
WHERE id = $1 AND status = 'paid'
RETURNING id;   -- no row back: another worker already claimed it

9. Return the original result, then set the annotation

On a repeated key, return the same order ID and the same checkout URL or delivery payload as the first call, not an error. The agent can then tell the user "here's the link again" instead of "something went wrong". Only after steps 1 to 8 hold, set annotations: { idempotentHint: true, destructiveHint: false } on the tool. Search and status tools should carry readOnlyHint: true.

Hosted checkout links soften the problem

If your purchase tool only creates a checkout link that the person opens and pays, a duplicate tool call costs much less. A retry produces a second unpaid session. The person pays one, and the other expires. That's one reason consent-first checkout is a good default for agents: the human's click is the step that actually moves money, so it's naturally performed once.

Off-session payments change that. When an agent charges a saved card inside a pre-approved limit, as in an AI agent spending limit setup, there's no human click to absorb the retry. Every call is a real charge, and steps 1 to 4 become mandatory. Spending caps limit how much a retry loop can spend, but they don't replace an idempotency key. A cap stops the tenth duplicate, not the second.

Where cartapi stands today

Being specific, from the current source:

If you're building your own server, the Stripe Checkout MCP server guide covers the session-creation side that step 4 plugs into.

Test it before an agent does

Related guides

Frequently asked questions

Does MCP have built-in idempotency for tool calls?

No. tools/call carries a name and arguments, and idempotentHint is only a hint that clients shouldn't trust from untrusted servers. The server has to accept and enforce a key itself.

Should the agent or the server generate the idempotency key?

Whoever knows the purchase intent: the agent or orchestrator, or a server-side hash of stable fields. A fresh random key per call protects nothing.

Is setting idempotentHint to true enough?

No. The MCP schema says annotations aren't guaranteed to describe behaviour. Set it only when the server actually deduplicates.

How long does Stripe remember an idempotency key?

For API v1, keys can be pruned once they're at least 24 hours old, and a reused key after that creates a new request. Keep your own unique constraint as well.

If my tool only returns a checkout link, do I still need idempotency?

Less urgently: a retry creates an extra unpaid session, not a charge. You still need webhook dedupe and atomic fulfilment. Off-session charges need keys on every call.

Try it

The cartapi docs list the REST endpoints, including POST /v1/checkout/session. To see the agent side, add cartapi from the install page and ask your assistant to find an eSIM or a gift card. Nothing is charged until you pay on the checkout page.

About the author

Roc Chow

Roc Chow builds cartapi, the commerce layer for AI agents, and runs . The cartapi behaviour described here comes from its checkout, fulfilment and MCP source code as of the publish date.

LinkedIn · · cartapi.io