mcptry.com

Guide

x402: pay per call, no API key

Most MCP servers that cost money want you to sign up, pick a plan and paste an API key. That works for people and is awkward for agents: an agent can't fill in a signup form, and a key that works everywhere is a key that can be leaked. x402 takes the other route. The server answers an unpaid request with a price, the client signs a stablecoin payment for exactly that amount, and the same request goes through. No account, no key, and nothing to cancel later.

244 MCP servers in the registry took x402 payments when we last checked.

How it works over HTTP

  1. A request with no payment gets 402 Payment Required. The PAYMENT-REQUIRED header holds base64 JSON listing what the server accepts: the scheme, the network (as a CAIP-2 id like eip155:8453 for Base), the token, the amount and the address to pay. Amounts are in the token's smallest unit: USDC has 6 decimals, so 3000 is $0.003.
  2. The client signs an authorization to transfer exactly that amount (EIP-3009 transferWithAuthorization for USDC) and sends the same request again with a PAYMENT-SIGNATURE header. Older v1 clients send X-PAYMENT.
  3. The server has a facilitator verify the signature, does the work, then settles. The answer carries a PAYMENT-RESPONSE header with the transaction hash.

The facilitator submits the transfer and pays the gas. So the buyer needs USDC and no ETH, and the seller needs only an address to be paid to: no private key ever sits on the server.

How it works over MCP

The @x402/mcp package puts the same exchange inside MCP messages. initialize and tools/list stay free, so any client can see what's on offer. An unpaid tools/call comes back as a tool result with isError: true and the PaymentRequired in structuredContent (and as JSON in the first text block). The tool hasn't run. The client pays in the call's _meta["x402/payment"] and calls again; the settlement comes back in _meta["x402/payment-response"].

An unpaid call looks like this, and is free to try against any server with the x402 badge:

curl -s "$MCP_URL" \
  -H 'content-type: application/json' \
  -H 'accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"fortune","arguments":{"topic":"x"}}}'
{
  "x402Version": 2,
  "error": "Payment required to access this tool",
  "resource": { "url": "mcp://tool/fortune" },
  "accepts": [{
    "scheme": "exact",
    "network": "eip155:84532",
    "amount": "10000",
    "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
    "payTo": "0xYOUR_RECEIVING_ADDRESS",
    "maxTimeoutSeconds": 300,
    "extra": { "name": "USDC", "version": "2" }
  }]
}

A well-behaved server settles only after the tool succeeds and cancels otherwise, so a failed call is never charged. createPaymentWrapper from @x402/mcp does this for you.

Walkthrough: charge for a tool, then pay for it

This runs end to end on Base Sepolia, a test network, so the money is free test USDC. You'll build an MCP server with one paid tool, then call it from a client that pays. It needs Node 22 or later.

1Install the packages

npm install @modelcontextprotocol/sdk @x402/core @x402/evm @x402/mcp viem zod

2Make a buyer wallet

A new key just for testing, written to buyer.env and never printed. Only the address shows. Keep the file out of git.

node --input-type=module -e '
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
const key = generatePrivateKey();
console.log("BUYER_KEY=" + key);
console.error("buyer address: " + privateKeyToAccount(key).address);
' > buyer.env
chmod 600 buyer.env

3Get test USDC

Paste the buyer address into Circle's faucet (choose Base Sepolia) or the Coinbase developer faucet. No test ETH needed: the facilitator pays the gas.

4Write the server

The receiving address can be any wallet you control, such as a MetaMask account. The testnet facilitator at x402.org needs no key.

// server.mjs: one paid tool, $0.01 a call in test USDC on Base Sepolia.
import { createServer } from "node:http";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { x402ResourceServer, HTTPFacilitatorClient } from "@x402/core/server";
import { ExactEvmScheme } from "@x402/evm/exact/server";
import { createPaymentWrapper } from "@x402/mcp";
import { z } from "zod";

const NETWORK = "eip155:84532"; // Base Sepolia
const facilitator = new HTTPFacilitatorClient({ url: "https://x402.org/facilitator" });
const x402 = new x402ResourceServer(facilitator).register(NETWORK, new ExactEvmScheme());
await x402.initialize();

const accepts = await x402.buildPaymentRequirements({
  scheme: "exact", network: NETWORK, payTo: process.env.PAY_TO, price: "$0.01",
});
const paid = createPaymentWrapper(x402, {
  accepts,
  resource: { url: "mcp://tool/fortune", description: "A fortune for any topic", mimeType: "text/plain" },
});

