← cartapi.io blog

How to add Stripe Checkout to an MCP server

Published 2026-11-10 · Last updated 2026-11-10 · 9 min read · engineering
TL;DR

Add one tool that creates a Stripe Checkout Session server-side and returns its URL. The agent hands that URL to the human, the human pays on Stripe's page, and a signed webhook marks the order paid and fulfils it. Add a second tool so the agent can read the order status. Never accept card data in a tool argument. The rest is the details that bite in production: idempotency, expiry, webhook dedupe, and manual capture for goods fraudsters like.

To add Stripe Checkout to an MCP server, expose a get_checkout_link tool that creates an order and a Checkout Session and returns the session URL, then fulfil the order from a verified checkout.session.completed webhook. The agent never charges anything. It produces a link that a human chooses to pay. This guide walks through that build using simplified code from cartapi's production MCP server, which sells eSIMs, mobile top-ups, and gift cards this way.

The shape: three tools and a webhook

A commerce MCP server needs surprisingly little surface:

  1. A search tool (search_gift_cards, search_esim_plans, ...) that returns products with stable IDs. Read-only.
  2. get_checkout_link(product_id, buyer_email), which writes an order, creates a Checkout Session, and returns { order_id, checkout_url, expires_at }.
  3. get_order_status(order_id), which returns the order's status and, once fulfilled, the delivery payload (a code, a QR, a reference).
  4. A Stripe webhook endpoint on your server (not an MCP tool) that moves orders from pending to paid to fulfilled.

What's deliberately missing is any tool that takes a card number or charges a saved card on the agent's say-so. The reasoning is in Consent-first checkout: the model's context can be prompt-injected, so whatever the model can call, an attacker's text can try to call too. The tool list is the trust surface.

The MCP tools specification backs this up. It says there should always be "a human in the loop with the ability to deny tool invocations," and that clients should prompt for confirmation on sensitive operations. It also says the protocol doesn't mandate any particular interaction model. So you can't count on every client showing a confirmation dialog. A hosted checkout page puts the human's yes inside the payment itself, whichever client is on the other end.

Step 1: define the checkout tool so the model uses it correctly

Tool descriptions are prompts. Say what the tool returns and what the agent must do with it, because the model reads the description to decide what happens next. A trimmed version of ours:

{
  name: 'get_checkout_link',
  description:
    'Buy a SPECIFIC product UUID (from a search tool). Returns a Stripe ' +
    'checkout URL for the human to pay. Hand the URL to the user; do not ' +
    'visit it. Only call after the user has explicitly agreed to buy.',
  inputSchema: {
    type: 'object',
    properties: {
      product_id:  { type: 'string', description: 'UUID from a search tool' },
      buyer_email: { type: 'string', description: 'Where the receipt and delivery go' },
    },
    required: ['product_id', 'buyer_email'],
  },
}

We repeat the consent rule in the server's MCP instructions too ("never call a checkout tool without the user's explicit go-ahead"). Belt and braces: the description is seen at call time, the instructions at connect time.

Keep the arguments to what the server can't look up itself. Price, currency, and product name come from your database by product_id, never from the model. If the agent could pass amount, a hallucination or an injection could change what the human is charged.

Step 2: write the order, then create the Checkout Session

Create your own order row first, so every Stripe object can point back to it through metadata.order_id. Simplified from cartapi's checkout service:

const product = await products.getById(input.product_id);
if (!product) throw new CheckoutError('product_not_found', '...');

const order = await orders.create({
  product_id: product.id,
  buyer_email: input.buyer_email,
  amount_cents: product.retail_price_cents,   // from the DB, not the model
  currency: product.currency,
  idempotency_key: input.idempotency_key,
});

const session = await stripe.checkout.sessions.create(
  {
    mode: 'payment',
    customer_email: input.buyer_email,
    line_items: [{
      quantity: 1,
      price_data: {
        currency: product.currency.toLowerCase(),
        unit_amount: product.retail_price_cents,
        product_data: { name: product.name },
      },
    }],
    metadata: { order_id: order.id, product_id: product.id },
    payment_method_options: { card: { request_three_d_secure: 'any' } },
    success_url: `${API_BASE_URL}/v1/orders/${order.id}?session={CHECKOUT_SESSION_ID}`,
    cancel_url: `${API_BASE_URL}/v1/checkout/canceled`,
  },
  { idempotencyKey: input.idempotency_key },
);

