Skip to content

x402

The x402 plugin enables tool monetization through the HTTP 402 payment protocol using USDC on Base.

For the complete documentation index, see llms.txt. Markdown variants of every page are available by appending .md to the URL.

Overview

The x402 plugin integrates the x402 payment protocol with your xmcp server, enabling you to charge USDC micropayments for tool usage on the Base blockchain.

Installation

Install the x402 plugin:

Shell

Set up your wallet

Before integrating the plugin, you need a wallet address to receive payments:

  1. Create or use an existing Ethereum-compatible wallet (e.g., Coinbase Wallet, MetaMask)
  2. Get your wallet's public address (starts with 0x)
  3. For testing, use Base Sepolia testnet and get test USDC from the Coinbase Developer Platform under Wallets > Faucet
Info

The x402 protocol uses USDC stablecoin for payments. On Base mainnet, 1 USDC = 1 USD.

Environment Variables

Create a .env file in the root of your project and configure the following environment variables:

Shell

Set up the Provider

Create a middleware.ts file in your xmcp app's src directory and import the provider from the package:

src/middleware.ts

Configuration Options

  • wallet: Your wallet address that receives payments
  • facilitator: (Optional) Facilitator URL (defaults to https://x402.org/facilitator)
  • debug: (Optional) Enable debug logging
  • nano: (Optional) Settings for tools on the nano network, see Nano (XNO)
    • wallet: nano_ address that receives XNO (falls back to wallet)
    • rpc: Nano node RPC URL used to verify payments (default: https://rpc.nano.to)
    • claimsFile: (Optional) Path of a file that records used block hashes so they are still refused after a restart, see Keeping claims across restarts
    • requireBinding: (Optional) Bind each payment to the order id of its 402 offer (default: false), see Binding a payment to an order
    • x402Version: (Optional) x402 version of the 402 offer sent for an unpaid Nano call, 1 or 2 (default: 1). Set 2 for clients of the x402 v2 Nano exact scheme, which read network nano:mainnet, the price under amount and the tool in a top-level resource. Payments of either version are accepted
  • defaults: (Optional) Default values for all paid tools
    • price: Price in USDC (default: 0.01)
    • currency: Currency code (default: "USDC")
    • network: Network - "base", "base-sepolia" or "nano" (default: "base")
    • maxPaymentAge: Maximum payment age in seconds (default: 300)

Monetize a Tool

Wrap your tool functions with paid() to require payment:

src/tools/analyze.ts

Pricing

You can set a custom price for each tool by passing a price option to paid(). If not specified, the tool will use the default price from your provider configuration. If the provider doesn't specify a default price either, the tool will cost 0.01 USDC per call.

src/tools/premium-analysis.ts
src/tools/basic-tool.ts

Tool Options

  • price: Price in USDC for this tool (falls back to provider default, then 0.01 USDC)
  • network: Override default network
  • maxPaymentAge: Override maximum payment age
  • description: Description used in payment requirements

Get Payment Details

Access payment details inside your tool using the payment() function:

src/tools/paid-greet.ts

Networks

The plugin supports three networks:

NetworkIDAssetUse Case
baseeip155:8453USDCProduction with real USDC
base-sepoliaeip155:84532USDCTesting with testnet USDC
nanonano:mainnetXNOProduction with real XNO

Nano (XNO)

Tools can also be paid in XNO on the Nano network, next to USDC on Base. Nano has no facilitator: the payer either publishes a send block to your Nano address first and retries the call with the block hash, or sends the signed block itself and the plugin publishes it (see Paying with a signed block). The plugin checks the block against a Nano node and does not hold a key. The only thing it ever broadcasts is a block the payer signed.

src/middleware.ts
src/tools/word-count.ts
Warning

On the nano network, price is an amount of XNO, not USD. There is no exchange rate conversion. The payment requirements advertise the amount in raw (1 XNO = 10^30 raw).

The client sends the hash of its send block in the payload of the x402 payment:

JSON

A payment is accepted when the block:

  • is a confirmed state block with subtype send
  • sends to the configured nano.wallet (checksum validated)
  • sends at least the tool price (previous balance minus the block's balance)
  • was first seen by the node within maxPaymentAge seconds, when the node reports a timestamp
  • has not already paid for another call on this server

The block hash and payer are returned in payment() and in the x402/payment-response metadata. If the tool returns an error, the block can be used again for a retry.

Things to know before using it:

  • By default the block hash is a bearer proof. Anyone who sees the block on the public ledger could present it first, so keep maxPaymentAge short, or turn on requireBinding.
  • By default used block hashes are kept in memory. They are forgotten on restart and are not shared between server instances. Set claimsFile to keep them across restarts.
  • Verification depends on the Nano node RPC you configure. Use a node you trust.

Paying with a signed block

Clients of the x402 Nano exact scheme (for example @x402nano/exact) send the signed send block itself as payload.block instead of a hash:

JSON

When payload.blockHash is present it is used and payload.block is ignored. With a block, the plugin:

  1. checks it before sending anything: a state send block to nano.wallet that follows the payer's previous block and sends at least the price (exactly the price, with the order commitment as representative, when requireBinding is on, in which case payload.orderId is sent beside the block)
  2. publishes it through the node with the RPC process action; the node checks the signature and the work
  3. reads it back until the node confirms it (up to 20 reads 500 ms apart), then verifies and claims it by its hash like a payload.blockHash payment

A block that is already on the ledger is not published again; it is verified by its hash.

Warning

The node behind nano.rpc must allow the process action. Public RPC endpoints often restrict it, and the call is then refused with Nano node did not publish the block. Payments sent as payload.blockHash only need block_info.

If the block was published but the node has not confirmed it in time, the call gets a 402 whose error names the block hash and says it may still confirm. The payer's XNO has already left its account, so a client should retry with that hash as payload.blockHash (or the same block, and the same orderId when requireBinding is on) instead of signing a new block and paying again.

Keeping claims across restarts

Set nano.claimsFile to a path the server can write to:

src/middleware.ts

Each block hash that pays for a call is appended to the file and flushed to disk before the tool runs, and the file is read back when the server starts, so a block that already paid is still refused after a restart. When the tool returns an error, a release line is appended and the block can be used again for a retry. The file is compacted to the live claims when it is opened, and while running once released lines outnumber them.

Warning

One claims file belongs to one server process. It is not a shared store: instances that run side by side each need their own file and do not see each other's claims.

Binding a payment to an order

Set nano.requireBinding: true so a block hash seen on the public ledger cannot be presented by someone else. The 402 offer then carries two extra fields:

JSON

The payer:

  • sets the representative of its send block to the order commitment: the nano_ encoding of SHA-256("xno-binding/v1/rep|" + orderId + "|" + payTo + "|" + amount), with amount in raw
  • sends exactly the price in raw (maxAmountRequired, or amount in an x402 v2 offer); overpaying is refused
  • pays with the order id beside the block hash:
JSON

A payment without orderId, with a malformed one, or with a block whose representative is not the commitment for that order is rejected. The plugin keeps no order state: each 402 response carries a fresh random order id, and the block hash is still claimed once, so one block pays for one call.

Troubleshooting

Payment Required Response

If clients receive a 402 response, they need to:

  • Extract payment requirements from result.structuredContent.accepts
  • Sign a payment authorization using their wallet
  • Retry with payment in params._meta["x402/payment"], either as the PaymentPayload JSON object (as the x402 MCP transport sends it) or as the same payload base64-encoded

Payment Verification Failed

If payment verification fails:

  • Ensure the payment amount matches the tool price
  • Check that the payment is recent (within maxPaymentAge seconds)
  • Verify the correct network is being used (base vs base-sepolia)
  • For nano, ensure the send block is confirmed before retrying the call

Settlement Errors

If settlement fails after tool execution:

  • Check the facilitator URL is correct and reachable
  • Verify your wallet address is valid
  • Ensure the payer has sufficient USDC balance

Missing Payment Context

If payment() throws "x402 context not initialized":

  • Ensure x402Provider is exported as default from middleware.ts
  • Only call payment() inside paid tool handlers
  • Don't call payment() at module load time

One framework to rule them all