function mcpServer() {
  const server = new McpServer({ name: "fortune", version: "1.0.0" });
  server.registerTool("fortune", {
    description: "A fortune for any topic. $0.01 a call, paid with x402 (USDC on Base Sepolia).",
    inputSchema: { topic: z.string() },
    annotations: { readOnlyHint: true },
  }, paid(async ({ topic }) => ({
    content: [{ type: "text", text: `Good news about ${topic} is on its way.` }],
  })));
  return server;
}

// Stateless streamable HTTP: a fresh server and transport per request.
createServer(async (req, res) => {
  const server = mcpServer();
  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
  res.on("close", () => { transport.close(); server.close(); });
  await server.connect(transport);
  let body = "";
  for await (const chunk of req) body += chunk;
  await transport.handleRequest(req, res, body ? JSON.parse(body) : undefined);
}).listen(4022, () => console.log("http://localhost:4022/mcp"));
PAY_TO=0xYOUR_RECEIVING_ADDRESS node server.mjs

5Write the client and pay

// pay.mjs: call a paid tool; the client pays when asked, up to the cap.
import { createx402MCPClient } from "@x402/mcp";
import { ExactEvmScheme } from "@x402/evm/exact/client";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount(process.env.BUYER_KEY);
const client = createx402MCPClient({
  name: "my-agent",
  version: "1.0.0",
  schemes: [{ network: "eip155:84532", client: new ExactEvmScheme(account) }],
  spendControls: { maxAmountPerPayment: "$0.05" }, // refuse anything pricier
  autoPayment: true,
});
await client.connect(new StreamableHTTPClientTransport(new URL(process.env.MCP_URL)));

const result = await client.callTool("fortune", { topic: "your launch" });
if (result.isError) {
  // Still unpaid: the text says why, e.g. invalid_exact_evm_insufficient_balance.
  console.log("not paid:", result.content?.[0]?.text);
} else {
  console.log(result.content?.[0]?.text);
  console.log("transaction:", result.paymentResponse?.transaction);
}
await client.close();
MCP_URL=http://localhost:4022/mcp node --env-file=buyer.env pay.mjs

It prints the fortune and the transaction hash. Look the hash up on Base Sepolia's explorer: 0.01 USDC moved from the buyer to your receiving address. Run the curl above against http://localhost:4022/mcp to see the unpaid answer.

Going live

Server: switch the network to Base (eip155:8453) and the facilitator to one that settles on mainnet. Coinbase's needs a CDP Secret API key, read through @coinbase/x402. Any facilitator that answers /supported, /verify and /settle works the same way.

import { createCdpAuthHeaders } from "@coinbase/x402";

const NETWORK = "eip155:8453"; // Base
const facilitator = new HTTPFacilitatorClient({
  url: "https://api.cdp.coinbase.com/platform/v2/x402",
  createAuthHeaders: createCdpAuthHeaders(process.env.CDP_API_KEY_ID, process.env.CDP_API_KEY_SECRET),
});

Say the price and “x402” in the tool description, so people and models know before they call. The 402 can also carry extensions.bazaar (from @x402/extensions), so facilitators can list the tool in the x402 Bazaar; the output is only listed if it includes an example.

Client: the same code with eip155:8453 and a wallet holding real USDC on Base. Treat an agent's wallet like a prepaid card: a few dollars, topped up as needed. x402Client refuses any single payment over $1 by default; spendControls.maxAmountPerPayment lowers that, and policies can limit payments to addresses you trust.

Gotchas

  • CDP key allowlists and IPv6. If your server reaches Coinbase over IPv6, an IPv4-only allowlist on the API key answers 401 Unauthorized from /supported. Allow both addresses (/32 and /128).
  • Proxies hide your errors. Cloudflare replaces a 502 from your origin with its own HTML page, so a “facilitator unavailable” answer never reaches the client. Answer facilitator outages with 503.
  • Test tokens don't show in MetaMask until you turn on test networks, add Base Sepolia and import the test USDC contract (0x036CbD53842c5426634e7929541eC2318f3dCF7e). The explorer's token transfers tab is quicker.
  • Funding a wallet. Sending USDC from MetaMask needs a little ETH on Base for gas; an exchange withdrawal on the Base network doesn't. Pick the network carefully: on the wrong one, the funds land on another chain.
  • Not every 402 is x402. Hosts send 402 when an owner's plan runs out (Vercel's DEPLOYMENT_DISABLED, for one), and some servers send 402 with their own checkout link. Only a body or header with an accepts list is something an x402 client can pay.

Servers that take x402 now

We list a server here only after we've seen it ask for an x402 payment ourselves, from an unpaid tool call or a 402 at connect time. Mentioning x402 in a description isn't enough. How we check. If yours takes x402 and isn't here, make sure it's in the MCP Registry and its paid tool is marked readOnlyHint or says x402 in its description; the check runs weekly.