x402 + MCP Tutorial: Build an AI Agent That Pays for APIs Autonomously
What You Will Build
By the end of this tutorial you will have an MCP-enabled AI client (Claude Desktop, Cursor, or Windsurf) that can fetch paid APIs over x402 without any human in the loop. You will ask the agent something like "fetch the latest article from this paid endpoint and summarize it," and the agent will:
- Call
call_x402_endpointwith the URL. - The MCP server fetches the URL.
- The endpoint returns
402 Payment Requiredwith payment instructions. - The MCP server pays the fee from the agent's MoltPe wallet (subject to spending policies).
- The server retries the request with the payment proof.
- The endpoint returns the content.
- The agent receives the content and continues with the user's request.
Total round-trip is typically under one second. The agent has no awareness of the payment handshake; it just gets the data it asked for.
Prerequisites
- An MCP-aware client installed: Claude Desktop, Cursor, Windsurf, or Cline.
- Node.js 18 or higher (the MCP server runs via npx).
- A few dollars of testnet or mainnet USDC for funding the wallet.
- About 15 minutes.
If you have not used MCP before, the MCP payment tools guide covers the fundamentals before you start this tutorial.
Step 1: Create the Wallet
Go to moltpe.com/dashboard and sign up. Create a new agent wallet on Polygon PoS or Base. Set conservative spending policies for the tutorial:
- Daily spending limit: $5 USDC
- Per-transaction cap: $1 USDC
These are tight enough that no test mistake can cost more than a coffee, but loose enough to call most x402 endpoints in the wild (typical fees are $0.01 to $0.50). The full setup walk-through is in our wallet setup guide.
Fund the wallet with $1-2 of USDC. The dashboard shows the address and chain; copy carefully. Once funded, generate an API key under API Keys and copy it somewhere safe.
Step 2: Install the MCP Server
Edit your client's MCP configuration. The location varies:
- Claude Desktop:
~/Library/Application Support/Claude/claude_desktop_config.json(macOS) or%APPDATA%\Claude\claude_desktop_config.json(Windows). - Cursor: Settings → MCP → Add MCP Server.
- Windsurf: Settings → MCP Servers → Edit Config.
Add this block:
{
"mcpServers": {
"moltpe": {
"command": "npx",
"args": ["-y", "@moltpe/mcp-server"],
"env": {
"MOLTPE_API_KEY": "your-api-key-from-step-1"
}
}
}
}
Restart the client completely (quit and relaunch, do not just reload the window). MCP servers are loaded at startup.
Once the client restarts, open a new conversation. The MoltPe tools should appear in the tool palette: send_payment, check_balance, list_transactions, agent_info, and call_x402_endpoint. If they don't, check the client's MCP log (each client exposes one) for connection errors.
Step 3: Call a Paid Endpoint
Open a new conversation and ask the agent to fetch an x402-paid URL. For testing, use any public x402 demo endpoint, or your own. A typical prompt:
Fetch this URL and tell me what it returns: https://api.example.com/x402-demo/article/42
The agent will recognize that this is a fetch task and call call_x402_endpoint with the URL. Behind the scenes:
- MCP server fetches the URL with a regular HTTP GET.
- Endpoint returns
402 Payment Requiredwith a JSON body specifying chain, amount, and recipient. - MCP server submits a payment request to MoltPe.
- MoltPe's policy engine validates the amount against your wallet's per-transaction cap and daily limit.
- If approved, MoltPe signs and broadcasts the USDC transfer (sub-second on Polygon PoS).
- MCP server retries the original request with the payment proof in a header.
- Endpoint validates the payment and returns the article.
- MCP server returns the article body to the agent.
The agent never sees any of the intermediate steps. From its perspective, it called a tool and got back content. The full protocol details are in our x402 complete guide.
Step 4: Verify the Audit Trail
Open the MoltPe dashboard and check the wallet's transaction history. You should see one new entry with:
- Status: completed
- Recipient: the x402 endpoint's payment address
- Amount: the fee charged by the endpoint
- Memo: usually the URL or a hash of it
- On-chain tx hash: clickable link to Polygonscan or Basescan
The on-chain hash is the proof that policy enforcement is verifiable and not just claimed. Click it; you can independently confirm on the block explorer that no transaction from your wallet ever exceeded the configured caps.
Extending the Pattern
Once the basic flow works, three extensions are obvious:
Multi-source research. Ask the agent to fetch five different paid sources and synthesize. The MCP server pays each fee independently and the agent gets back five response bodies. Total cost is the sum of fees; total wall time is roughly the slowest single fetch (since the MCP server runs them in parallel).
Selling your own x402 endpoint. The reverse direction. Run an x402 server (open-source implementations exist for Express, FastAPI, Fastify) that charges agents to call your API. Receive USDC into a MoltPe wallet. This is the simplest possible business model for AI-native APIs.
Agent-to-agent commerce. One agent calls another agent's x402 endpoint as part of a multi-agent workflow. The whole transaction graph is on-chain auditable. Each agent has its own wallet, its own policies, and its own audit trail. This pattern is what early agent-to-agent marketplaces are built on.
For more on the broader autonomous-agent payment landscape, read our AI agent economy guide.
Frequently Asked Questions
What is x402?
x402 is an HTTP-native payment protocol that uses the long-dormant 402 Payment Required status code. When a client requests a paid endpoint, the server responds with 402 plus payment instructions. The client pays, retries the request, and the server returns the content. It is the most direct way to monetize APIs for autonomous AI agents.
Do I need to write any payment code?
No. The MoltPe MCP server exposes call_x402_endpoint as a single tool. The agent passes a URL, the server handles the entire 402 handshake (parsing the payment requirements, signing the transaction, retrying the request), and the agent gets back the final response body.
How do spending policies apply to x402 payments?
Identically to any other payment. When the MCP server attempts to pay an x402 fee, the request goes through MoltPe's policy engine. If the fee exceeds the per-transaction cap or pushes daily spending past the limit, the payment is rejected and the call_x402_endpoint tool returns a structured error to the agent.
Can I test x402 endpoints without spending real money?
Yes. Use Polygon PoS or Base testnets for development. Many public x402 demo endpoints accept testnet USDC. The MCP server reads the chain and amount from each endpoint's payment requirements, so testnet vs mainnet works transparently.
Ready to ship an x402-paying agent?
Free tier, sub-second settlement, and one MCP install gets you the full x402 toolchain.
Get Started Free →About MoltPe
MoltPe is AI-native payment infrastructure that gives AI agents isolated wallets with programmable spending policies for autonomous USDC stablecoin transactions. Live on Polygon PoS, Base, and Tempo. Free tier with zero gas fees. Supports x402, MPP, MCP, and REST API. Works with Claude Desktop, Cursor, and Windsurf. Non-custodial via Shamir key splitting.