await orders.attachStripeIds(order.id, session.id);
return {
  order_id: order.id,
  checkout_url: session.url,
  expires_at: new Date(session.expires_at * 1000).toISOString(),
};

Three choices in there are worth explaining.

Inline price_data instead of Stripe Prices

Digital-goods catalogs change constantly (ours re-syncs from providers every few hours). Creating a Stripe Price per SKU means keeping two catalogs in sync. Inline price_data lets your database stay the single source of truth.

Idempotency: decide what "the same request" means

Stripe's idempotencyKey stops a network retry from creating two sessions. The harder question is what counts as the same request in an agent conversation. Our MCP handler generates a fresh key on every tool call. So if the model calls the tool twice, it gets two sessions, and that's acceptable because an unpaid session charges nothing and expires on its own. If your goods are scarce (event tickets, limited stock), derive the key from something stable instead, like conversation ID plus product ID, so a retrying agent gets the same URL back. The REST API takes the key from the client's Idempotency-Key header, and a unique index on the order table enforces it.

Expiry

By default a Checkout Session expires 24 hours after it's created, and Stripe's expires_at parameter accepts anything from 30 minutes to 24 hours. Agent conversations end up in logs, transcripts, and shared screenshots. If your users usually pay within minutes, a shorter expiry shrinks what a leaked link is worth. Return expires_at to the agent so it can tell the human how long the link lasts.

Step 3: fulfil from a verified webhook, once

The success redirect is for the human. The webhook is for the money. Fulfil only from the webhook, because the redirect can be skipped, replayed, or never load.

app.post('/v1/webhooks/stripe', async (req, reply) => {
  let event;
  try {
    event = stripe.webhooks.constructEvent(
      req.rawBody, req.headers['stripe-signature'], STRIPE_WEBHOOK_SECRET);
  } catch {
    return reply.code(400).send({ error: 'bad_signature' });
  }

  // Stripe can deliver an event more than once. Record event.id first.
  if (!(await webhookEvents.recordOnce(event.id, event.type))) return reply.send({ ok: true });

  switch (event.type) {
    case 'checkout.session.completed': {
      const orderId = event.data.object.metadata.order_id;
      await settleIfHeld(orderId, event.data.object.payment_intent); // step 4
      await fulfil(orderId);
      break;
    }
    case 'payment_intent.payment_failed':
      await orders.markFailed(/* ... */);
      break;
  }
  return reply.send({ ok: true });
});

Two details that are easy to get wrong:

Step 4: manual capture for goods you might need to refuse

Some orders can only be judged after the buyer has entered a card. Gift cards are the classic case: they're a common way to cash out stolen cards. cartapi sells gift cards only cross-border, so a buyer whose card was issued in the gift card's own country is declined. But the card's country isn't known until the buyer types it into Stripe.

The fix is to authorize first and decide in the webhook:

// at session creation, for gift cards only
...(isGiftCard(product) && {
  payment_method_types: ['card'],
  payment_intent_data: { capture_method: 'manual', metadata: { order_id: order.id } },
}),

// in the webhook
const pi = await stripe.paymentIntents.retrieve(piId, { expand: ['latest_charge'] });
if (pi.status === 'requires_capture') {
  const cardCountry = pi.latest_charge.payment_method_details.card.country;
  if (cardCountry === product.metadata.country_code) {
    await stripe.paymentIntents.cancel(piId);   // hold released, nothing to refund
    await orders.markBlocked(orderId);
    return;
  }
  await stripe.paymentIntents.capture(piId);
}

Stripe's guide to placing a hold says online card authorizations typically stay valid for 7 days, so an automated check that runs in seconds has plenty of room. A refused buyer is never charged, which is cleaner than charging and refunding. We also restrict these sessions to payment_method_types: ['card'], because 3D Secure is requested through the card options, and wallet-funded payments can skip that path.

If you take this route, ignore payment_intent.succeeded for manual-capture intents, or you'll fulfil twice: once on capture in the session handler and again when the success event arrives.

Step 5: return errors the agent can act on

