How to pay for one call
Every paid route answers an unpaid request with a 402 that names the price and every way to pay it. Pay with a stablecoin from a wallet over x402 or MPP, in sats over Lightning, with a card where the price allows it, with a prepaid key, or with a solved puzzle on the pure-CPU tools. Same URL, same answer, same receipt.
New to x402 or MPP? ask402.ai explains both.
One handshake, and one rule about money.
The handshake is two requests: the first carries no payment and gets a 402 with the terms; the second is the identical request plus one payment header, and gets the answer with a receipt header.
The rule is the order of operations: the handler runs first, and the payment settles only after a response below 400 is ready (a Tempo push transfer and a Lightning payment are the exceptions, below). On x402, on MPP's evm method, on a Tempo charge, on a card and on credits, a 4xx or 5xx cancels settlement and nothing is charged; a 200 is charged only if its settlement then succeeds, and otherwise the answer is withheld behind a 402. Some calls are paid before they run. If one fails, send the same payment again to retry it free, or it is refunded.
x402: a stablecoin from your own wallet.
x402 is served on every paid route. This server settles it on fourteen chains: USDC on Base, Solana, Polygon, Arbitrum One, Monad, Celo, Avalanche C-Chain, Sei, OP Mainnet, Arc, Ink, Stellar and Algorand, plus USDG on Robinhood Chain.
What you need
A private key for a wallet that holds a little of the stablecoin on one chain from the table. The key never leaves your process: the client signs a transfer authorization for exactly the quoted amount, and the facilitator moves the funds wallet to wallet. 45 routes (the identity-bound ones such as memory, and the long-running report routes) take an EVM authorization only; /api/pricing lists each route's networks and its 402 offers only those.
No wallet yet? Fund a first one with USDC on Base, no ETH needed, or run npx -y agent402-mcp@0.21.0 wallet new to make one on this computer: it stores the key and prints the address and the config, never the key.
| chain | asset | wallet | caip-2 |
|---|---|---|---|
| Base | USDC | EVM: the facilitator sponsors gas, so the wallet needs only the stablecoin | eip155:8453 |
| Solana | USDC | Solana wallet and its own x402 scheme package | solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp |
| Polygon | USDC | EVM: the facilitator sponsors gas, so the wallet needs only the stablecoin | eip155:137 |
| Arbitrum One | USDC | EVM: the facilitator sponsors gas, so the wallet needs only the stablecoin | eip155:42161 |
| Monad | USDC | EVM: the facilitator sponsors gas, so the wallet needs only the stablecoin | eip155:143 |
| Celo | USDC | EVM: the facilitator sponsors gas, so the wallet needs only the stablecoin | eip155:42220 |
| Avalanche C-Chain | USDC | EVM: the facilitator sponsors gas, so the wallet needs only the stablecoin | eip155:43114 |
| Sei | USDC | EVM: the facilitator sponsors gas, so the wallet needs only the stablecoin | eip155:1329 |
| OP Mainnet | USDC | EVM: the facilitator sponsors gas, so the wallet needs only the stablecoin | eip155:10 |
| Arc | USDC | EVM: the facilitator sponsors gas, so the wallet needs only the stablecoin | eip155:5042 |
| Ink | USDC | EVM: the facilitator sponsors gas, so the wallet needs only the stablecoin | eip155:57073 |
| Stellar | USDC | Stellar wallet and its own x402 scheme package | stellar:pubnet |
| Algorand | USDC | Algorand wallet and its own x402 scheme package | algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k |
| Robinhood Chain | USDG | EVM: the facilitator sponsors gas, so the wallet needs only the stablecoin | eip155:4663 |
See a quote, free
curl -i -X POST https://agent402.tools/api/hash \
-H 'Content-Type: application/json' -d '{"text":"hello world"}'
# HTTP/2 402 (the same terms ride base64 in the PAYMENT-REQUIRED header)
# {"x402Version":2,"accepts":[{"scheme":"exact","network":"eip155:8453",
# "amount":"1000","asset":"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
# "payTo":"0x…","maxTimeoutSeconds":…}, … one entry per chain …]}amount is in the asset's smallest unit (six decimals for USDC), so $0.001 reads as 1000. Every accept entry names its own network, asset and payTo; a client picks the one it can sign.
A small header limit
A client whose parser caps one header line near 8 KB (Python aiohttp's default max_line_size and max_field_size are 8190) reads the 402 one of two ways. Raise the limit: aiohttp.ClientSession(max_line_size=32768, max_field_size=32768). Or send X-Payment-Compact: 1 (a User-Agent that names aiohttp gets the same without it) for a PAYMENT-REQUIRED header under 7,500 bytes: the resource, the Bazaar extension and the builder code unchanged, the Base exact accept first, each other exact accept that fits, and a compact field whose fullOfferIn names the body, which keeps every accept. A payment signed from the compact header settles the same way. The paywall's 402 body states the header's size in paymentRequiredHeader.
Pay it
import { wrapFetchWithPayment } from "@x402/fetch";
import { x402Client } from "@x402/core/client";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";
const client = new x402Client();
client.setSpendControls?.(false); // keep your own ceiling in code instead
registerExactEvmScheme(client, { signer: privateKeyToAccount(process.env.AGENT_KEY) });
const payFetch = wrapFetchWithPayment(fetch, client);
const res = await payFetch("https://agent402.tools/api/extract", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url: "https://example.com/article" }),
});
console.log(res.status, res.headers.get("payment-response"), await res.json());That one wrapped fetch pays every route on the EVM chains at $0.001 for /api/extract and the catalog price elsewhere. For Solana, Stellar and Algorand, register that chain's exact scheme on the same client. The buyer SDK wraps the same thing with spend caps and a stable idempotency key per call:
import { Agent402 } from "agent402-client";
const a = new Agent402({ fetch: payFetch, maxPerCallUsd: 0.05, dailyLimitUsd: 2 });
const article = await a.call("extract", { url: "https://example.com/article" });What the receipt looks like
HTTP/2 200
PAYMENT-RESPONSE: eyJzdWNjZXNzIjp0cnVlLCJ0cmFuc2FjdGlvbiI6IjB4…
# base64 JSON: {"success":true,"transaction":"0x…","network":"eip155:8453","payer":"0x…"}
{ "title": "…", "markdown": "…", "wordCount": 1180 }transaction is the on-chain settlement, checkable on the chain's explorer. A refused payment answers 402 again with a reason naming the field that differed from the offer; /x402-test lists every reason, and a refusal costs nothing.
MPP: the same handshake in HTTP auth headers.
MPP, the Machine Payments Protocol, carries the quote in WWW-Authenticate: Payment and the payment in Authorization: Payment, and the settled answer returns a Payment-Receipt. The same 402 carries both the x402 offer and the MPP challenges, so your client picks the dialect. A client whose User-Agent starts with python-httpx/ gets the x402 offer alone, with no WWW-Authenticate: Payment challenge, unless it sends X-Payment-Offers: mpp or an Accept-Payment header naming an MPP method.
| method | pays with | what you need |
|---|---|---|
| tempo | USDC.e or PathUSD on Tempo | A key holding the stablecoin on Tempo. The challenge is settled natively through Tempo; withheld on identity-bound and long-running routes. |
| evm | USDC on Base or Celo | The same EVM key as x402: the credential is the same signed EIP-3009 authorization, settled by the same facilitator at the same price. |
| stripe | card, on routes priced $0.50 or more | A shared payment token issued by a card wallet your agent holds. The charge is captured only after a final 200. |
| lightning | sats over Lightning, on routes priced $0.005 or more | A Lightning wallet that pays a BOLT11 invoice and returns its preimage. Paid before the tool runs: Lightning, below. |
The 402 lists the methods in this order: tempo, then evm, then stripe, then lightning. A stock mppx client takes the first one it holds a method for.
What you need
The mppx client signs the challenge it can satisfy and retries for you.
import { Mppx, tempo, evm } from "mppx/client";
import { privateKeyToAccount } from "viem/accounts";
const account = privateKeyToAccount(process.env.AGENT_KEY);
const mppx = Mppx.create({ methods: [tempo.charge({ account }), evm.charge({ account, currencies: [evm.assets.base.USDC, evm.assets.celo.USDC] })] });
// $0.001 per call; the first request returns 402, mppx pays and retries.
const res = await mppx.fetch("https://agent402.tools/api/crypto-price?coins=BTC,ETH¤cy=usd");
console.log(res.status, res.headers.get("payment-receipt"), await res.json());What the receipt looks like
HTTP/2 200
Payment-Receipt: eyJtZXRob2QiOiJ0ZW1wbyIsInJlZmVyZW5jZSI6IjB4…
# base64url JSON: {"method":"tempo","reference":"0x…","status":"success","timestamp":"2026-…"}reference is the settlement transaction on the method's chain (for the evm method it is the same transaction an x402 receipt would carry). Tempo settlements are listed with their explorer links on /revenue.
Charge and push. A Tempo charge credential is broadcast by this server only after the handler answers below 400, so a 4xx or 5xx on a Tempo charge is not charged. Some calls are paid before they run; a failed one can be retried free with the same payment, or is refunded. A Tempo push credential is a transfer your client already sent; the server finalizes it before the handler runs, and if the answer then fails or never reaches you, the amount is booked as owed to your wallet in the refund ledger.
Card over MPP. On routes priced $0.50 or more the same 402 carries a stripe challenge. Your agent presents a shared payment token from its card wallet in Authorization: Payment; the card is captured only after the handler has answered with a 200, and a 4xx or 5xx on the card path leaves nothing captured. A person can also buy a finished report by card at /reports with no agent at all.
Lightning: sats, paid before the run.
This server also takes sats over MPP lightning, x402 exact on lnbtc and L402. Lightning pays this server's own tools priced $0.005 or more. It is not offered on identity-bound routes, routes that buy from an outside seller, routes whose effect outlives the answer, or long-running or metered routes. One 402 carries one BOLT11 invoice for the route's price in whole sats at the current BTC/USD rate, rounded up, payable for 10 minutes; each Lightning option on that 402 offers the same invoice. Your wallet pays it and learns the preimage, and the retry presents the preimage as the proof.
A Lightning payment is final before the tool runs: each invoice pays for one run, and a proof sent again is refused. Lightning names no payer: the receipt names the payment hash and nothing else. When an invoice cannot be made in time (the wallet or the BTC/USD rate is unavailable, or the per-minute invoice budget is spent), the 402 goes out without the Lightning option and every other way to pay is unchanged.
| wire | the 402 carries | you send | a 200 carries |
|---|---|---|---|
| MPP lightning | WWW-Authenticate: Payment with method="lightning"; its request holds amount (sats), currency: "sat" and methodDetails with the invoice, its paymentHash and the network. | Authorization: Payment, a credential for that challenge with payload: { preimage }. | Payment-Receipt with method: "lightning" and reference, the payment hash. |
| x402 lnbtc | An accepts entry: scheme: "exact", network: "lnbtc:000000000019d6689c085ae165831e93", amount in millisats, asset: "BTC", payTo (the key that signed the invoice) and extra with the invoice, paymentFlow: "upfront", the requestHash it is bound to and a refundToken. Offered on GET requests with no body only, bound to that URL. | PAYMENT-SIGNATURE: base64 JSON { x402Version: 2, accepted, payload: { preimage } }. | PAYMENT-RESPONSE with success, transaction (the payment hash) and network, and no payer. |
| L402 | WWW-Authenticate: L402 macaroon="...", invoice="...", first in the header. | Authorization: L402 <macaroon>:<preimage>. | No receipt header: the macaroon and the preimage are your record. |
Pay it
import { Challenge, Credential } from "mppx";
// payInvoice(bolt11) is your Lightning wallet: it pays the invoice and
// returns the payment's preimage, 64 lowercase hex characters.
const url = "https://agent402.tools/api/x402-trending";
const quote = await fetch(url); // 402
const challenge = Challenge.deserializeList(quote.headers.get("www-authenticate"))
.find((c) => c.method === "lightning");
const preimage = await payInvoice(challenge.request.methodDetails.invoice);
const res = await fetch(url, {
headers: { Authorization: Credential.serialize(Credential.from({ challenge, payload: { preimage } })) },
});
console.log(res.status, res.headers.get("payment-receipt"));
// a refund claim's offerProof: challenge.id// payInvoice(bolt11) is your Lightning wallet: it pays the invoice and
// returns the payment's preimage, 64 lowercase hex characters.
const url = "https://agent402.tools/api/x402-trending";
const quote = await fetch(url); // 402
const required = JSON.parse(Buffer.from(quote.headers.get("payment-required"), "base64").toString());
const accepted = required.accepts.find((a) => a.network.startsWith("lnbtc:"));
const preimage = await payInvoice(accepted.extra.invoice);
const payment = Buffer.from(JSON.stringify({ x402Version: 2, accepted, payload: { preimage } })).toString("base64");
const res = await fetch(url, { headers: { "PAYMENT-SIGNATURE": payment } });
console.log(res.status, res.headers.get("payment-response"));
// a refund claim's offerProof: accepted.extra.refundToken// payInvoice(bolt11) is your Lightning wallet: it pays the invoice and
// returns the payment's preimage, 64 lowercase hex characters.
const url = "https://agent402.tools/api/x402-trending";
const quote = await fetch(url); // 402
const [, macaroon, invoice] = /L402 macaroon="([^"]+)", invoice="([^"]+)"/.exec(quote.headers.get("www-authenticate"));
const preimage = await payInvoice(invoice);
const res = await fetch(url, { headers: { Authorization: `L402 ${macaroon}:${preimage}` } });
console.log(res.status);
// a refund claim's offerProof: the macaroonWhen the run fails
A run that answers 400 or more, or whose buyer left before its first byte, is recorded as owed under the payment hash, and its failure body says charged: true, refundOwed: true, the paymentHash and the refundClaim URL. An invoice paid and never presented, or presented after it expired, is owed the same way. Claim it with POST /api/lightning/refund-claim and JSON { preimage, offerProof, invoice }: offerProof is the id of the Payment challenge you paid (MPP lightning), extra.refundToken of the accepts entry you paid (x402 exact on lnbtc) or the macaroon you paid with (L402), so the preimage alone claims nothing; invoice is a BOLT11 invoice for exactly the sats paid (or no amount), on this server's network, payable for at least 24 hours. Refunds are sent by hand, in sats, to that invoice. GET /api/lightning/refund-claim?paymentHash=<hex> reads the refund's status.
curl -X POST https://agent402.tools/api/lightning/refund-claim \
-H 'Content-Type: application/json' \
-d '{"preimage":"<64 hex>","offerProof":"<from your 402>","invoice":"<BOLT11 for the sats>"}'
# {"claimed":true,"paymentHash":"...","sats":...,"refund":"owed","note":"Refunds are sent by hand, in sats, to this invoice."}
curl "https://agent402.tools/api/lightning/refund-claim?paymentHash=<hex>"
# {"paymentHash":"...","refund":"owed","claimed":true}Prepaid credits: a key instead of a wallet.
Prepaid credits are on sale at /credits: a card checkout issues one a402_ key, spent across the paid tools at list price, for an agent that will not hold a wallet.
How a key pays
curl -X POST https://agent402.tools/api/extract \
-H "Authorization: Bearer a402_YOUR_KEY" \
-H 'Content-Type: application/json' \
-d '{"url":"https://example.com/article"}'
# 200 with the answer, and X-Credits-Balance: <what is left>
curl -H "Authorization: Bearer a402_YOUR_KEY" https://agent402.tools/api/credits/balanceThe gate authorizes before the handler runs (the balance must cover the route's list price), holds that amount, and debits it only on a final 200; a 4xx or 5xx on credits releases the hold. The X-Credits-Balance header on every answer carries what is left, and a refused call answers 402 with the balance and nothing debited. Credits never expire. A balance with no activity for several years may have to be paid to a state's unclaimed property program, where the owner can claim it.
Credits are refused on the identity-bound routes (memory, usage, attest, feedback), where the signed payer address is the identity; those take a wallet. The buyer SDK sends the key for you: pass it as creditsKey to new Agent402() and every wallet-only call carries the header.
No wallet: pay the pure-CPU tools with proof-of-work.
187 tools (hashing, encoding, JSON, dates, text, finance math and more) also accept a solved sha256 puzzle instead of money: about 65,536 sha256 hashes on average, a fraction of a second of CPU on a laptop at the current difficulty of 16 bits. Each one is marked computePayable: true on /api/pricing, and the 402 of an eligible route names its challenge URL in X-Pow-Challenge.
curl -s "https://agent402.tools/api/pow/challenge?slug=hash"
# { "challenge": "…", "difficulty": 16, "token": "…", "ttlSeconds": … }
# find an integer nonce so sha256("<challenge>:<nonce>") has at least
# <difficulty> leading zero bits, then send the TOKEN (not the challenge):
curl -X POST https://agent402.tools/api/hash \
-H 'Content-Type: application/json' \
-H "X-Pow-Solution: <token>:<nonce>" \
-d '{"text":"hello world"}'import { createHash } from "node:crypto";
const lz = (b) => { let t = 0; for (const x of b) { if (!x) { t += 8; continue; } t += Math.clz32(x) - 24; break; } return t; };
const c = await (await fetch("https://agent402.tools/api/pow/challenge?slug=hash")).json();
let n = 0;
while (lz(createHash("sha256").update(c.challenge + ":" + n).digest()) < c.difficulty) n++;
const res = await fetch("https://agent402.tools/api/hash", {
method: "POST",
headers: { "Content-Type": "application/json", "X-Pow-Solution": c.token + ":" + n },
body: JSON.stringify({ text: "hello world" }),
});A solved call answers 200 with X-Pow-Accepted: true; a wrong or reused solution answers 402 with X-Pow-Error naming why. A challenge is single-use, scoped to one tool, and expires. The free tier is rate-limited per client (20/min, 120/hour per client); a limited call says so in X-Pow-Limits. The buyer SDK solves the puzzle for you: new Agent402() with no fetch pays every eligible tool this way.
From an MCP host, the payment rides underneath.
The hosted connector at https://agent402.tools/mcp serves the free tier with no install and no wallet, and makes the wallet-only tools payable in the call over x402 or MPP, from an MCP client that speaks it. The npm server pays over x402 from a key you give it, with spend caps checked before any payment is signed.
# hosted, no wallet: the proof-of-work tools claude mcp add --transport http -s user agent402 https://agent402.tools/mcp # npm server with a funded EVM key: every paid tool over x402 # Use a new wallet holding only a few dollars of USDC. Never your main wallet. # setup asks for the key once (hidden) and stores it in the OS keychain npx -y agent402-mcp@0.21.0 setup claude mcp add agent402 -s user -- npx -y agent402-mcp@0.21.0 # a credits key works there too claude mcp add agent402 -s user -e AGENT402_CREDITS_KEY=a402_YOUR_KEY -- npx -y agent402-mcp@0.21.0
Every host's verified config block is in the agent-hosts guide; /quickstart has the same first call for curl, JavaScript and the model gateway.
What happens to the money, rail by rail.
| rail | a 4xx or 5xx | a 200 whose settlement fails | an answer that never reached you |
|---|---|---|---|
| x402 | Not charged: the error cancels settlement before any facilitator call. | The result is withheld and you get a 402; nothing settled. A transfer that lands after a timed-out settle, a disconnect during settle, or a settle the facilitator answered as pending whose receipt was not read in time, is booked as a refund owed and repaid after on-chain proof. | Not charged while the hang-up budget holds (below); past it, the charge is booked as owed. |
| Gateway batched | Not charged: the same settlement path as x402. | A 402 with Retry-After; resend the same payment to be served; a payment that settles and is never served is booked as owed. | Same budget rule as x402. |
| MPP evm | Not charged: the same settlement path as x402. | Same as x402. | Same as x402. |
| Tempo charge | Not charged: the credential is broadcast only after a response below 400. | A 402 and nothing broadcast. | Same budget rule as x402. |
| Tempo push | The transfer was already on chain: the amount is booked as owed to you. | Booked as owed. | Booked as owed. |
| card | Nothing captured. | Nothing captured. | Same budget rule as x402. |
| credits | The hold is released; the balance is unchanged. | Not debited. | The hold is released while the budget holds; past it, the debit is booked as owed. |
| Lightning | Paid before the run: recorded as owed and repaid in sats on your claim. | Not applicable: the payment is final before the run. | Recorded as owed when you left before the first byte. |
| proof-of-work | The solution is spent; fetch a new challenge. | Not applicable: nothing settles. | Fetch a new challenge. |
Some calls are paid before they run. If one fails, send the same payment again to retry it free, or it is refunded.
A hang-up before the first byte
The hang-up budget is bounded on purpose. A buyer whose connection closes before the first response byte is not settled while the service holds a forgiveness ticket for that request, priced at the charge, against a per-wallet, per-IP and service-wide budget that a paid success never refills. It never refuses service: once it is spent, the call settles as usual and the charge is booked as owed, repaid after on-chain proof. Routes whose effect outlives the answer (memory writes, attestations, purchases from outside sellers) never take a ticket.
Retries with an Idempotency-Key
Retries. Send an Idempotency-Key header (or the x402 payment-identifier extension) and a repeat of the same credential, route and body within 10 minutes replays the settled 200 (answers up to 1 MB) without a second settlement. On the x402 wallet path the key is bound to the exact signed authorization: a fresh signature is a fresh payment, so keep the signed request and resend it yourself, or use a credits key for the calls you retry. A request re-sent with the same signed EVM payment and no key is replayed the same way inside that window (X-Replayed-Answer: 1); routes with a lasting effect and streamed calls are the exception.
Refunds. A charged-but-undelivered call is recorded as a debt with its settlement transaction as evidence and repaid from a separate, capped job after review; the server never holds a spending key.
Where to check.
- /api/pricing: each route's price, networks and
computePayable. - /.well-known/x402: the manifest, with this instance's chains and MPP methods.
- /x402-test: why a client was refused on a real paid route.
- /proof: settled receipts beside their quotes.
- /status: the paid path, measured from outside.
- /revenue: every settlement on these rails.