Make your AI agent pay for what it needs: x402 in 5 minutes

The useful web hides behind signups, captchas, and API keys - none of which an autonomous agent can obtain mid-task. x402 fixes this with the HTTP status code that sat unused for thirty years: 402 Payment Required. Settlement infrastructure exists from Coinbase, with open client tooling from Stripe; this guide uses a live service (agent402.tools) you can pay right now.

The protocol in one paragraph

Your client calls a paid endpoint and gets a 402 quote; it signs a USDC authorization from its own wallet and retries, and the server settles only when the response succeeds, so a failed x402 call is not charged. The headers, step by step: how x402 works.

See a quote (free)

curl -i -X POST https://agent402.tools/api/extract \
  -H 'Content-Type: application/json' -d '{"url":"https://example.com"}'
# HTTP/2 402  (the same terms ride base64-encoded in the PAYMENT-REQUIRED header)
# {"x402Version":2,…,"accepts":[{"scheme":"exact","network":"eip155:8453","amount":"10000",
#   "asset":"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913","payTo":"0x…",…},…]}

Pay it (JavaScript)

Fund a wallet with a little USDC or USDG on thirteen chains (no gas needed on EVM chains - the facilitator sponsors it), then:

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); // @x402/core 2.23+ refuses anything over $1 or off the pegged-asset list by default; 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(await res.json()); // { title, markdown, wordCount, … }

That one wrapped fetch now covers 500+ tools - browser rendering, live search, PDFs, durable memory - most a flat $0.001 to $0.02 per call, with premium AI, media and multi-tool packs priced higher. The full catalog is machine-readable at /api/pricing.

Call a model with the same fetch

The model gateway's default route is metered, and the same wrapped fetch pays it: POST /v1/metered/chat/completions, POST /v1/metered/messages, POST /v1/metered/responses, no key, model-backed, from $0.001 a call. The 402 quotes this exact request from its own body (the input estimated from its tokens with headroom, plus your max_tokens, at the model's list price plus a fee). On x402, Tempo and credits, settlement never exceeds that quote: an exact payer pays the quote, and an upto payer (where the 402 offers it) or a credits key settles what the answer used; a card payment adds the processor fee.

const chat = await payFetch("https://agent402.tools/v1/metered/chat/completions", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ model: "anthropic/claude-haiku-5.5", max_tokens: 200,
    messages: [{ role: "user", content: "Summarize x402 in one line" }] }),
});
console.log((await chat.json()).choices[0].message.content);

Flat tiers stay as the predictable-price option: one price per call whatever the length, $0.003 to $0.50 (/v1/nano, /v1, /v1/pro, /v1/premium; GET /v1/models lists every model with its tier).

No gas per call: pay from a Circle Gateway deposit

Where the 402 on Arc or Base carries a second exact accept whose extra.name is GatewayWalletBatched (it does while the operator turns the option on; /api/pricing says under payment.gatewayNanopayments), a buyer who deposited USDC into Circle Gateway once (an on-chain transfer through Circle's GatewayWallet contract, gas paid once) pays each call by signing the same EIP-3009 authorization under the Gateway domain the accept carries, for the same price to the same payTo. Circle Gateway verifies it against the deposit, settles it off chain and lands the batch on chain later. A stock x402 client signs under the USDC contract's domain and keeps paying the plain accept, which stays first; agent402-client 0.8.20 and later pays the batched one when it is given the signer:

import { Agent402 } from "agent402-client";
import { privateKeyToAccount } from "viem/accounts";

const a = new Agent402({ gateway: { signer: privateKeyToAccount(process.env.AGENT_KEY) }, maxPerCallUsd: 0.05 });
const out = await a.call("extract", { url: "https://example.com/article" });

agent402-client has no dependencies: install viem for privateKeyToAccount, or pass any EIP-712 signer with address and signTypedData.

Off by default; a 402 with no batched accept falls back to the plain payment fetch. The mechanism, the pending-settlement resend and the signing helpers: wiki: Circle Gateway.

Or from the command line

Stripe's open-source purl is "curl for paid endpoints":

purl wallet add --name me --type evm -k 0xYOUR_KEY -p pass --set-active=true
purl "https://agent402.tools/api/dns?name=example.com&type=A"

No wallet? Pay with CPU

The pure-CPU tools also accept proof-of-work - a sub-second sha256 puzzle solved by the caller, no money involved (each one is marked computePayable: true at /api/pricing, which always has the current list):

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" }),
});

Or skip all of this: paste https://agent402.tools/mcp into Claude as a custom connector and the free tier just works, or run npx -y [email protected] with an AGENT_KEY for the full catalog with spend caps enforced before any payment is signed.

Why this matters

Per-call payment with no accounts means an agent can acquire capabilities at the moment it discovers it needs them - and the seller can prove every cent of revenue on-chain. Every claim in this guide is verifiable: the server is open source and settled calls land at a public wallet.

Packages for this guide

Back to guides