Agents recover well from structured errors and badly from stack traces. Throw typed errors in the service and turn them into JSON in the tool handler:

} catch (err) {
  if (err instanceof CheckoutError) {
    return jsonReply({ error: err.code, message: err.message, detail: err.detail });
  }
  return jsonReply({ error: 'tool_failed', message: err.message });
}

Codes like product_not_found, provider_inactive, or buyer_email_required let the model search again, pick another SKU, or ask the human for the missing field, instead of telling the user "something went wrong".

Step 6: let the agent close the loop

get_order_status reads the order row that the webhook keeps current and returns the delivery payload once it exists. The flow from the human's side:

  1. "Buy me a €25 Netflix Spain card for my sister." The agent searches and confirms the price.
  2. The human says yes. The agent calls get_checkout_link and shows the URL.
  3. The human pays on Stripe and lands on the success page.
  4. "Done?" The agent calls get_order_status and reports "fulfilled, code sent to your email".

Pre-launch checklist

CheckWhy
No tool accepts card data, a stored payment method, or an amountWhatever the model can pass, an injection can pass
Price and currency come from your DB by product IDThe model can't change what the human is charged
Tool description and server instructions say "hand the URL over, only after explicit consent"The model reads descriptions to decide its next step
metadata.order_id on the session (and the PaymentIntent if you use manual capture)Every webhook maps back to one order
Idempotency key policy decided (per call, or per conversation and product)Agent retries are normal, not exceptional
expires_at set deliberately and returned to the agentLinks leak into transcripts
Webhook verifies the signature over the raw body and dedupes by event.idStripe retries deliveries
Fulfilment is idempotent at the providerA repeated fulfil must not buy twice upstream
Manual capture for goods you may need to refuseRefusing before capture means no refund and no chargeback
Typed error codes returned as JSONLets the agent recover on its own

Beyond click-per-purchase

One click per purchase is the right default, but it's tedious for small repeat buys like a $5 top-up every week. The next step is a pre-authorized spend policy: the human saves a card once and sets a ceiling (per transaction, per time window, lifetime, plus allowed categories and countries). The agent then presents a token instead of a URL. cartapi implements this as consent envelopes on the same get_checkout_link tool, and it's conceptually close to what ACP and Stripe's Shared Payment Tokens standardize. For how those protocols fit together, see ACP vs MCP vs A2A. Who carries tax, refunds, and chargebacks once agents are buying is covered in Merchant of record for AI-agent purchases.

Or skip the build

If what your agent needs to sell is eSIMs, mobile top-ups, or gift cards, cartapi already is this server, with Stripe as merchant of record, so you don't hold the payment relationship. Point your client at it:

claude mcp add --transport http cartapi https://mcp.cartapi.io/mcp

Tool reference is in the docs, client setup on the install page, and the wider field of commerce MCP servers in MCP servers for e-commerce.

Frequently asked questions

How do I add payments to an MCP server?

Expose a tool that creates an order and a Stripe Checkout Session server-side and returns the URL. The human pays on Stripe. A signed checkout.session.completed webhook marks the order paid and fulfils it, and a status tool lets the agent report back.

Should an MCP tool ever accept card details?

No. Tool arguments pass through the model's context, which can be prompt-injected and is often logged. Card entry belongs on a hosted payment page.

How long does a Stripe Checkout URL stay valid?

24 hours by default. expires_at accepts 30 minutes to 24 hours. Shorter is safer for links that end up in chat transcripts.

Does MCP require human approval for tool calls?

The spec says there should always be a human able to deny tool invocations, but it doesn't mandate how clients do it. Don't rely on the client's dialog alone for payments. A hosted checkout makes approval part of the payment.

When should I use manual capture?

When you may need to refuse an order based on data you only get at payment, like card country. Authorize, check in the webhook, then capture or cancel. Online card holds typically last 7 days.

How does the agent know the purchase completed?

A get_order_status tool that reads the order row the webhook updates. Point success_url at an order status page for the human.

About the author

Roc Chow

Roc Chow builds cartapi, the commerce layer for AI agents, and runs . The code here is simplified from cartapi's checkout service, MCP handler, and Stripe webhook. Stripe and MCP behaviour is quoted from their docs, linked above.

LinkedIn · · cartapi.io