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:
Set up your wallet
Before integrating the plugin, you need a wallet address to receive payments:
- Create or use an existing Ethereum-compatible wallet (e.g., Coinbase Wallet, MetaMask)
- Get your wallet's public address (starts with
0x) - For testing, use Base Sepolia testnet and get test USDC from the Coinbase Developer Platform under Wallets > Faucet
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:
Set up the Provider
Create a middleware.ts file in your xmcp app's src directory and import the provider from the package:
Configuration Options
wallet: Your wallet address that receives paymentsfacilitator: (Optional) Facilitator URL (defaults tohttps://x402.org/facilitator)debug: (Optional) Enable debug loggingnano: (Optional) Settings for tools on thenanonetwork, see Nano (XNO)wallet:nano_address that receives XNO (falls back towallet)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 restartsrequireBinding: (Optional) Bind each payment to the order id of its 402 offer (default:false), see Binding a payment to an orderx402Version: (Optional) x402 version of the 402 offer sent for an unpaid Nano call,1or2(default:1). Set2for clients of the x402 v2 Nanoexactscheme, which read networknano:mainnet, the price underamountand the tool in a top-levelresource. Payments of either version are accepted
defaults: (Optional) Default values for all paid toolsprice: 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:
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.
Tool Options
price: Price in USDC for this tool (falls back to provider default, then 0.01 USDC)network: Override default networkmaxPaymentAge: Override maximum payment agedescription: Description used in payment requirements
Get Payment Details
Access payment details inside your tool using the payment() function:
Networks
The plugin supports three networks:
| Network | ID | Asset | Use Case |
|---|---|---|---|
base | eip155:8453 | USDC | Production with real USDC |
base-sepolia | eip155:84532 | USDC | Testing with testnet USDC |
nano | nano:mainnet | XNO | Production 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.
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:
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
maxPaymentAgeseconds, 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
maxPaymentAgeshort, or turn onrequireBinding. - By default used block hashes are kept in memory. They are forgotten on restart and are not shared between server instances. Set
claimsFileto 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:
When payload.blockHash is present it is used and payload.block is ignored. With a block, the plugin:
- checks it before sending anything: a state send block to
nano.walletthat follows the payer's previous block and sends at least the price (exactly the price, with the order commitment as representative, whenrequireBindingis on, in which casepayload.orderIdis sent beside the block) - publishes it through the node with the RPC
processaction; the node checks the signature and the work - 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.blockHashpayment
A block that is already on the ledger is not published again; it is verified by its hash.
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:
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.
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:
The payer:
- sets the representative of its send block to the order commitment: the
nano_encoding ofSHA-256("xno-binding/v1/rep|" + orderId + "|" + payTo + "|" + amount), withamountin raw - sends exactly the price in raw (
maxAmountRequired, oramountin an x402 v2 offer); overpaying is refused - pays with the order id beside the block hash:
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
maxPaymentAgeseconds) - 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
x402Provideris exported as default frommiddleware.ts - Only call
payment()inside paid tool handlers - Don't call
payment()at module load time
