Charging for an MCP server used to mean the same machinery as any SaaS API: accounts, API keys, a billing provider, invoices, and a dashboard nobody asked for. The x402 protocol removes almost all of it. Your server answers an unpaid tool call with HTTP 402 Payment Required and a machine-readable price. The calling agent pays in stablecoins, retries with proof of payment, and gets its result. No signup, no API key, no card on file, settlement in about two seconds for a fraction of a cent in fees.

This is no longer a fringe crypto experiment. Coinbase reports the protocol has processed roughly 165 million transactions across 69,000 active agents, with a median price of $0.028 per call (as of April 2026, per Coinbase's x402 ecosystem reporting). In the first two weeks of July 2026, Cloudflare announced a Monetization Gateway that charges for web pages, APIs, and MCP tools at its edge, and AWS shipped an equivalent Monetize action in AWS WAF for CloudFront. When the two largest edge networks ship the same payment protocol within a fortnight, the direction is set.

This guide is the end-to-end version nobody has written: what x402 actually is at the wire level, how payment relates to MCP authentication (they are different questions, and conflating them causes real security bugs), which services are worth charging for with evidence from today's per-call API market, and a complete self-hosted implementation in Rust, from 402 response to settled USDC, on testnet first. The quick version:

  1. Serve your MCP server over Streamable HTTP.
  2. Keep tools/list free; gate tools/call on priced tools behind an x402 middleware.
  3. Return 402 with a PaymentRequirements body (price, asset, network, your wallet address).
  4. Verify and settle the returned payment through a facilitator (hosted or self-run).
  5. Start on Base Sepolia testnet USDC; switch one config value for mainnet.

Everything below expands those five steps with working detail.

Why would AI agents pay for tools?

The economic argument for per-call payment is not that crypto is fashionable. It is that the existing monetisation models for APIs assume a human is in the loop, and agents break that assumption in specific, observable ways.

A subscription requires someone to visit a pricing page, create an account, enter card details, and manage a plan. An API key requires the same, plus secret distribution to wherever the agent runs. Both are provisioning steps that happen before the work, on a human timescale, for a vendor the human predicted the agent would need. But agents discover needs mid-task. An agent researching a market hits a bot wall and needs one page fetched through a residential proxy. An agent triaging a mailbox needs 40 email addresses verified, once, this afternoon. No procurement process is coming to rescue either of those calls. The agent either pays at the point of use or goes without.

That is the gap x402 fills. Payment happens inside the request-response cycle, at machine speed, with no account anywhere. The x402 specification describes the goal as making payment a first-class part of HTTP, and the design holds to it: one extra round trip, two extra headers, and money moves.

Three properties make stablecoin rails the practical substrate rather than cards or bank transfers:

  • Settlement speed. USDC on Base settles in roughly two seconds. Card authorisation is comparably fast, but card settlement is days away and reversible for months.
  • Fee floor. Interchange makes sub-dollar card payments uneconomic; a $0.01 charge loses money on fees. On-chain transfer fees on Base run well under a tenth of a cent, so a $0.005 price can still carry margin.
  • No chargebacks. A settled transfer is final. For a seller of machine-readable output, this removes the entire fraud-dispute apparatus.

There is also a demand-side signal worth taking seriously. The metered API economy already proves agents' operators will pay per call: search APIs clear millions of requests daily at $0.30 to $1.00 per thousand, scraping APIs charge around a cent a page, document parsers charge per page processed. Those markets grew up with API keys because that was the only rail available. x402 is the same commercial model with the provisioning friction removed, which is why the earliest adoption is concentrated in exactly those categories (more on this in the ideas section below).

Who is actually buying today?

Averages hide the shape of demand, so break the 69,000 active agents into the buyer populations a seller can actually target. The observable clusters, from ecosystem reporting and the composition of what is listed in the discovery indexes: research and data-gathering agents (the largest population, buying search, scrape, and extraction calls in bursts); trading and DeFi agents (early adopters for obvious reasons, buying market data and execution-adjacent services, and notable because their operators are entirely unfazed by wallets); developer-tool agents (CI-attached and IDE-attached, buying execution sandboxes, review services, and test infrastructure); and a long tail of workflow agents doing enrichment, verification, and document processing inside business processes. Consumer agents buying on humans' behalf are conspicuously not yet a meaningful x402 population; their purchases route through the card-network programmes described below.

Two properties of these populations matter commercially. They are operator-concentrated: thousands of agents often trace back to one platform or one team's fleet, so a single operator's allowlist decision can be a third of your volume, which cuts both ways and argues for the relationship-building that pure protocol thinking ignores. And they are budgeted, not price-sensitive in the retail sense: an agent does not haggle, it either fits your price inside its envelope or skips you, which is why the budgeting patterns later in this guide double as market research about your own headroom.

Where x402 sits in the agentic payments landscape

x402 is one protocol in a suddenly crowded field, and a seller should know the neighbours, because buyers will ask and because the boundaries explain what x402 is for. The card networks and the big processors all shipped agentic payment programmes across 2025-26: Visa's Intelligent Commerce and Mastercard's Agent Pay tokenise card credentials for agent use, Stripe's Agentic Commerce Protocol (with OpenAI) structures agent checkout at merchants, and Google's AP2 (Agent Payments Protocol) defines signed mandates that prove a human authorised an agent's purchase across card, bank, and stablecoin rails. PayPal, Skyfire, and a shelf of startups fill the gaps between.

The map becomes simple once you sort by what is being bought. The card-network programmes and AP2 target agent-assisted human commerce: an agent buying flights or groceries for a person, where the hard problems are mandates, consumer protection, refunds, and merchant acceptance, and where transaction sizes justify card economics. x402 targets machine-to-machine resource purchases: an agent buying compute, data, or an API call from another machine, where the hard problems are latency, sub-cent fees, and zero-signup access, and where a card-shaped dispute process would cost more than the transaction. The protocols are complementary rather than competing (AP2 explicitly lists x402 as a supported settlement method for its crypto rail), and the practical division for you as a builder: if you are selling tool calls, x402 is the rail; if your agent is buying sneakers, it is not.

The nearest true predecessor is worth a sentence for the pattern it proves: L402, a Lightning-Network-based 402 scheme from the Bitcoin ecosystem, demonstrated the challenge-response design years earlier but never escaped its niche, partly because Lightning liquidity management is a hobby in itself. x402's bet is that stablecoins on cheap L2s remove exactly that operational burden, and the adoption numbers above suggest the bet is landing.

Be equally clear about what x402 does not solve. It does not create demand for a tool nobody wants. It does not replace enterprise procurement for five-figure contracts. And a paying agent still needs a funded wallet, which today means a developer or platform provisioned it. The near-term buyers of paid MCP calls are agents operated by developers and companies, not consumers. Price and build accordingly.

How does HTTP 402 and the x402 protocol work?

HTTP 402 has been a curiosity for three decades. RFC 9110 section 15.5.3 says, in full, that the code "is reserved for future use". The original HTTP/1.1 authors expected digital cash schemes to arrive; they did not, and 402 sat unused while 401 (authentication) and 403 (authorisation) did all the work. Stripe and Shopify return 402 when a charge fails, GitHub returns it at paid limits, but none of those define a payment protocol. x402 does.

The four-step flow

The protocol is a challenge-response cycle layered on ordinary HTTP:

 Agent (buyer)                Server (seller)              Facilitator            Base L2
      |                             |                           |                    |
      |--- 1. POST /mcp tools/call ->|                           |                    |
      |                             |                           |                    |
      |<-- 2. 402 Payment Required --|                           |                    |
      |    PaymentRequired body:    |                           |                    |
      |    accepts:[{scheme,network,|                           |                    |
      |    amount,asset,payTo,...}] |                           |                    |
      |                             |                           |                    |
      | 3. sign EIP-3009            |                           |                    |
      |    transferWithAuthorization|                           |                    |
      |                             |                           |                    |
      |--- 4. retry + payment hdr -->|                           |                    |
      |                             |--- 5. POST /verify ------->|                    |
      |                             |<-- {isValid, payer} -------|                    |
      |                             |--- 6. POST /settle ------->|                    |
      |                             |                           |-- submit transfer ->|
      |                             |<-- {success, transaction} -|<--- confirmed -----|
      |                             |                           |                    |
      |<-- 7. 200 + tool result ----|                           |                    |
      |    + settlement response hdr|                           |                    |

Walk the steps once slowly, because every implementation decision later hangs off one of them.

Step 2, the 402 response, carries a JSON body the spec calls PaymentRequired. Its core is an accepts array of PaymentRequirements objects, each describing one way to pay:

{
  "x402Version": 2,
  "error": "payment required",
  "accepts": [
    {
      "scheme": "exact",
      "network": "eip155:84532",
      "amount": "10000",
      "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
      "payTo": "0x209693Bc6afc0C5328bA36FaF03C514EF312287C",
      "maxTimeoutSeconds": 60,
      "extra": { "name": "USDC", "version": "2" }
    }
  ]
}

Read the fields carefully. scheme names the payment mechanism; exact (pay a fixed amount) is the one in production use. network is a CAIP-2 chain identifier: eip155:8453 is Base mainnet, eip155:84532 is Base Sepolia testnet, and Solana, Avalanche, Stellar, and Aptos identifiers also appear in the wild. amount is in the asset's atomic units, so with USDC's six decimals, "10000" means $0.01. asset is the token contract address, payTo is the seller's receiving address, and maxTimeoutSeconds bounds how long the offer stands.

Step 3, the client's signature, is where the design gets quietly clever. On EVM networks the exact scheme uses EIP-3009 transferWithAuthorization, a USDC contract feature that lets the token holder sign an authorisation off-chain that anyone may submit on-chain. The buying agent never spends gas and never touches the chain; it produces a signature. The PaymentPayload it sends back looks like this:

{
  "x402Version": 2,
  "accepted": {
    "scheme": "exact",
    "network": "eip155:84532",
    "amount": "10000",
    "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
    "payTo": "0x209693Bc6afc0C5328bA36FaF03C514EF312287C"
  },
  "payload": {
    "signature": "0x2d6a7588d6acca505cbf0d9a4a227e0c52c6c34008c8e8986a1283259764173608a2ce6496642e377d6da8dbbf5836e9bd15092f9ecab05ded3d6293af148b571c",
    "authorization": {
      "from": "0x857b06519E91e3A54538791bDbb0E22373e36b66",
      "to": "0x209693Bc6afc0C5328bA36FaF03C514EF312287C",
      "value": "10000",
      "validAfter": "1740672089",
      "validBefore": "1740672154",
      "nonce": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f13480"
    }
  }
}

The validAfter/validBefore window and the single-use nonce are the replay protections; the security section covers what happens when servers ignore them.

One wire-level trap before you write any code: header naming. The x402 v2 core specification deliberately delegates header names to per-transport specs, and two conventions coexist in shipping software. Version 1 and most current SDKs (including Coinbase's CDP docs) send the payment payload base64-encoded in an X-PAYMENT request header and return settlement details in X-PAYMENT-RESPONSE. Newer v2 transport language uses PAYMENT-SIGNATURE and PAYMENT-RESPONSE. Interoperability failures between a v1-convention client and a v2-convention server present as a 402 loop that never resolves. Pin your SDK versions on both sides and confirm which header they emit before debugging anything else. No published tutorial mentions this; half the "x402 doesn't work" threads on the topic trace back to it.

Steps 5 and 6, verify and settle, belong to the facilitator, a service that saves the seller from running blockchain infrastructure. The facilitator API is two endpoints. POST /verify checks the signature, the authorisation window, the amount, and the payer's balance, entirely off-chain, and returns {"isValid": true, "payer": "0x857b..."}. POST /settle submits the authorisation to the token contract and returns {"success": true, "transaction": "0x1f4a...", "network": "eip155:84532", "payer": "0x857b..."} once confirmed. The seller's server makes two HTTP calls and never holds a private key for anything except its own receiving address, which can be a cold wallet.

Step 7's receipt deserves a moment, because it is the artifact both sides keep. The settlement response (returned to the buyer in a response header, logged by the seller) contains the transaction hash of the on-chain transfer, and that hash is a pointer into a public, append-only record that neither party controls. The buyer can prove it paid: the transfer is visible to anyone at that hash, amount and destination included. The seller can prove it was paid, to an auditor, a tax authority, or a disputing customer, without trusting its own logs. What the receipt does not prove is service delivery; x402 deliberately stops at settlement, and "you took my money and returned garbage" remains a reputation problem rather than a protocol problem. That boundary is the right one (encoding service quality on-chain is a research programme, not a payments feature), but be clear-eyed that the receipt answers "did money move?" with cryptographic finality and answers "was it worth it?" not at all.

You choose a facilitator the way you choose a payment processor. The Coinbase CDP facilitator is the default: fee-free for USDC on Base, roughly two-second settlement, and it performs compliance screening on payers. Alternatives exist for other networks and jurisdictions (Pieverse for BNB Chain, AsterPay for SEPA-adjacent euro flows under MiCA, MERX for TRON), and, importantly for anyone with self-hosting requirements, you can run your own: the x402-rs project ships a facilitator binary, covered in the implementation sections. A hosted facilitator sees your traffic metadata and can throttle or drop you; a self-hosted one is yours, at the cost of operating RPC access to the chain and keeping a gas wallet funded for settlement submissions.

Where did x402 come from, and who governs it?

The protocol's short history matters for one practical reason: version churn is live, and knowing the timeline tells you which documents to trust. Coinbase published the original x402 in May 2025 as a company project. Adoption grew fast enough that governance moved to an independent x402 Foundation (announced September 2025), with the spec co-developed in the open across the coinbase/x402 and x402-foundation/x402 repositories. Version 2 of the specification landed in early 2026 and generalised the design in three directions: CAIP-2 network identifiers replaced bare chain names (so "base-sepolia" became "eip155:84532"), the scheme system was formalised so non-EVM chains could define their own payment mechanics, and transport bindings were split out of the core spec.

That last change is the source of the header-naming trap above, and it is worth understanding rather than just working around. The v2 core spec defines what a payment payload is; separate transport specifications define how it travels over HTTP, over MCP, or over A2A (the agent-to-agent protocol). The HTTP transport spec was still converging on final header names while most production SDKs continued shipping the v1 convention. This is normal young-protocol behaviour, the same way early HTTP/2 implementations disagreed on upgrade mechanics, and the practical rule stands: the SDK's behaviour, not the spec's prose, is what interoperates.

Scale, for calibration, since numbers in this space age quickly: Coinbase reported roughly $50 million in cumulative settled volume by April 2026, with the 165 million transactions and 69,000 active agents cited earlier. Median transaction value of $0.028 against that volume tells you the protocol is being used exactly as designed, for machine-scale micropurchases, not as a general payments rail wearing a developer costume.

What payment schemes exist beyond exact?

Everything in this guide uses the exact scheme: a fixed amount, known before the call, transferred in full. It is the only scheme with broad production deployment, and for tool pricing it is usually what you want. But the scheme field exists precisely because fixed-price-per-call does not fit every service, and two other shapes are worth knowing about.

The spec's extension surface anticipates up-to schemes (authorise a maximum, settle actual usage), which map to metered services like sandboxed execution where cost is unknowable upfront. Until those mature, the shipping workaround is the one from the architecture section: define atomic billable actions and price those. The second shape is non-EVM schemes. Solana's scheme replaces EIP-3009 signatures with Solana transaction semantics, and Stellar and Aptos bindings exist in the SDK tree. As a seller you opt into schemes per PaymentRequirements entry; the accepts array exists so you can offer several at once (USDC on Base and USDC on Solana, say) and let the client pick whichever its wallet supports. Each entry you add widens your addressable buyers at the cost of another settlement path to monitor, and two entries (Base for the EVM world, Solana for the rest) covers the overwhelming majority of paying agents today.

One scheme-adjacent detail affects your revenue reconciliation. Because exact on EVM rides EIP-3009's transferWithAuthorization, the on-chain transfer is initiated by the facilitator, not the buyer. What you see at your payTo address is a stream of inbound USDC transfers whose on-chain sender is the token contract's authorisation machinery, with the true payer recoverable from the settlement records and transaction logs. Accounting tools that assume "sender address = customer" need the facilitator's settlement export instead.

How do agents discover priced endpoints?

A paid tool nobody can find earns nothing, and x402 has grown a discovery layer worth plugging into on day one. The pattern is called the Bazaar in ecosystem terminology: crawlers and registries probe HTTP endpoints, collect 402 challenges (which are, usefully, self-describing advertisements), and index the resulting catalogue of priced services with their prices, assets, and networks. Coinbase operates one such index; independent ones exist, and the awesome-x402 list tracks the moving set.

Getting indexed costs you nothing beyond being reachable: your 402 response is your listing. What you control is its quality. The optional fields in PaymentRequirements and the surrounding PaymentRequired body (a human-readable error string, resource descriptions, your tool's description in the free tools/list) are what an index displays next to your price. Write them like the one line of ad copy they are. A challenge that says "error": "payment required" and one that says "error": "geocode_address costs $0.002/call: street address in, WGS84 coordinates out, 40ms median" occupy the same bytes-on-wire budget and very different positions in an agent's tool-selection reasoning.

For MCP specifically, discovery is two-layer: the x402 Bazaar finds your endpoint, and MCP registries (the official registry, plus community directories) find your server. List in both. The MCP registries currently carry no price metadata, which is another reason the price-in-description convention from the architecture section matters: it is the only place an MCP-side directory shows your pricing at all.

Is the 402 payload public?

Yes, definitionally. Anyone who requests a gated resource without payment receives your full price list: amounts, assets, and your receiving address. Treat that as a feature with consequences. Agents can comparison-shop programmatically, which is the point. Competitors read your prices, which you cannot prevent. And your payTo address's transaction history is public on-chain, so anyone patient can estimate your revenue. If that transparency is unacceptable, rotate receiving addresses periodically or route through an address per product line; both are config changes, not protocol changes.

How do MCP authentication and payment relate?

This is the section to get right before writing code, because the two mechanisms answer different questions and the failure mode of confusing them is not aesthetic, it is a security bug or a business-model bug.

Authentication answers "who is calling, and what may they access?" The MCP authorization specification standardises this for HTTP transports on OAuth 2.1: the MCP server acts as an OAuth resource server, clients obtain tokens from an authorization server (with dynamic client registration recommended, since agents cannot fill in signup forms), and every request carries a bearer token the server validates. API keys and mTLS are the informal alternatives in wide use.

It is worth being concrete about what the OAuth side actually involves for an MCP server, because the payment comparison only makes sense against the real thing, not a hand-wave. Under the June 2025 authorization spec, an HTTP-served MCP server that requires auth must behave as an OAuth 2.1 resource server: it advertises its authorization server via protected-resource metadata (RFC 9728), the client discovers endpoints through authorization-server metadata (RFC 8414), registers itself dynamically (RFC 7591, recommended because agents cannot fill in a developer-portal form), runs an authorization-code flow with PKCE, and then presents bearer tokens that the server validates for issuer, audience, expiry, and scope on every request. That is five RFCs, a token lifecycle, and a dependency on an authorization server, all to establish and re-establish identity.

Now count the infrastructure x402 requires for settlement: a keypair and two HTTP calls to a facilitator. The asymmetry is the entire reason anonymous-paid access is suddenly viable: the marginal cost of accepting a new paying stranger dropped from "operate an identity relationship" to approximately zero. But the asymmetry also explains why payment cannot replace auth for anything identity-shaped. A bearer token binds a request to a subject with a revocation path, an expiry, and scopes granted by a human somewhere. A payment binds a request to nothing but itself.

Payment answers "has this specific call been paid for?" A verified x402 payment tells you an on-chain transfer of a specific amount to your address was authorised for this request. It tells you nothing else. Not who the payer is in any legal sense, not whether they are the same caller as five minutes ago (wallets are free to create), not what they should be allowed to access beyond what the payment bought.

Because the questions are orthogonal, a server sits somewhere on a two-by-two grid, and each quadrant is a legitimate business model:

No payment required Payment required (x402)
No authentication Open access. Public documentation, free-tier tools, discovery endpoints (tools/list). Rate-limit by IP; expect scraping. Anonymous pay-per-call. The x402-native quadrant: no signup, wallet signature replaces the account. Ideal for one-shot agent traffic. Sybil-resistant by price, not identity.
Authentication (OAuth 2.1 / API key) Subscription or seat model. Access is the entitlement; calls are free once you are in. The classic SaaS API. Authenticated metered billing. Identity for access control and audit, payment for usage. Enterprise-friendly: per-tenant policy plus per-call settlement, or x402 as overage beyond a subscription allowance.

Three of those quadrants existed before x402. The interesting one is the top-right: anonymous-but-paid. Until now, anonymous access and monetised access were mutually exclusive, because the only way to bill was to know who to bill. x402 decouples them. The wallet signature is a bearer instrument: whoever holds the key pays, and payment itself is the credential. That single property is what makes mid-task agent purchases possible, because the agent does not need an identity relationship with your service, only money.

The decoupling cuts both ways, and here are the rules that keep it safe:

  • Payment is not authorisation. A settled $0.01 does not entitle the payer to admin endpoints, another tenant's data, or ten calls. It entitles them to exactly the one resource at the one price in the requirements it satisfied. Scope every payment check to the specific route and price, and never let a payment header influence an OAuth scope decision.
  • Authentication is not payment. Do not fall into billing by trust: verifying a token and then invoicing later reintroduces the receivables and fraud problems x402 removed. If a call should be paid, gate it on settlement, even for authenticated callers.
  • Layer them by caller class, not globally. The pattern both Cloudflare's gateway rules and self-hosted middleware support: authenticated subscribers skip the 402 (their plan covers usage), anonymous callers pay per call. One route, two monetisation paths, and the OAuth check runs first so the payment branch only sees strangers.
  • API keys are the pragmatic middle, not a third principle. Plenty of MCP servers will keep issuing keys, and that is fine as long as you file them correctly: a key is a weak identity credential (it answers "who" with "whoever holds this string") and often a billing pointer, so a keyed-plus-x402 server is just the bottom-right quadrant with lighter identity. What keys cannot do is the top-right quadrant; there is no key without a signup, and the signup is the thing being removed. If you already run a keyed API, the incremental x402 lane does not disturb it.
  • Audit them separately. Log token-validation events and settlement events as distinct records. When an incident review asks "who accessed this?", an x402 payer address is an answer of a very different quality to an OIDC subject. Conflate them in your logs and the difference disappears exactly when you need it.

A worked example of layering auth and payment

Abstract rules earn their keep when they survive contact with a concrete policy, so here is one, for the geocoding server the implementation sections build. The business wants three caller classes on one tool: internal services (free, unlimited), subscribers (free within a plan, identified by OAuth), and strangers (pay per call). The decision sequence per tools/call:

1. Bearer token present?
   ├─ yes → validate (issuer, audience, expiry, scope)
   │        ├─ valid, scope covers tool  → execute, FREE (log: subject, plan)
   │        └─ invalid/expired           → 401 (do NOT fall through to 402;
   │                                       a subscriber with a stale token
   │                                       must refresh, not silently pay)
   └─ no  → payment header present?
            ├─ no  → 402 + PaymentRequirements
            └─ yes → verify + settle via facilitator
                     ├─ settled → execute, PAID (log: payer address, tx hash)
                     └─ failed  → 402 + error detail

Two subtleties in that tree repay attention. The 401-not-402 branch for invalid tokens is deliberate: a caller who claimed an identity gets identity semantics, including the failure mode. Only callers who never claimed one enter the payment path. And the two execute branches log different things, which is the audit-separation rule made concrete: the subscription branch produces a record about a subject, the payment branch a record about a settlement. Six months later, "which tenant made this call?" and "which transfers made up Tuesday's revenue?" are answered from different logs because they were different questions at request time.

The same tree also shows where each quadrant's abuse pressure lands. The free-internal branch is protected by network boundaries and token issuance, the subscriber branch by plan-level rate limits keyed to the OAuth subject, and the anonymous branch needs neither: its rate limiter is the price. If a stranger wants to make ten thousand calls an hour, that is not an attack, that is your best customer.

One more relationship worth naming: 401 versus 402 ordering. A request can fail both checks. Convention in shipping implementations, including Cloudflare's origin-integration mode, is that identity is evaluated first (401 if you require auth and it is absent) and price second (402 for the unauthenticated-but-payable path). If your server can serve a caller in either the subscription or the pay-per-call quadrant, evaluate the token first and fall through to the 402 challenge, never the reverse: a 402-first flow trains paying users that payment can substitute for login, which is precisely the confusion rule one exists to prevent.

There is no formal spec yet unifying OAuth scopes with payment requirements (a scope that means "may buy up to $5/day", say). The MCP community discussion is active but young. Until one lands, the composition above, OAuth for access, x402 for settlement, checked in that order, is the state of the art, and it is entirely implementable today.

What do developers need to know about stablecoin rails?

You can ship a paid MCP server while knowing almost nothing about blockchains, because the facilitator absorbs the chain interaction. But "almost nothing" is not nothing, and the gaps bite at predictable moments: choosing a network, holding keys, and moving revenue to a bank account. This section is the minimum viable understanding.

The asset is USDC, in practice. x402 is asset-agnostic in principle, but the shipping ecosystem (Coinbase's facilitator, Cloudflare's gateway, the AWS WAF action) settles USDC, Circle's dollar-pegged stablecoin. USDC has six decimal places, which is why every amount in this guide is an integer of millionths of a dollar: 10000 atomic units is one cent. Prices below $0.000001 cannot be represented, which sets a floor on how micro your micropayments can be.

The network is an L2, for fee reasons. Base, Coinbase's Ethereum layer-2, is where the volume is: transfer fees run well under $0.001 and confirmation is a couple of seconds. Mainnet Ethereum fees would eat any sub-dollar price. The AWS integration also settles USDC on Solana, and the x402 spec's CAIP-2 network identifiers keep the protocol chain-neutral, but if you are choosing today, Base mainnet (eip155:8453) for production and Base Sepolia (eip155:84532) for testing is the default pairing the entire tooling ecosystem assumes.

Testnet money is free, which is why you develop there. Base Sepolia runs a real USDC contract at 0x036CbD53842c5426634e7929541eC2318f3dCF7e (Circle's published testnet deployment) whose tokens cost nothing: Circle's faucet dispenses testnet USDC, and the Coinbase CDP and Alchemy faucets cover the small amount of Sepolia ETH a buyer-side wallet needs for anything beyond signing. The verify/settle flow is byte-identical to mainnet apart from the network field. Every code sample in this guide runs on Base Sepolia, and the switch to real money is one config value plus a mainnet facilitator URL.

Your receiving key is the crown jewel; treat the rest as disposable. The seller side of x402 holds exactly one secret that matters: the private key of the payTo address. Nothing in the request path needs it (payments arrive by the buyer's signature, not yours), so keep it in cold storage and put only the address in config. Buyer-side agents are the opposite: their wallets must sign per-call, so the key is hot by definition. Fund agent wallets like petty cash, small amounts, topped up on a schedule, monitored for drain.

The life of one cent

To make the moving parts concrete, trace a single $0.01 payment through the whole stack, naming every party that touches it. An agent's wallet on Base holds $25 of USDC, topped up last Tuesday from its operator's treasury. Your server's 402 quotes amount: "10000". The agent's client library builds an EIP-3009 authorisation (from: agent's address, to: your address, value: 10000, a 65-second validity window, a random nonce) and signs it with the agent's key, an operation that happens in memory in microseconds and touches no network. The payload travels to your server inside a request header. Your gate checks conformance, then hands it to the facilitator, whose /verify reads Base (via its RPC provider) to confirm balance and nonce freshness: still no money has moved. Your gate calls /settle; the facilitator wraps the authorisation in an actual Base transaction, pays roughly $0.0003 of gas from its own gas wallet, and submits it. A Base sequencer includes it in a block about two seconds later; the USDC contract verifies the same signature on-chain, decrements the agent's balance by 10000 units, increments yours. The facilitator sees the confirmation, returns the transaction hash, your gate executes the geocode and returns coordinates plus the receipt. Total wall-clock: under three seconds. Parties who could have stopped it: the agent's spend guard, your conformance check, the facilitator, and the chain's own signature verification, in that order, each one a narrower and better-tested gate than the last. Parties who ever held custody of the cent: none; it moved from the agent's address to yours in one atomic contract operation. That last property, no intermediary balance anywhere in the flow, is the structural difference from every card and PSP flow you have operated, and most of the operational simplicity in the sections that follow descends from it.

Wallets: what sellers and buyers actually hold

"Wallet" compresses several different arrangements, and the right one differs by side of the trade.

On the seller side, remember that x402's exact scheme never requires you to sign anything at request time. The payTo address is just a destination. That gives you the full menu: a self-custody hardware wallet (maximum sovereignty, you handle backup and inheritance), a multi-signature contract wallet like Safe (no single key can move funds, right answer once revenue matters), or a custodial exchange deposit address (Coinbase or similar holds the key, off-ramping is trivial, and you have reintroduced a counterparty). A defensible progression: start custodial while daily revenue is coffee money, move to a multisig when it is payroll money, and never let the migration be urgent, because changing payTo is one config line and the old address keeps working for stragglers holding cached 402 offers.

The buyer side is structurally harder, and if you operate agents as well as selling to them you own both problems. A paying agent's key must be online and signing without a human, which makes it a hot wallet by definition, and the mitigations are the ones from the client section plus one architectural option worth knowing: server-side key custody with policy. Instead of the key living in the agent's environment, the agent calls a signing service (Coinbase CDP wallets, Turnkey, and Privy are the established options; MetaMask's mcp-x402 does the local equivalent) that enforces per-key policies (spend caps, allowlisted destinations, velocity limits) before producing a signature. The agent is compromised? The blast radius is the policy, not the balance. For fleets of agents, per-agent sub-wallets funded from a treasury on a schedule give you the same blast-radius arithmetic plus per-agent cost attribution for free, since the chain is itself the metering.

One EIP-3009 detail rounds out the picture, because it surprises people pleasantly: the buyer's wallet needs no ETH, ever. Ordinary ERC-20 transfers cost gas, paid by the sender in the chain's native token, which historically meant every agent wallet needed two balances to manage. transferWithAuthorization moves gas payment to whoever submits the transaction, which in x402 is the facilitator. Agent wallets hold USDC and nothing else; the faucet ETH mentioned earlier is only for development conveniences like deploying test contracts. Fleet funding therefore reduces to one stablecoin transfer per agent per top-up, which is the kind of operational simplification that decides whether a thousand-agent deployment is a script or a team.

The regulatory ground is firmer than the vibes suggest. The reflexive objection to building a business on stablecoin receipts is regulatory uncertainty, and it is two years stale. The US GENIUS Act (signed July 2025) created a federal framework for payment stablecoins, with reserve, audit, and issuer-licensing requirements that USDC was substantially built to anticipate; the EU's MiCA regime has had stablecoins (e-money tokens, in its vocabulary) under supervision since mid-2024, and Circle was the first major issuer licensed under it. None of that makes your tax or licensing questions disappear (see below), but it does change their character: accepting a regulated dollar instrument for services rendered is a known shape to a competent accountant in 2026, not frontier territory. The genuinely unsettled edges are elsewhere: whether high-volume facilitation triggers money-transmission analysis (a facilitator question more than a seller question), and how jurisdictions treat agent-initiated purchases for consumer-protection purposes (an agent-buys-sneakers question, not a machine-buys-API-calls one).

Off-ramping is a solved but regulated problem. USDC redeems 1:1 for dollars through Circle or Coinbase, and both offer business accounts with bank withdrawal. Revenue on-chain is still revenue for tax purposes; jurisdictions differ on whether it is recognised at receipt or at conversion, so keep the settlement log (the facilitator returns a transaction hash per sale, which is an audit trail most businesses would envy) and ask an accountant, not a blog post, this guide included.

What is actually worth selling?

Protocol mechanics are necessary but not sufficient. The other half of monetising an MCP server is choosing a service agents will actually pay for, and here the evidence base is unusually good, because the metered API market has been price-testing agent-shaped demand for years. Every category below is anchored to a real product's published per-call price, which is the strongest willingness-to-pay signal available.

Two selection principles emerge from the data before the table. First, x402's unlock is no-signup access, so the strongest fits are high-frequency, low-ticket primitives an agent needs mid-task and cannot have pre-provisioned keys for: search, scrape, verify, geocode, parse. Second, licensing is the hidden margin killer: categories where you resell someone else's data (contact enrichment, real-time market data, SEO metrics) leave you a thin spread, while categories where you own the compute and the output (OCR, code review, PDF rendering, compliance checks) keep the margin at home.

# Service What the agent buys Market price anchor (source, Jul 2026) Suggested x402 price Demand / Margin / Moat (1-5)
1 Web scraping and structured extraction Clean markdown/JSON from any URL, including bot-protected pages Firecrawl ~$0.83-1.66 per 1k pages (pricing); Tavily $0.008/credit $0.01-0.05/page 5 / 4 / 3
2 Anti-bot fetch and CAPTCHA solving A successful fetch through residential proxies and challenge walls 2Captcha $1.00 per 1k reCAPTCHA, $0.90 per 1k Turnstile (pricing) $0.005-0.02/solve 5 / 3 / 3
3 Agent-native web search Grounding/RAG retrieval, the most-called agent primitive Serper $0.30-1.00 per 1k queries; DataForSEO SERP $0.60 per 1k (pricing) $0.002-0.01/query 5 / 3 / 2
4 Document OCR and structured parsing PDF/scan/invoice to structured JSON AWS Textract $1.50 per 1k pages basic, $50 per 1k forms (pricing); Mistral OCR ~$2 per 1k $0.01-0.05/page 4 / 5 / 3
5 Company and person enrichment Domain or name to firmographics and contacts People Data Labs $0.01-0.10/record $0.02-0.10/record 4 / 3 / 3
6 Email verification Deliverability check before a send or CRM write ZeroBounce/Kickbox ~$0.008/check; MyEmailVerifier $0.0025 $0.003-0.008/check 4 / 4 / 2
7 Sandboxed code execution Run untrusted code, return outputs E2B $0.0504/vCPU-hr, per-second billing (pricing) $0.01-0.05/execution 5 / 3 / 4
8 Deep code and security review A diff or repo in, structured findings out No per-call analog; Snyk/Semgrep are seat-based. Pricing whitespace $0.10-0.50/review 4 / 4 / 4
9 Reranking and relevance scoring Rerank retrieved chunks for RAG precision Cohere Rerank $2.00 per 1M tokens (pricing) $0.001-0.005/call 4 / 3 / 2
10 Audio transcription A call or podcast URL to text with speakers AssemblyAI from $0.15/hr (pricing) $0.003-0.006/min 3 / 3 / 2
11 Image and asset generation Marketing/UI images on demand fal.ai $0.003-0.15/image; Replicate $0.003-0.04 $0.01-0.08/image 3 / 2 / 2
12 SEO, keyword, and rank data Volumes, SERP positions, backlinks DataForSEO Labs $0.0006-0.0012/task (pricing) $0.005-0.02/query 3 / 3 / 2
13 Geocoding and places Address to coordinates and back Google Geocoding $5 per 1k after free tier (pricing) $0.001-0.004/lookup 3 / 4 / 2
14 Financial and market data Quotes, fundamentals for research agents Free tiers at Finnhub/Twelve Data; real-time is licence-walled $0.005-0.05/query 3 / 3 / 3
15 Browser automation Drive a real browser through a flow behind JS or login Browser-minutes at ~$0.005-0.02 (Browserbase et al.) $0.02-0.10/action 4 / 3 / 3
16 Contract and legal-clause analysis Obligations, risks, key terms from an agreement Google Document AI contract parsing $10-30 per 1k pages $0.05-0.30/contract 3 / 4 / 3
17 Compliance and policy checks Text/dataset/model card against a regulation, with citations No per-call analog; GRC tooling is enterprise SaaS. Whitespace $0.02-0.20/check 3 / 4 / 4
18 PDF and document generation Structured data to a styled PDF or report DocRaptor/Api2Pdf ~$0.01-0.05/doc typical $0.003-0.02/doc 3 / 4 / 2

A few readings of the table that matter more than any single row.

The high-frequency primitives (rows 1-6, 13) are volume businesses. Individually tiny prices, enormous call counts, low defensibility. You win them with reliability and latency, not features, and the anti-bot rows (1, 2, 15) carry a real operational moat because proxy pools and challenge evasion decay without constant upkeep. If you cannot commit to that upkeep, do not enter those rows.

The LLM-powered judgment services (rows 8, 16, 17) are the pricing whitespace. Nothing sells code review, contract analysis, or regulatory checking per call today, because the incumbents package them as seats and platforms. Their marginal cost is model inference ($0.05-0.50 for large-context calls), so the margin story depends on prompt and harness quality, which is also the moat: a review harness with proprietary rulesets is hard to clone from the outside. These rows are where a small team can charge $0.10-0.50 per call rather than fractions of a cent.

The resale rows (5, 12, 14) look easy and are not. The data behind them is licensed, and the licence is the moat of whoever you buy from. Margins compress to the spread, and terms of service often prohibit exactly the redistribution an MCP tool performs. Check the licence before the business plan.

Session-shaped services (rows 7, 15) fit per-call billing awkwardly. A sandbox or browser session is metered in seconds, but x402's exact scheme wants an atomic unit. The shipping pattern is to bill per action or per completed result rather than per second, and to set maxTimeoutSeconds so a stalled session does not hold an open offer.

Three build profiles, three different businesses

The table's rows sort into three build profiles, and knowing which one you are entering matters more than the specific row, because the profile determines what you will actually spend your time on.

Profile one: infrastructure arbitrage (rows 1-3, 13, 15). You operate unglamorous infrastructure (proxy pools, headless browser fleets, a self-hosted Nominatim, SERP crawlers) and sell access to it one call at a time. The margin comes from utilisation: the Nominatim instance costs the same per month whether it serves one query or a million, so every marginal call is nearly pure margin once the fixed cost clears. The work is operations, and the competitive risk is a bigger operator with better utilisation undercutting you. What defends the anti-bot rows specifically is that the fixed cost is partly labour: challenge evasion decays weekly as bot-detection vendors update, and the maintenance burden is a moat precisely because it never ends. Enter these rows if you would run this infrastructure anyway, or if you enjoy the cat-and-mouse; the price floor otherwise grinds you down.

Profile two: model resale with a wrapper (rows 9-11, and honestly much of 10). You call someone else's model, mark it up, and compete on convenience. These rows look attractive because they ship in a weekend, and that is exactly the problem: everyone's weekend is the same length. fal.ai's own per-image prices are visible in the table; an x402 wrapper above them is paying for the no-signup convenience only, and that premium compresses as x402 adoption spreads to the upstream providers themselves. Coinbase's own tooling already lets model providers charge natively. Treat this profile as a learning exercise or a bridge, not a business.

Profile three: judgment services (rows 8, 16, 17, and 4 at the structured-extraction end). You sell an opinion a model produced under your harness: this diff has these vulnerabilities, this contract has these obligations, this dataset fails this regulation in these places. The buyer cannot evaluate the output's quality before paying, which inverts the economics of profile one: trust, not utilisation, is the scarce asset. That is why these rows sustain prices two orders of magnitude above the primitives ($0.10-0.50 against $0.002-0.008) and why they suit a team that already has domain expertise to encode. The moat is the harness: the rulesets, the eval suite proving the output's quality, and the accumulated corpus of judged cases. Notice these are exactly the assets that do not appear in your API surface, so they cannot be cloned by observing it.

A dynamic worth watching across all three profiles: x402 changes who your competitor is. In the API-key world, switching costs (integration work, contract, key provisioning) protected mediocre incumbents. A paying agent has no switching cost at all; it re-reads the price list every task. That is brutal for undifferentiated sellers and excellent for new entrants with a genuinely better price or product, which, at the moment you are reading a guide like this, is more likely to be you than the incumbent.

Validating demand before you build

The table de-risks category selection, not your product, and x402's economics allow a validation step that key-based APIs cannot offer cheaply: sell the service before the service is good. Concretely: stand up the thinnest correct version of the tool (the weekend build), price it at the low end of the suggested band, list it in the registries, and watch three numbers for a month. Challenge volume (how many 402s you issue) measures discovery: if nobody probes you, your problem is distribution, and building a better tool will not fix it. Conversion (challenges that become settled payments) measures offer quality at that price for whoever arrived. And repeat-payer rate (distinct payer addresses seen more than once, which your settlement log gives you for free) measures whether the thing was worth what it cost, which is the only number of the three that predicts a business. A hundred settled calls from twelve returning payers is a stronger signal than ten thousand free-tier signups ever were, because every data point cost the buyer money.

The failure modes of the month are equally informative. High challenges, low conversion: price above envelope-fit, or a client-compatibility break (check the troubleshooting section before concluding anything about demand). Good conversion, no repeats: quality below the price; improve the tool, not the marketing. Nothing at all: distribution, per above. Each has a different fix, and none of them is "pivot", which is the diagnosis paralysis this little funnel exists to prevent.

If you want the shortest path to a working paid server for learning purposes, three rows have near-zero infrastructure and no licensing wall: geocoding on OpenStreetMap data (row 13), email verification via SMTP/MX probing (row 6), and PDF rendering (row 18). The implementation sections that follow use a geocoding tool as the worked example for exactly this reason, and the architecture transfers unchanged to whichever row you actually pursue.

Anatomy of the three starter builds

Since the three no-licence-wall rows are where most readers will start, here is each one at the next level of detail: what you actually operate, where the quality bar lives, and the trap each one hides.

The geocoder (row 13). You operate a Nominatim instance over an OpenStreetMap planet extract, refreshed on a schedule (weekly is fine to start; the diff-based updater makes daily cheap once you care). The tool surface is two tools: forward geocoding (address in, coordinates plus normalised address out) and reverse (coordinates in, address out), each priced identically because their costs are identical. The quality bar is match quality on messy input: the queries agents send are extracted from documents and chat, not typed into a form, so "10 Downing St London UK" and "downing street number 10" must both resolve, which means fronting Nominatim with a normalisation pass, and that pass is your differentiation. The trap is coverage asymmetry: OSM address data is superb in Germany and patchy in parts of the US suburbs and much of the global south; publish a coverage note before your buyers discover it for you, and consider returning a confidence field, because an agent can act on "low confidence" but not on a silently wrong rooftop.

The email verifier (row 6). You operate an SMTP-conversation engine: MX resolution, greylisting-aware connection handling, mailbox probing without sending, plus static layers (syntax, disposable-domain lists, role-account detection). The tool surface is one tool returning a verdict enum (deliverable, undeliverable, risky, unknown) plus evidence flags. The quality bar is the unknown rate: the big providers accept-all and catch-all configurations defeat naive probing, and your value over the $0.0025 incumbents is a lower unknown rate on exactly those domains. The trap is that outbound port-25 traffic from cloud IPs is itself treated as abuse: you need clean IP space, PTR records, and connection pacing, or the mail world blacklists your prober and your product degrades for everyone; this operational reputation-keeping is, like proxy upkeep, a moat with a cost.

The PDF renderer (row 18). You operate headless Chromium (or Typst, which is faster and lighter for template-shaped documents) behind a queue. The surface is one tool: structured payload plus template choice in, PDF out, with the output returned as a resource link rather than inline base64, because multi-megabyte tool results abuse the MCP transport. The quality bar is typographic: agents generate reports for humans to read, and the difference between "obviously generated" and "presentable" is fonts, page-break logic, and table handling. The trap is input-driven resource abuse: a payload that renders to ten thousand pages is a denial-of-service you invoiced $0.01 for, so cap pages, cap render time, and price by size tier. Of the three, this one most rewards the batch pattern from the transport section, since report generation is bursty.

Any of the three is a weekend to demo and a month to make good, and the month is the product. The x402 gate in front of them is identical, which is rather the point of the architecture that follows.

How should a paid MCP server be architected?

There are two architectural decisions that matter before any code: where the payment gate sits, and what stays free. Get these right and the payment layer is boring plumbing; get them wrong and you either leak paid compute or break agent discovery.

Where the payment gate sits

An MCP server over Streamable HTTP is, at the wire level, an HTTP endpoint receiving JSON-RPC. That gives you three places to enforce payment:

  1. Edge (managed gateway). Cloudflare's Monetization Gateway or the AWS WAF Monetize action intercepts unpaid requests before they reach your origin. Zero code changes, but coarse granularity: the edge sees URLs and verbs, not JSON-RPC method names, so per-tool pricing requires splitting tools across routes or waiting for gateway-side MCP awareness (Cloudflare has announced MCP-tool pricing rules; details are behind the waitlist).
  2. Middleware in the server process. An HTTP-layer middleware (Axum tower layer, Express middleware) wraps the MCP endpoint, inspects the JSON-RPC body, and issues 402 challenges for priced methods. This is the sweet spot for self-hosting: full per-tool control, one deployable artifact, and the pattern this guide implements.
  3. A separate billing proxy. A reverse proxy in front of one or many MCP servers (the pattern behind projects like mcp-billing-gateway and nginx-x402). Right when you operate several servers and want one billing point, at the cost of another moving part.

What stays free

The convention that has emerged across shipping paid MCP servers, and it is worth following because agent clients now expect it: reads and discovery are free; execution is paid. Concretely:

  • initialize, tools/list, resources/list, prompts/list: always free. An agent that cannot see your catalogue cannot decide to pay for it. This is your shop window.
  • tools/call on priced tools: gated behind 402.
  • Cheap or loss-leader tools can stay free within the same server; the gate is per-method-per-tool, not global.

Advertise prices in the tool metadata itself, not only in the 402 response. An agent planning a task reads tools/list and needs cost as an input to tool selection, before it commits to a call. The emerging convention is a price annotation in the tool's description or _meta field. It costs nothing and materially improves how often price-aware agents pick your tool:

{
  "name": "geocode_address",
  "description": "Resolve a street address to coordinates. Price: $0.002 per call (x402, USDC on Base).",
  "_meta": { "x402": { "amount": "2000", "asset": "USDC", "network": "eip155:8453" } },
  "inputSchema": { "type": "object", "properties": { "address": { "type": "string" } }, "required": ["address"] }
}

The multi-server pattern

One deployment shape deserves a note before the operational details, because several readers will be planning it: many tools, or many whole MCP servers, under one commercial roof, a private marketplace in effect. The architecture scales by making the gate a shared layer and the prices data. Concretely: one billing component (the reverse-proxy pattern from the list above, or a shared library every server links) owns the facilitator relationship, the idempotency store, and the settlement log; each server contributes rows to a price table (tool -> amount, asset, network, payTo) rather than embedding payment code; and payTo becomes a per-product column, which gives you per-product revenue attribution directly from the chain with no bookkeeping at all. The failure to avoid is the opposite arrangement, payment logic copy-pasted into each server, which guarantees the conformance checks drift apart, and drift in exactly the code that decides whether money is real is how one server in the fleet quietly serves free compute for a month. If the fleet is heterogeneous (some Rust, some TypeScript), the proxy pattern beats the shared library on those grounds alone.

Two operational notes complete the architecture. Settlement timing is a real choice: settle before executing the tool (no free work ever, but you charge even if your tool then errors) or after (you absorb the risk of settlement failure post-compute). Convention: settle-before for cheap fast tools, verify-before-settle-after for expensive ones, and always return the result only after settlement succeeds. Idempotency is on you: agents retry, and a retried request with a fresh payment is a double charge from the buyer's point of view. Key your execution on the payment nonce, cache the result briefly, and a retry with the same payment returns the cached result instead of executing twice.

How do you build the MCP server in Rust?

The implementation sections build one coherent thing: an MCP server exposing a geocode_address tool at $0.002 per call, served over Streamable HTTP, gated by x402, settling testnet USDC on Base Sepolia. Rust is the implementation language for two reasons beyond preference. The x402 Rust ecosystem is unusually complete (x402-rs ships server middleware, an auto-paying client, shared types, and a self-hostable facilitator, with x402-axum, x402-reqwest, and x402-types at version 2.0.2 on crates.io as of July 2026), and a single static binary with no runtime dependencies is the deployment shape self-hosters actually want. Nothing in the architecture is Rust-specific; the TypeScript equivalents (@x402/express and friends) map one-to-one.

A word on code provenance before the first snippet: the excerpts below are drawn from a companion implementation built alongside this guide and compile against the pinned versions shown. Where a snippet is simplified for the page, the simplification is called out. Versions matter here more than usual; the x402 crates moved from 1.x to 2.x in 2026 with breaking changes to the middleware API, so if you copy code into a project resolving different versions, expect to reconcile.

Project skeleton

[package]
name = "paid-geocoder-mcp"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
reqwest = { version = "0.12", features = ["json"] }
x402-axum = "2.0.2"
x402-types = "2.0.2"
tracing = "0.1"
tracing-subscriber = "0.3"

The server is deliberately SDK-light. MCP over Streamable HTTP is JSON-RPC 2.0 over a single POST endpoint, and for a server with a handful of tools, dispatching it by hand keeps every moving part visible, which is the point of a reference implementation. (The official Rust MCP SDK, rmcp, is the right choice once your tool count grows; the payment layer attaches the same way.)

JSON-RPC dispatch and the free surface

use axum::{routing::post, Json, Router};
use serde_json::{json, Value};

async fn mcp_handler(Json(req): Json<Value>) -> Json<Value> {
    let id = req.get("id").cloned().unwrap_or(Value::Null);
    match req.get("method").and_then(Value::as_str) {
        Some("initialize") => Json(json!({
            "jsonrpc": "2.0", "id": id,
            "result": {
                "protocolVersion": "2025-06-18",
                "capabilities": { "tools": {} },
                "serverInfo": { "name": "paid-geocoder", "version": "0.1.0" }
            }
        })),
        Some("tools/list") => Json(json!({
            "jsonrpc": "2.0", "id": id,
            "result": { "tools": [ {
                "name": "geocode_address",
                "description": "Resolve a street address to WGS84 coordinates. \
                                Price: $0.002 per call (x402, USDC).",
                "inputSchema": {
                    "type": "object",
                    "properties": { "address": { "type": "string" } },
                    "required": ["address"]
                }
            } ] }
        })),
        Some("tools/call") => handle_tool_call(id, &req).await,
        _ => Json(json!({
            "jsonrpc": "2.0", "id": id,
            "error": { "code": -32601, "message": "method not found" }
        })),
    }
}

Note what is absent: no payment logic in the handler. initialize and tools/list answer unconditionally, which keeps the discovery surface free per the architecture above. The tool implementation itself is equally payment-unaware:

async fn geocode(address: &str) -> Result<(f64, f64), String> {
    let url = format!(
        "https://nominatim.openstreetmap.org/search?q={}&format=json&limit=1",
        urlencoding::encode(address)
    );
    let client = reqwest::Client::builder()
        .user_agent("paid-geocoder-mcp/0.1 (contact: ops@example.com)")
        .build().map_err(|e| e.to_string())?;
    let results: Vec<Value> = client.get(&url).send().await
        .map_err(|e| e.to_string())?
        .json().await.map_err(|e| e.to_string())?;
    let hit = results.first().ok_or("no match")?;
    let lat = hit["lat"].as_str().and_then(|s| s.parse().ok()).ok_or("bad lat")?;
    let lon = hit["lon"].as_str().and_then(|s| s.parse().ok()).ok_or("bad lon")?;
    Ok((lat, lon))
}

Production note rather than legal footnote: Nominatim's public instance has a usage policy (roughly one request per second, attribution, no heavy use) that a commercial tool will outgrow immediately. Self-host Nominatim from OpenStreetMap data, which is precisely what makes geocoding a zero-licence-wall business in the ideas table, and the operational cost of that self-hosting is what your $0.002 per call is buying.

MCP transport details that interact with payment

Three Streamable-HTTP behaviours interact with the payment gate in ways that only surface once real MCP clients connect, and all three are cheaper to design for than to retrofit.

Sessions. Streamable HTTP lets a server issue a session ID during initialize (the Mcp-Session-Id header) that clients then attach to every request. The gate must be stateless with respect to it: payment attaches to calls, not sessions, so two calls in one session each pay, and a paid call in a fresh session is as good as one in an old session. The temptation to resist is session-scoped entitlements ("paid once, free for the session"), which quietly converts your per-call price into a per-session price at whatever call rate the client chooses. If you want bundle pricing, price a bundle explicitly (a tools/call that returns a batch) rather than letting session mechanics improvise one.

Streaming responses. MCP servers may answer a tools/call over server-sent events, streaming partial results before the final response. With settle-before-execution this is uncomplicated: payment completed before the first byte. With settle-after, streaming is a trap: you have shipped most of the value before the settlement step, and a buyer who disconnects mid-stream has consumed compute you now cannot charge for. Rule: streaming tools settle before execution, full stop. If the tool's latency makes pre-settlement painful (the two facilitator calls add roughly two seconds), stream a heartbeat during settlement rather than moving settlement after the stream.

Notifications and long-running tools. Tools that outlive the HTTP exchange (the request returns quickly, progress arrives via notifications, results via a later call) split the payment moment from the value moment. The pattern that works is a claim-check: the priced call is the submission (pay $0.10, receive a job token), polling is free, and the token is single-redemption keyed like a payment nonce. It reuses the idempotency machinery you already built, and it means a crashed client can resume its job without paying twice, which buyers notice and remember.

How do you add the x402 payment gate?

The gate is a tower layer wrapped around the MCP route. x402-axum provides the mechanics: it reads the payment header, calls the facilitator's /verify, optionally /settles, and produces the 402 challenge with your PaymentRequirements when payment is absent or invalid.

The straightforward case first, because it shows the library's intended grain. If your priced tool lived on its own HTTP route, gating it is four lines:

use x402_axum::X402Middleware;
use x402_types::{networks::USDC, price_tag::V1Eip155Exact};
use alloy_primitives::address;

let x402 = X402Middleware::new("https://facilitator.x402.rs");

let app = Router::new().route(
    "/tools/geocode",
    post(geocode_route_handler).layer(
        x402.with_price_tag(V1Eip155Exact::price_tag(
            address!("0x209693Bc6afc0C5328bA36FaF03C514EF312287C"),
            USDC::base_sepolia().parse("0.002").expect("valid amount"),
        ))
        .settle_before_execution(),
    ),
);

That snippet is real and sufficient for a plain paid HTTP API. An MCP server complicates it in one specific way: every method arrives at one endpoint, and only tools/call on priced tools should pay. The middleware cannot know that from the URL, so the composition is a thin body-inspecting layer in front of the same machinery:

use axum::{body::Body, extract::Request, middleware::Next, response::Response};
use http::StatusCode;

const PRICED_TOOLS: &[(&str, &str)] = &[("geocode_address", "2000")]; // atomic USDC units

async fn mcp_payment_gate(req: Request, next: Next) -> Result<Response, StatusCode> {
    let (parts, body) = req.into_parts();
    let bytes = axum::body::to_bytes(body, 64 * 1024).await
        .map_err(|_| StatusCode::PAYLOAD_TOO_LARGE)?;
    let rpc: Value = serde_json::from_slice(&bytes)
        .map_err(|_| StatusCode::BAD_REQUEST)?;

    let priced = rpc.get("method").and_then(Value::as_str) == Some("tools/call")
        && rpc.pointer("/params/name").and_then(Value::as_str)
            .map(|tool| PRICED_TOOLS.iter().any(|(name, _)| *name == tool))
            .unwrap_or(false);

    let req = Request::from_parts(parts, Body::from(bytes));
    if priced {
        // Delegate to the x402 verification path: absent/invalid payment
        // yields the 402 + PaymentRequirements response; valid payment is
        // verified and settled against the facilitator, then we fall through.
        verify_and_settle(req, next).await
    } else {
        Ok(next.run(req).await)
    }
}

verify_and_settle is where the two facilitator calls from the protocol section happen. With x402-axum doing the heavy lifting it is largely configuration; written out longhand (worth reading once even if you never hand-roll it) the sequence is:

  1. Read the payment header. Absent: respond 402 with the PaymentRequired JSON body for this tool's price. This is the challenge.
  2. Base64-decode and parse the PaymentPayload. Malformed: 402 again, with an error field saying why. Never 400; the buyer's client library treats 402 as "re-read the requirements and retry", which is the recovery you want.
  3. Check the payload's accepted block matches what you offered: same scheme, network, asset, payTo, and an amount equal to your price. Skipping this check is the classic vulnerability: a buyer who edits amount down and signs the smaller transfer will pass naive verification, because their signature is valid for the smaller amount.
  4. POST the payload and your requirements to the facilitator's /verify. isValid: false means a bad signature, an expired window, or an insufficient balance: 402.
  5. POST /settle (before or after execution, per your timing choice). Record the returned transaction hash against the request.
  6. Run the tool and return the result, adding the settlement response header so the buyer has its receipt.

Written as code, with the library types elided to keep the shape visible (the companion implementation carries the full version):

async fn verify_and_settle(req: Request, next: Next) -> Result<Response, StatusCode> {
    let price = requirements_for(&req); // this tool's PaymentRequirements

    // 1. Challenge if no payment attached.
    let Some(header) = req.headers().get("X-PAYMENT") else {
        return Ok(payment_required_response(&price, None));
    };

    // 2. Decode; malformed payloads get a 402 with a reason, not a 400.
    let payload: PaymentPayload = match decode_payment(header) {
        Ok(p) => p,
        Err(e) => return Ok(payment_required_response(&price, Some(e))),
    };

    // 3. Conformance: the payload must match what WE offered.
    if payload.accepted.scheme  != price.scheme
        || payload.accepted.network != price.network
        || payload.accepted.asset   != price.asset
        || payload.accepted.pay_to  != price.pay_to
        || payload.accepted.amount  != price.amount {
        return Ok(payment_required_response(&price, Some("offer mismatch".into())));
    }

    // 4. Idempotency: a nonce we have settled is a replay -> cached result.
    let nonce = payload.authorization_nonce();
    if let Some(cached) = REDEEMED.get(&nonce) {
        return Ok(cached.clone());
    }

    // 5. Facilitator verify (off-chain), then settle (on-chain).
    let v: VerifyResponse = facilitator_post("/verify", &payload, &price).await
        .map_err(|_| StatusCode::BAD_GATEWAY)?;
    if !v.is_valid {
        return Ok(payment_required_response(&price, v.invalid_reason));
    }
    let s: SettleResponse = facilitator_post("/settle", &payload, &price).await
        .map_err(|_| StatusCode::BAD_GATEWAY)?;
    if !s.success {
        return Ok(payment_required_response(&price, Some("settlement failed".into())));
    }

    // 6. Execute, attach the receipt, cache under the nonce.
    let mut resp = next.run(req).await;
    resp.headers_mut().insert("X-PAYMENT-RESPONSE", receipt_header(&s));
    REDEEMED.insert(nonce, resp.clone(), REDEMPTION_TTL);
    tracing::info!(payer = %s.payer, tx = %s.transaction, "settled");
    Ok(resp)
}

The error taxonomy embedded in that function is most of what separates a production gate from a demo. Three distinct failure families come out of it, and they must not be collapsed: buyer-fixable failures (no payment, malformed payload, offer mismatch, invalid signature, insufficient balance) return 402 with a reason, because the buyer's client library treats 402 as "re-read and retry" and anything else as fatal; seller-side failures (facilitator unreachable, settlement infrastructure down) return 502, because the buyer did nothing wrong and should not be told to pay differently; and replays return the cached success, because from the buyer's perspective a retry of a paid request is the same request. Map any of these to the wrong family and you either strand paying customers or hand out free compute.

Configuration for the two environments differs by exactly two values, which is the entire testnet-to-mainnet switch:

network = "eip155:84532"                     # Base Sepolia
facilitator = "https://facilitator.x402.rs"  # self-hostable, see below
pay_to = "0x209693Bc6afc0C5328bA36FaF03C514EF312287C"

# config.mainnet.toml
network = "eip155:8453"                      # Base mainnet
facilitator = "https://api.cdp.coinbase.com/platform/v2/x402"
pay_to = "0xYOUR_COLD_WALLET_ADDRESS"

What the facilitator actually checks

Treating /verify as a magic boolean invites both over-trust and redundant paranoia, so here is what a conforming facilitator establishes before saying isValid: true, and therefore what you may stop re-checking yourself. It recovers the signer from the EIP-712 signature and confirms it matches the authorisation's from address (signature authenticity); confirms the authorisation's fields match the payment requirements presented alongside it (its own conformance pass, which backs up rather than replaces yours, since only you know what you actually offered); checks the current time sits inside validAfter/validBefore; queries the token contract to confirm the from address holds at least value (balance sufficiency, the check you could not do without chain access); and confirms the nonce is unconsumed on-chain (protocol-level replay protection, distinct from your application-level idempotency cache, which exists to make retries succeed cheaply rather than to make double-spends fail). What /verify cannot promise is that the money will still be there at /settle time: the buyer could move it in the gap. That race is why /settle's success, not /verify's, is the moment you treat as paid, and why verify-then-execute-then-settle tools carry the residual risk the settlement-timing discussion priced in.

Knowing the division of labour also clarifies the failure semantics your gate maps to HTTP: isValid: false with a reason is buyer-fixable (402), a facilitator that cannot answer is your dependency problem (502), and a settle that returns success: false after a passing verify is almost always the balance race or a gas-side incident at the facilitator, which is why the runbook treats it as a page rather than a shrug.

Running your own facilitator

Every tutorial in circulation points the facilitator URL at a hosted service and stops. If you self-host your MCP server for sovereignty reasons, outsourcing the payment-verification step to a third party's availability and policy is a strange place to reintroduce a dependency. The x402-rs project ships a facilitator binary for exactly this: point it at a Base RPC endpoint (your own node or a provider), fund a gas wallet for settlement submissions, and set facilitator = "http://127.0.0.1:8402". You take on chain-infrastructure operations (RPC reliability, gas top-ups, reorg handling) in exchange for a payment path with no third party in it. For most sellers the hosted facilitator is the right default; for air-gapped-adjacent deployments and anyone whose compliance posture forbids traffic metadata sharing, the self-hosted option is the difference between adopting x402 and not.

Deploying the thing

The deployment story is mercifully ordinary, which is worth stating because newcomers assume blockchain adjacency implies exotic infrastructure. It does not. The build produces one static binary; the runtime needs are outbound HTTPS to a facilitator and whatever your tool itself requires. A complete production deployment is the binary, a config file, TLS, and a process supervisor:

FROM rust:1.88 AS build
WORKDIR /src
COPY . .
RUN cargo build --release

FROM gcr.io/distroless/cc-debian12
COPY --from=build /src/target/release/paid-geocoder-mcp /usr/local/bin/
COPY config.mainnet.toml /etc/geocoder/config.toml
EXPOSE 8080
ENTRYPOINT ["paid-geocoder-mcp", "--config", "/etc/geocoder/config.toml"]

Three deployment-time rules carry the payment-specific weight. TLS is not optional, terminated at your reverse proxy or in-process: a payment payload replayed off a plaintext capture is money, and a tampered 402 challenge is a price-manipulation attack, so an x402 endpoint on port 80 is negligence rather than laziness. The idempotency cache must survive what your deployment does: an in-process map is fine for one replica and wrong the moment you scale to two or roll a deploy mid-window, at which point it moves to Redis or your database, keyed by nonce, TTL'd past validBefore. And secrets hygiene is short but strict: the config carries no private keys (the payTo is an address), so the only secret in the deployment is whatever your tool itself needs, and if you find yourself mounting a wallet key into the server container, revisit the wallets section, because the design does not require it and the blast-radius table assumed you did not.

Capacity planning has one payment-specific wrinkle: the facilitator round trips add roughly two seconds of latency and one concurrent outbound connection per paid call in flight. For tools whose own execution is milliseconds (the geocoder), settlement dominates the request lifetime, so your concurrency budget is set by facilitator latency, not compute; size connection pools accordingly and the throughput math stays linear.

How does the paying agent side work?

Your server is only half the loop. Understanding the buyer makes you better at selling to it, and you need one anyway to test.

A paying client needs three things: a wallet (a keypair; on testnet, generated freely), testnet USDC in it (from Circle's faucet), and an HTTP client that understands the 402 dance. With x402-reqwest, the dance is invisible:

use x402_reqwest::PayingClient;

let signer: PrivateKeySigner = std::env::var("AGENT_WALLET_KEY")?.parse()?;
let client = PayingClient::builder(reqwest::Client::new(), signer)
    .max_amount(USDC::base_sepolia().parse("0.05")?)   // per-request ceiling
    .build();

// Retries with payment automatically on 402:
let resp = client.post("https://geocoder.example.com/mcp")
    .json(&json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "geocode_address",
                    "arguments": { "address": "10 Downing Street, London" } }
    }))
    .send().await?;

The max_amount ceiling is the line to notice. An auto-paying client will pay whatever the server asks up to its configured limit, and a malicious or misconfigured server asks for more. Every x402 client library exposes a spend guard; no agent should ever run without one, and platform-level allowances (per-task budgets, daily caps, allowlisted payTo addresses) belong in whatever harness operates the agent. The official MCP-with-x402 tutorial's example client auto-approves every payment, which is fine on a testnet and negligent advice beyond it.

For an agent built on an LLM tool-use loop rather than raw HTTP, the wiring is the same but lives in the MCP client layer: MetaMask's mcp-x402 wraps wallet signing as an MCP server so any MCP-capable agent can construct payment headers, and Cloudflare's Agents SDK bakes the paying client into its MCP connector. From the model's point of view nothing changes; a priced tool call simply takes one round trip longer the first time.

Budgeting patterns for agent operators

If you operate paying agents at any scale, per-request ceilings are necessary but not sufficient, and the patterns that hold up in practice are worth recording because your buyers will be using them, which makes them your pricing constraints.

The unit that matters is the task budget, not the request budget. An agent researching a market might legitimately spend $4 across two hundred calls to six different sellers; the same agent spending $4 on one call is probably being exploited. Harnesses that work give each task an envelope (say $5), decrement it per settlement, and hard-stop with a human escalation when it empties. Within the envelope, per-seller sublimits catch the pathological cases: a single payTo address absorbing 80% of a task budget is either your most valuable tool or a pricing bug, and the harness cannot tell, so it asks.

Below that, three mechanical rules from operators who learned them expensively. Log every settlement receipt with the task that spent it, or cost attribution across a fleet becomes archaeology; the receipts arrive in the X-PAYMENT-RESPONSE header and cost nothing to keep. Alert on spend velocity, not just totals: a wallet that spends its weekly budget in an hour is the compromise signal that matters, and it fires while there is still budget left to save. And treat new sellers like new dependencies: an allowlist of known payTo addresses with a manual step for additions is annoying for exactly the mid-task discovery x402 enables, so most operators run it in log-only mode, but the log is what makes the post-incident question "when did we start paying this address?" answerable.

For you as the seller, the takeaway is the pricing constraint mentioned earlier, now with its mechanism visible: your price does not just need to be worth it, it needs to fit inside the envelope arithmetic of a task that calls you among many others. A $0.50 review tool inside a $5 task envelope gets called ten times at most; the same tool at $0.15 fits thirty calls and probably earns more. Envelope-fit is a demand curve you can reason about before you have any customers.

Which raises the question your product decisions hang on: how does the agent decide to pay? Today, one of three ways. The operator pre-authorises a budget and the client pays silently within it (the dominant mode, and why your prices must sit comfortably inside typical default budgets). The client surfaces the price and the model reasons about it (needs the price in tools/list, per the architecture section, because mid-call 402 surprises abort tasks). Or a human approves each payment, which no one sustains beyond a demo. Design for the first two: price within budgets, advertise in metadata, and make the first free thing the agent sees (your tool description) state clearly what the paid thing returns.

Appendix on the wire: a full annotated transcript

Everything above described the flow; here it is as bytes, the reference to debug against. A client calls the priced geocoding tool with no payment (transcript trimmed to the relevant headers; the convention shown is the v1/SDK header naming discussed earlier):

POST /mcp HTTP/1.1
Host: geocoder.example.com
Content-Type: application/json
Mcp-Session-Id: 3f9a2c…

{"jsonrpc":"2.0","id":7,"method":"tools/call",
 "params":{"name":"geocode_address","arguments":{"address":"Alexanderplatz 1, Berlin"}}}

The gate finds no payment header and challenges:

HTTP/1.1 402 Payment Required
Content-Type: application/json

{"x402Version":2,
 "error":"geocode_address costs $0.002/call: address in, WGS84 out. No payment header received.",
 "accepts":[{"scheme":"exact","network":"eip155:84532","amount":"2000",
   "asset":"0x036CbD53842c5426634e7929541eC2318f3dCF7e",
   "payTo":"0x209693Bc6afc0C5328bA36FaF03C514EF312287C",
   "maxTimeoutSeconds":60,"extra":{"name":"USDC","version":"2"}}]}

The client's spend guard approves ($0.002 is under its ceiling), it signs the authorisation, and retries the identical JSON-RPC body with one added header (the base64 decodes to the PaymentPayload shown in the protocol section, here with value: "2000"):

POST /mcp HTTP/1.1
Host: geocoder.example.com
Content-Type: application/json
Mcp-Session-Id: 3f9a2c…
X-PAYMENT: eyJ4NDAyVmVyc2lvbiI6MiwiYWNjZXB0ZWQiOnsic2NoZW1lIjoiZXhhY3QiLCJuZXR3b3JrIj…

{"jsonrpc":"2.0","id":8,"method":"tools/call",
 "params":{"name":"geocode_address","arguments":{"address":"Alexanderplatz 1, Berlin"}}}

Roughly two and a half seconds later (conformance in microseconds, verify ~300ms, settle ~2s, the geocode itself ~40ms):

HTTP/1.1 200 OK
Content-Type: application/json
X-PAYMENT-RESPONSE: eyJzdWNjZXNzIjp0cnVlLCJ0cmFuc2FjdGlvbiI6IjB4MWY0YT…

{"jsonrpc":"2.0","id":8,
 "result":{"content":[{"type":"text",
   "text":"{\"lat\":52.5219,\"lon\":13.4132,\"display\":\"Alexanderplatz 1, 10178 Berlin\",\"confidence\":0.97}"}]}}

Five details in the transcript reward attention, because each is a place implementations diverge. The retried request keeps the same session but uses a fresh JSON-RPC id (7 then 8): the retry is a new request at the RPC layer, and servers keying idempotency on RPC ids instead of payment nonces break here. The challenge's error string is doing sales and support work simultaneously, per the discovery section. The amount in the challenge and the value inside the signed authorisation must match to the atomic unit; the conformance check compares them, and the transcript is where you eyeball it when they disagree. The settlement receipt rides a response header while the tool result rides the body, so intermediaries that strip unknown response headers destroy the buyer's receipt without touching the result, the mirror image of troubleshooting entry seven. And nothing anywhere in the exchange named the buyer: the entire commercial relationship, discovery to settlement to receipt, fits in two HTTP round trips between strangers, which is the whole thesis of this guide expressed as a transcript.

Should you use x402 or conventional metered billing?

Before committing to the implementation, one honest comparison, because x402 is not automatically the right monetisation for every MCP server, and the alternative is mature. Conventional metered billing (API keys plus Stripe usage-based billing or an equivalent) remains the default for APIs, and it beats x402 on several axes that matter to specific businesses.

Dimension x402 per-call API keys + metered billing (Stripe et al.)
Buyer onboarding None: wallet signature is the credential Signup, key issuance, card on file
Time to first paid call Seconds Minutes to days (human in the loop)
Viable price floor ~$0.001 (fee-limited) ~$0.50 invoice line practical floor; sub-cent only via aggregation
Settlement ~2s, final, no chargebacks Net-30-ish, reversible, dispute apparatus
Buyer identity None by default (add OAuth if needed) Always present (the account)
Recurring relationship Rebuilt per call Native (plans, tiers, invoices)
Enterprise procurement fit Poor alone (no invoice, no contract) Strong (POs, invoices, SOC 2 checkboxes)
Currency exposure Stablecoin custody + off-ramp None (fiat throughout)
Buyer-side requirement Funded wallet + x402 client HTTP client with a header

Read as a decision rather than a scorecard: x402 wins where the buyer is a stranger, the ticket is small, and the moment is now, which is precisely the agent-hits-a-wall-mid-task purchase this guide opened with. Metered billing wins where the buyer is a relationship: known customers, four-figure monthly spend, procurement departments, and anyone for whom "we pay invoices, we do not custody tokens" is a compliance position rather than a preference. The strongest sellers run both, and the quadrant architecture from the auth section is exactly how: OAuth-identified subscribers ride the billing relationship, anonymous x402 covers everyone else, and the x402 lane doubles as the zero-friction trial that feeds the subscription lane. If you must pick one first, pick the one your likeliest next hundred buyers can actually pay through; for tools marketed to autonomous agents that is x402, for tools sold to engineering managers it is still the invoice.

How do you test the full payment loop?

Payment code has a testing problem ordinary code does not: the interesting failures involve money, timing, and a third party, and none of those appear in unit tests. A test strategy that has caught real bugs in this stack has three tiers, in increasing order of realism and decreasing order of speed.

Tier one: the gate in isolation. Every branch of verify_and_settle is reachable with a hand-built payload and a mock facilitator, and this is where the conformance checks earn their tests. The cases that have caught real implementations out, and belong in any suite: a valid signature over a smaller amount than offered (must fail conformance, step 3); a payload whose network is the testnet twin of the offered mainnet (must fail); a nonce presented twice (second presentation must return the cached response and must not call the facilitator again, which the mock can assert); an expired validBefore (must produce a 402, and specifically one whose reason the client can act on); and a facilitator timeout (must be 502, not 402). None of these needs a chain.

A representative tier-one test, to fix the shape (the mock facilitator is an axum router answering /verify and /settle from a script of canned responses):

#[tokio::test]
async fn smaller_amount_with_valid_signature_is_rejected() {
    let (server, facilitator) = test_harness().await;
    facilitator.expect_no_calls(); // conformance must fail before verify

    let mut payment = signed_payment_for(&server.requirements(), &buyer_key());
    payment.accepted.amount = "1000".into();   // offered 2000, paying 1000
    re_sign(&mut payment, &buyer_key());       // signature is VALID for 1000

    let resp = server.tools_call("geocode_address", &payment).await;
    assert_eq!(resp.status(), 402);
    assert!(resp.error_reason().contains("offer mismatch"));
}

The expect_no_calls assertion is the subtle half: rejecting the underpayment is table stakes, but rejecting it without spending a facilitator round trip is what keeps your challenge path cheap enough to survive being hammered, and a test is the only thing that stops a refactor from quietly reordering those checks.

Tier two: real facilitator, testnet chain. Base Sepolia exists so this tier can run in CI. Generate a throwaway buyer wallet, fund it from Circle's faucet (programmatic faucets exist at Coinbase CDP and Alchemy for the gas side), point the client at your staging server with the testnet config, and assert the full loop: a tools/call with no budget fails at the client's spend guard, one within budget round-trips to a settled payment, and the USDC balance at your test payTo address increased by exactly the price. That last assertion, checked against the chain via any Base Sepolia RPC, is the one that catches config drift: a passing test that settles the wrong amount on the wrong network is worse than a failing one.

Tier three: simulated hostile traffic. Before mainnet, run a week of the traffic you do not want: replayed captures of paid requests, concurrent duplicate submissions of the same payment (a race your idempotency cache either wins or does not), challenge floods against the free surface at whatever rate your rate limiter claims to handle, and a client whose spend ceiling sits below your price (which should produce clean, budget-guard-shaped failures on the client, and no half-executed state on the server). The point of the week is less the pass/fail than the metrics shakedown: by the end you know what your 402-to-paid conversion, settlement latency, and replay-hit-rate dashboards look like under load, so mainnet anomalies have a baseline to be anomalous against.

A note on what not to bother with: mocking the chain itself. The facilitator boundary is the correct seam; below it you would be testing Circle's contract, which Circle tests. The one chain-level behaviour worth an occasional manual check is reorg handling, and on Base's sequencer model the practical exposure is small enough that the settle-response's confirmation is a reasonable line to trust.

Why is my client stuck in a 402 loop? (Troubleshooting)

Every x402 integration hits a variant of the same few failures, and they present identically from the outside (the client pays, or thinks it does, and the server challenges again, forever). In observed-frequency order:

  1. Header-convention mismatch. The client sends X-PAYMENT; the server reads PAYMENT-SIGNATURE, or vice versa. The server never sees a payment at all, so it re-challenges. Diagnose in one step: log header names on arrival. Fix by pinning SDK versions on both sides, per the protocol section.
  2. Network mismatch. The 402 offered eip155:8453; the client wallet is configured for eip155:84532 and signs a testnet payment. Conformance (or the facilitator) rejects it, the client sees another 402, and some client libraries retry the same wrong wallet indefinitely. The error string you return should name the expected network for exactly this case.
  3. Spend guard below price. The client's max_amount is under your price, so it never attaches payment and just re-requests. Server-side this is indistinguishable from a scraper; client-side it logs a budget refusal. If your conversion rate dips after a price rise, this is the first suspect.
  4. Clock skew. The authorisation's validAfter is in the server's future because the buyer's clock runs fast. Verification fails until the window opens, and a fast-retrying client can burn through its patience first. Facilitators tolerate small skews; a payload valid-from more than a minute ahead is a client bug.
  5. Facilitator disagreement. Client and server trust different facilitators with different views (one supports the scheme version, one does not). Rare, but it presents as "verify succeeds for the buyer's pre-flight, fails on the server". The settle-response body names the facilitator; compare.

Two rarer loops complete the set. Idempotency-cache eviction races: a buyer's legitimate retry arrives after your cache dropped the nonce but inside the authorisation window, so the gate sends it to the facilitator, which rejects the consumed nonce, and the buyer sees a 402 for a call it paid for. The fix is the TTL rule from the launch checklist (cache lifetime strictly exceeds validBefore), and the symptom that finds it is paid-complaint reports that reconcile cleanly, the worst kind to debug without this paragraph. And proxy header stripping: corporate egress proxies and some CDN configurations drop non-standard request headers, so the payment never arrives at all; it presents as one specific buyer looping while everyone else converts, and the buyer-side fix (tunnel, or a proxy exception) is theirs to make, but your error string saying "no payment header received" is what lets them find it.

The meta-fix for all five is the same: make your 402 responses talk. The error field costs nothing and is the only debugging channel the buyer's automation can read. A gate that distinguishes "no payment attached", "wrong network: expected eip155:8453", "amount below price", and "authorisation not yet valid" turns every one of these loops into a one-line diagnosis on the client's side, and the client's operator into someone who says your API is pleasant to integrate.

When should you use a managed gateway instead?

Everything above assumes you own the payment path. The alternative arrived in July 2026 from both major edge networks at once, and for many sellers it will be the right answer, so weigh it honestly.

Cloudflare's Monetization Gateway (announcement, 1 July 2026) charges for anything behind Cloudflare: pages, datasets, APIs, and MCP tools by name. Pricing rules are expressions in the same engine as WAF rules, configured via dashboard, API, or Terraform: a flat price per route and verb ("$0.01 per GET"), variable pricing by declared complexity (their example prices image generation up to $2), or conditional rules such as charging only unauthenticated callers, which is the auth-and-payment layering from earlier expressed as edge config. It can also intercept a 401 from your origin and convert it to a 402 challenge, meaning an existing authenticated API gains an anonymous-paid tier without origin changes. Settlement is USDC through Coinbase's facilitator. The caveat that matters: it is waitlist-only as of mid-July 2026, with no published pricing or GA date.

AWS's version is shipping today. It is not a named product but a Monetize rule action in AWS WAF Bot Control, applied to CloudFront distributions, at general availability and no charge beyond standard WAF pricing (per InfoQ's coverage, July 2026). It settles USDC on both Base and Solana, again through Coinbase's facilitator with its compliance screening. Simpler than Cloudflare's rules engine, but available now.

Context makes the edge moves less surprising than they first read. Cloudflare had spent 2025 building toward this: its pay-per-crawl experiments charged AI crawlers for content access, and its earlier x402 integration work (plus a "deferred payments" scheme aimed at aggregated settlement) told everyone where the roadmap pointed. The Monetization Gateway generalises pay-per-crawl from "charge bots for pages" to "charge any caller for any resource", and MCP tools are named as a first-class resource type in the announcement. The strategic subtext matters to a seller choosing between self-hosting and waiting on the waitlist: for the edge networks this is a traffic-economics play (bot traffic passed human traffic on their networks some time ago, and unmonetised bot traffic is pure cost), so the capability will be pushed hard, priced to drive adoption, and iterated fast. Betting that the managed option gets better quickly is reasonable; betting that it will cover every self-hosting requirement never is.

A note on the migration path in each direction, since the compose-don't-choose point is easy to state and worth making mechanical. Moving self-hosted to managed is deletion: your 402 middleware comes off the route, the gateway's rules take over pricing, and your payTo and prices move into edge config; keep the middleware behind a feature flag for the first weeks, because the edge rules engine sees URLs while your gate saw JSON-RPC, and any per-tool pricing you had must be re-expressed as routes before the flag flips. Moving managed to self-hosted is this guide's implementation sections, with one addition: capture a week of the gateway's settlement records first, so your revenue reconciliation has continuity across the cutover.

The decision grid is short. A managed gateway wins when your service already sits behind that edge, you want zero payment code, and route-level pricing granularity is enough. Self-hosting wins when you need per-tool JSON-RPC-aware pricing today, when your deployment cannot depend on an edge vendor (on-premises and air-gapped-adjacent environments), when you want facilitator choice including self-hosted, or when the waitlist is the blocker. The two compose, too: nothing stops a self-hosted 402 implementation running behind Cloudflare with the gateway disabled, ready to migrate route-level pricing to edge config if that later simplifies operations. Since both gateways speak standard x402, a paying client cannot tell the difference, which is the payoff of building on an open protocol rather than a vendor billing API.

How should you price per-call tools?

Pricing a paid MCP server is more empirical than it looks, because the reference class is visible: the per-call API market in the ideas table, and the observed x402 flow itself, with its $0.028 median and $0.002 to $0.44 working range (Coinbase, April 2026). Within that frame, five rules cover most cases.

Price the unit of value, not the unit of cost. Agents buy outcomes: a page extracted, an address resolved, a review delivered. Meter the thing the buyer would describe wanting. If your cost driver diverges from that unit (long documents, heavy pages), publish size tiers rather than metering seconds; per-second prices are unplannable for the agent's budget guard.

Anchor against the incumbent's retail, then discount for the friction you removed. A geocode call retails at $0.005 at Google after the free tier; an x402 geocoder at $0.002 undercuts it while charging a premium over marginal cost for the no-signup convenience. Selling far below the anchor wastes the willingness-to-pay evidence the incumbents spent years establishing.

Dynamic pricing is legitimate; surprise is not. The 402 payload is generated per request, so nothing stops complexity-based pricing (Cloudflare's rules engine explicitly supports it). The constraint is the buyer's spend guard: a price that jumps above the client's ceiling mid-task aborts the task and burns trust. If prices vary, state the range in the tool description and keep the ceiling case rare.

Freemium splits map cleanly to tools. The natural split: discovery free (always), a taste of the value free (a rate-limited basic tool), the real thing priced. A free geocode_address limited to ten calls a day next to an unlimited priced twin converts better than a paywall with no taste, because agent operators evaluate before budgeting.

Remember the price list is public. Every unpaid probe reads your prices; scrapers will index them (an x402 "Bazaar" of discovered priced endpoints already exists). You are pricing in the open, like a menu in a restaurant window, so price moves are visible history. That argues for fewer, better-considered changes over continuous tweaking.

Changing prices without breaking buyers

Because the price list is public and consumed by software, price changes have a compatibility dimension SaaS pricing never had, and a little protocol-aware process removes the pain. A price change takes effect the instant your 402 challenges start quoting it; there is no cache to invalidate on your side. But three classes of buyer state lag it: challenges already issued (an agent holding your old requirements will sign the old amount, so honour outstanding offers within their maxTimeoutSeconds, which your conformance check does automatically if you version requirements rather than mutate them in place); tool descriptions in registries and in agents' cached tools/list responses (update the metadata the same deploy, and expect stragglers for days); and buyers' budget configurations (a rise that crosses an operator's per-call ceiling converts silently to zero traffic from that operator, per the troubleshooting section).

The process that respects all three: stage the metadata change first, raise the challenge price second, and watch conversion by payer address for a week, because a price rise shows up not as complaints but as specific addresses going quiet. For rises above ten percent or so, the courteous move borrowed from API deprecation practice is a parallel tool for a transition window (geocode_address at the new price, the old price honoured on outstanding offers), though the stateless-quadrant truth is that anonymous buyers have no inbox: the 402 body's error string is your only changelog channel, and "price rises to $0.003 on 1 August" is a perfectly good use of it in the weeks before.

Discounting has protocol-native shapes too. Volume pricing cannot key on identity in the anonymous quadrant, but it can key on the thing the chain gives you free: payer-address history. A gate that quotes "1500" instead of "2000" to an address with a thousand settled calls is loyalty pricing with no loyalty programme, implemented in four lines against your own settlement log. Whether that is clever or a privacy-adjacent smell depends on your buyers; it is at least honest, since the address chose to be pseudonymous rather than anonymous the moment it repeated.

Worked pricing: the geocoder, end to end

Numbers make the rules concrete, so price the guide's own example. Self-hosting Nominatim for a planet-scale index runs roughly $150-300 per month in compute and storage on commodity cloud (a mid-size instance plus ~1TB of fast disk; the Nominatim install docs carry the sizing detail). Per-query marginal cost at that fixed base is effectively zero until saturation, somewhere north of a million queries a month on that hardware.

The anchor: Google charges $5 per thousand after its free tier, so $0.005 per lookup. The x402 convenience story justifies sitting under that while charging a large multiple of marginal cost: at $0.002 per call, breakeven on the fixed cost is 75,000-150,000 calls a month, and every call beyond it is better than 95% gross margin. Below the anchor by 60%, above the Coinbase-observed floor of $0.002, inside any plausible client budget guard. At the observed x402 median of $0.028 you would be an expensive geocoder; at $0.0005 you would clear only $500 on a million calls while absorbing all the operational risk. The band that works is narrower than it first appears, and the anchor plus the floor plus the budget-guard ceiling is how you find it for any row of the ideas table.

Now the check that pricing discussions usually skip: is the demand plausible? A million geocoding calls a month is a real number for a single mid-size logistics or CRM-enrichment workload, and agent traffic is spikier than SaaS traffic (one research task can burn a thousand lookups in an afternoon, then nothing for a week). Which means the fixed-cost breakeven is not a growth milestone, it is a risk decision you make on day one: either you have a reason to believe some population of agents will find you (Bazaar indexing, MCP registry listings, a community that knows you), or the $200 a month is your marketing budget and should be judged as one.

How do you launch? A mainnet checklist

Testnet-to-mainnet is one config change technically and about a dozen decisions operationally. In the order they bite:

  1. Receiving address: cold or multisig, per the wallets section. Verify it once by sending yourself $1 of mainnet USDC before any customer does.
  2. Facilitator: mainnet URL configured, fallback chosen, and (if self-hosting) the gas wallet funded plus alerting on its balance, because a facilitator that cannot pay gas is an outage with a silly cause.
  3. Config audit: grep the deployment for 84532 and the testnet USDC address. A mainnet endpoint that emits testnet requirements gives away product; the reverse strands buyers.
  4. Prices sanity-checked in atomic units. The all-time classic x402 incident is a decimal error: "20000" where you meant "2000" is a 10x price rise no test catches, because everything settles correctly. Write the price in dollars in a comment next to the atomic value.
  5. Idempotency cache sized and TTL'd against your maxTimeoutSeconds, so a redeemable nonce cannot outlive its cache entry.
  6. Dashboards live before launch: 402-to-paid conversion, settlement latency, replay hits, facilitator error rate, and a revenue counter reconciled from settle responses rather than chain-watching (see operations below).
  7. Discovery seeded: MCP registry listing, price in every tool description, 402 error strings written like ad copy, and a probe of your own endpoint from outside confirming the challenge renders the way an indexer will see it.
  8. Policy page written: refund/retry policy, rate expectations, and a contact route. It is one markdown page, and its existence is a trust signal the judgment-service rows in particular cannot skip.

Launch quietly, watch the conversion funnel for a week, and only then spend effort on distribution; a leak in the payment loop found by your first hundred organic calls is a bug report, found by a launch-day thousand it is a reputation.

How do you operate a paid MCP server in production?

The parts of the operation that are genuinely new relative to running any MCP server are all downstream of money, and there are fewer of them than you might fear.

Treasury. Revenue accrues as USDC at your payTo address in real time. Sweep it on a schedule to custody you trust (an exchange business account for off-ramping, or cold storage), keep the receiving key cold as covered in the rails section, and reconcile with the facilitator's settlement records: every sale has a transaction hash, so your books can be provably complete, which is a novelty accountants appreciate once they stop being suspicious of it.

Metrics. Two new gauges join your dashboards. The 402-to-paid conversion rate (what fraction of challenges convert to settled payments) is your funnel metric; a collapse means prices above client ceilings, a client-compatibility break (check the header convention first), or scraping noise. And settlement latency and failure rate is your dependency health metric for the facilitator; sustained failures with verify passing mean the facilitator's chain access is degraded, and your settle-before-execution tools are now refusing paying customers, which is the outage mode to alarm on.

Failed-payment recovery. Decide in advance what a buyer with a settled payment and a failed tool execution gets. On-chain transfers do not reverse, so your options are refund transfers (a real cost: you pay gas), credit against a future call keyed to the payer address, or free retry against the same payment nonce. The retry option is cleanest and falls out of the idempotency design from the architecture section: the nonce already keys the execution, so let a retry within the validity window redeem it. State the policy in your tool description; agents' operators do read it when choosing between two similar tools.

Reconciliation, concretely. Your revenue ledger has two independent sources that must agree: the settle responses your server logged (payer, amount, transaction hash, which tool, which request) and the transfer history at your payTo address on-chain. A nightly job that joins them on transaction hash and alerts on any row present in one but not the other catches every interesting failure at once: settlements your logging dropped (observability bug), transfers with no matching settlement (someone paying the address outside the protocol, or a facilitator submitting without reporting), and amount mismatches (which should be impossible, and "impossible but checked nightly" is the right posture for money). Every Base block explorer exposes the transfer history as an API; the job is thirty lines and the day it first fires you will be very glad it exists.

Support in an anonymous market is a genuinely new problem, so design for it rather than discovering it. Your paying customers have no accounts, no emails, and no names; what they have is payer addresses and, behind them, operators who will eventually need to reach you about a specific call. Give them the hooks: include a support URL in your 402 body and tool descriptions, accept the settlement transaction hash as the ticket identifier (it uniquely names the exact call, which is more than most SaaS support systems can say), and keep your settlement log queryable by hash so "what happened to this payment?" is a thirty-second lookup. The pleasant surprise of hash-keyed support is that disputes are short: both parties are looking at the same public transfer and your logged execution outcome, so the conversation starts at "what went wrong" rather than "prove you paid".

The incident runbook, pre-written. Payment systems reward pessimism, so write the five runbook entries before the first one fires. Facilitator down: settle-before tools are refusing paying customers; fail over to the fallback facilitator URL, and if none, flip priced tools to free-with-rate-limit rather than serving errors, because an hour of free geocoding is cheaper than a reputation for flakiness (make this a config flag now, not during the incident). Settlement succeeding, executions failing: you are charging for nothing; the kill switch that returns tools to unpriced is the same flag. Conversion rate cliff: check header conventions, then recent client-SDK releases, then your own last deploy, in that order, per the troubleshooting section. Revenue reconciliation mismatch: freeze sweeps, diff the two ledgers, and treat a transfer-without-settlement as a possible facilitator incident worth reporting upstream. Receiving-address compromise suspected: rotate payTo in config (old payments still settle to the old address; new challenges advertise the new one), sweep what remains, and note that nothing about the protocol needs to stop while you do.

Compliance is jurisdiction-specific and real. Selling compute for stablecoins is revenue (VAT/sales tax may apply to the service), and in some jurisdictions high volumes of crypto receipts trigger money-transmission or MiCA-adjacent questions, which is part of why facilitators with built-in compliance screening (Coinbase's screens payers) and fiat-adjacent facilitators (AsterPay for SEPA/MiCA contexts) exist. The transaction log makes the accounting tractable; whether you owe a licence is a question for a lawyer in your jurisdiction, and this guide's scope ends at flagging it.

What can go wrong? Security and abuse

The x402 trust model is small enough to enumerate, which is one of its virtues. Attack it from four directions and you have covered the map.

Replay and double-spend, buyer versus seller. The signed authorisation is single-use on-chain (the nonce is consumed at settlement), but nothing stops a buyer replaying it against your server hoping for a second execution without a second settlement, and nothing stops a network middlebox re-delivering a request. Every defence is the same: key execution and settlement on the authorisation nonce, treat a seen nonce as a cache hit, and reject payloads outside their validAfter/validBefore window. If you settle after execution, the window between running the tool and consuming the nonce is your exposure; keep it short and single-flight.

Amount and requirements substitution. Step 3 of the gate sequence exists because signature validity and offer conformance are different checks. A payload can carry a perfectly valid signature for the wrong amount, the wrong asset (a worthless token at the right contract-address shape), the wrong network (a testnet payment replayed against a mainnet endpoint), or someone else's payTo. Compare every field of the accepted block against what you actually offered, and let the facilitator's verify be the second opinion, not the only one.

Facilitator trust. The facilitator can lie in both directions: falsely confirm (you serve free compute) or falsely reject (you refuse paying customers). Hosted facilitators are reputationally bonded against the first and operationally prone to the second. Two mitigations: spot-check settlements against the chain directly (the transaction hashes are verifiable by anyone), and keep the facilitator URL a config value so you can fail over. Self-hosting removes the trust question and replaces it with an operations question, as discussed above.

Griefing on the free surface. Your unpaid surfaces (tools/list, the 402 challenge itself) cost you compute and can be hammered for free. This is ordinary DoS hygiene, not payment security: rate-limit challenges per IP, keep the 402 body generation allocation-free, and remember that the one thing the attacker cannot do for free is get a tool executed, because that is the thing the gate protects. A related economic nuisance is penny-probing, where a buyer pays the minimum price repeatedly to fish for expensive edge cases in your tool; if a request class costs you disproportionately, price that class separately rather than average it into everyone's price.

Buyer-side threats are your problem too, commercially. A seller is not responsible for buyers' wallet hygiene, but sellers absorb the fallout: a drained agent wallet generates a dispute-shaped conversation with no dispute mechanism, and "your agent paid us, the transfer is final" is technically correct and commercially corrosive if it happens at scale. The buyer-side attack pattern to understand is price manipulation against auto-payers: a malicious server (or a compromised one, or a man-in-the-middle where TLS is absent, which is why x402 without TLS is malpractice) presents inflated PaymentRequirements to clients whose ceilings are generous. The client-side spend guard is the defence, which is why every client section of this guide bangs on about it, and why, as a seller, keeping your prices stable and well under typical guards is also a security posture: clients that trust your endpoint keep their guards loose, and clients burned once tighten them for everyone.

Key-compromise blast radii, enumerated, because "keep keys safe" is advice and a blast radius is a design input. Seller receiving key compromised: attacker can move accumulated revenue but cannot charge buyers or forge settlements; loss is bounded by your sweep cadence, which is the argument for sweeping. Buyer agent key: attacker spends the wallet balance at any x402 endpoint; bounded by funding policy, hence petty-cash funding. Facilitator gas key: attacker drains gas, settlement halts, no customer funds touched; bounded by top-up size and alerting. Nothing in the protocol shares custody, so no single compromise reaches everything, and the worst-case story is an operational bad day rather than a platform-wide incident. Contrast with an API-key billing system, where the database of keys plus the payment-provider secret is exactly such a single point, and the trade x402 is making becomes visible.

None of these is exotic. The protocol's security posture reduces to three habits: verify conformance yourself, treat nonces as the unit of truth, and treat the facilitator as a dependency with an SLA rather than an oracle.

How do agents actually find and adopt your paid server?

Distribution deserves its own section because it is where paid MCP servers differ most from paid APIs, and where most of the early sellers are visibly under-investing. A conventional API is marketed to humans who read comparison posts and sit through demos. A paid MCP tool is selected by software, at task time, from whatever catalogue the agent's harness exposes, and marketed to the humans who configure those harnesses. That is two audiences with different discovery paths, and you need both.

The machine path is the one this guide has been seeding all along, collected in one place: list the server in the MCP registries (the official registry plus the large community directories, whose crawlers also feed each other); make the 402 challenge and tools/list self-describing, because the x402 Bazaar and its kin index what your endpoint says about itself; put the price, the unit, and the output shape in every tool description, because that text is what a tool-selecting model actually reads; and publish agent-facing surfaces on your own domain (an llms.txt, an AGENTS.md, a machine-readable catalogue at a well-known path) so that an agent researching "geocoding" with a web tool finds a page written for it. None of this is speculative: server logs on agent-facing endpoints already show autonomous fetches of exactly these surfaces, and they convert differently from human traffic (no bounce, immediate tool calls, and either silent adoption or silent disappearance).

The human path still decides the big accounts, because a fleet operator allowlisting your payTo address is a human decision. What works looks like developer marketing with the demo inverted: instead of "sign up for a key and try it", the pitch is a copy-pasteable client snippet with a spend ceiling, against your live endpoint, on testnet if the reader wants to pay nothing. The absence of signup is itself the demo. Beyond that, the boring truths hold: a comparison page against the incumbent anchor (yours versus Google Geocoding, with the price table), a status page, a changelog that shows the thing is alive, and answers in the places your buyers' operators ask questions. The judgment-service rows add one more requirement: published evals. A code-review tool that shows its precision and recall on a public benchmark, with the harness version pinned, converts skeptics that no price can.

And one distribution asset unique to this model: your settlement history is public proof of adoption. A payTo address with a steady stream of small inbound transfers is verifiable traction, checkable by anyone, unfakeable at any interesting scale without spending real money. Early x402 sellers have started linking their address's explorer page from their docs the way SaaS companies link customer logos. It is a strange new genre of social proof, and for a stranger-to-stranger market it is exactly the right one.

How will the numbers in this guide age?

A guide stuffed with prices and version pins owes the reader a decay schedule, so here is which figures to re-verify by when, in descending order of half-life. The protocol structures (the 402 challenge shape, EIP-3009 mechanics, the verify/settle division, the auth-versus-payment quadrants) are the stable core; they survive spec point-releases and are safe to build against as described. The contract addresses and network identifiers (Base Sepolia USDC at 0x036CbD…, the CAIP-2 chain IDs) change only on the rare redeployment; check them against Circle's developer documentation rather than any tutorial, this one included. The library versions (x402-axum 2.0.2 and friends) will be stale in months; the crates were updated the day before this guide was written, which tells you the cadence. The market prices in the ideas table drift on quarters, and the direction of drift is itself information: falling incumbent prices in a row mean x402 sellers arrived. And the adoption figures ($50M settled, 165M transactions, the $0.028 median) were current as of April 2026 and will read as quaint fastest of all, which is, for once, the failure mode to hope for. Everything time-sensitive above carries its retrieval date inline for exactly this audit; when the dates and your calendar disagree by more than a quarter, trust the primary sources linked beside them.

Common objections, answered honestly

Every conversation about charging agents in stablecoins hits the same five objections, and a guide that pretends they have no substance would deserve the skepticism. Here is where each one lands after the details.

"This is crypto; the whole apparatus is toxic to my organisation." The aversion usually attaches to volatility, speculation, and custody risk, so check each against this design. The asset is a regulated, reserve-backed dollar token, not a speculative coin; your exposure window between settlement and sweep is hours of dollar-pegged float, not a position. Custody on the selling side is one receive-only address. What legitimately remains is category discomfort (some compliance departments treat anything chain-shaped as radioactive regardless of mechanics), and if that is your organisation, the managed gateways are the answer: revenue arrives from Cloudflare or AWS, entities your procurement already knows, and the chain becomes their implementation detail.

"Agent traffic is hype; the buyers will evaporate." Maybe the growth curves flatten. The floor, though, is not zero: the metered-API market that anchors every price in this guide predates the agent wave and pays real invoices today, and the x402 lane is additive distribution to it, at near-zero marginal cost once the gate exists. The downside case for a well-chosen row of the table is "an API business with an extra, cheap acquisition channel", which is a tolerable way to be wrong.

"Why not wait for the Cloudflare gateway and skip all this?" Waiting is defensible if your service already lives behind Cloudflare and route-level pricing suffices. You still want most of this guide: the pricing, discovery, idempotency, and auth-layering decisions are yours regardless of who enforces the 402. What waiting costs is the window itself, plus the self-hosting option and per-tool control, and the waitlist has no published exit date.

"Micropayments have failed for thirty years; why now?" The canonical objections to micropayments were mental transaction costs (humans cannot price a nickel's worth of attention) and fee floors. Both were about humans. An agent evaluates a $0.002 price in microseconds against a budget rule, feels no decision fatigue, and the fee floor fell three orders of magnitude below the price. The pattern held for decades because the buyer was the bottleneck; the buyer changed. That is also the honest scope limit: x402 does not make micropayments work for people, and businesses selling to human readers should keep their subscriptions.

"I can see the revenue address; so can my competitors. Won't someone just clone my tool and undercut me?" If your moat is the price, yes, and faster than in the key-based world, per the switching-cost point in the ideas section. The table's defensibility column is the real answer: pick rows where the moat is operational (proxy upkeep, IP reputation, data freshness) or epistemic (rulesets, evals, judged-case corpora), and let the transparency work for you; a competitor can read your price, but your repeat-payer rate is the part they cannot clone by reading anything.

Where does this go next?

You now have the full map: a protocol that finally gives HTTP 402 semantics, a clean separation between who-is-calling and has-this-been-paid-for, an evidence-based menu of services worth charging for, a self-hosted implementation path in Rust with a testnet-to-mainnet switch the size of a config stanza, and two edge networks racing to make the same capability a checkbox.

On the protocol's own trajectory, three developments are worth tracking because each would change a recommendation in this guide. Metered schemes (authorise-max, settle-actual) would collapse the claim-check workarounds for session-shaped services into native protocol; the spec's scheme system was built for exactly this extension. An MCP-native payment binding (the transport spec work that would put payment negotiation inside JSON-RPC rather than wrapped around it) would dissolve the body-inspecting middleware into something cleaner, and the MCP community discussion is live. And facilitator plurality: today's ecosystem leans on one dominant facilitator, and the health of the protocol depends on the self-hosted and alternative options maturing from viable to boring. If you build now, none of these is worth waiting for; all three are worth an occasional check of the spec repository, and the architecture in this guide (gate as a layer, facilitator as a config value, prices in one table) is shaped so each lands as a refactor rather than a rewrite.

The strategic read is worth one paragraph. Payment rails arriving at the protocol layer do to API monetisation what MCP did to tool integration: standardise the interface so the value moves to what is behind it. When any endpoint can charge, having a tool worth paying for and operating it reliably become the whole game. The window where shipping a well-built paid MCP server is itself a differentiator is open now, and the ideas table is a reasonable place to choose your entry.

Build order, if you want one: pick a service with no licensing wall, implement it as an ordinary free MCP server first, add the x402 gate on Base Sepolia with faucet USDC and an auto-paying test client, run a week of simulated agent traffic against your idempotency and failure paths, then switch the config to mainnet and price against the anchors above. For the MCP fundamentals under this guide, see building an MCP server in Rust and MCP server authentication and security; for the deployment surface, running MCP servers in production.