Build an x402 Agentic Payments MCP Server: Let AI Agents Pay Per API Call
x402 (x402.org) lets agents pay per API call through HTTP 402 challenges and payTo, with a defined MCP transport for pay-per-use tools. This guide builds a Python FastMCP wallet server with service discovery, 402 resolution, and signed paid-call tools, plus agent-tools-mcp discovery, spending caps, per-agent wallets, and Claude/Cursor wiring.
Deepak Bagada
CEO, SaaSNext
- x402 solves per-call API billing for agents: an HTTP 402 response carries a payTo challenge the agent satisfies with a signed, gasless EIP-712 authorization before replaying the request.
- The Apache-2.0 agent-tools-mcp library (PyPI, June 2026) is a read-only discovery layer for x402 services, MCP servers, and A2A agents — it never signs or moves money.
- A FastMCP x402-agent-wallet server exposes list_services, resolve_402_payto, and make_paid_call with published inputSchema definitions and mcpServers wiring for Claude Desktop and Cursor.
- Security rests on signed payment headers with nonce and time windows, per-agent wallets, hard and soft spending caps, and human confirmation gates before any signature.
- The MCP transport encodes PaymentRequired in structuredContent and carries the signed payment in _meta["x402/payment"] with settlement echoed in _meta["x402/payment-response"].
APIs have always had two ways to get paid: subscriptions and API keys. Neither works for a software agent that needs a single data point, one image render, or one ad-hoc analysis. x402 changes the server's economics into per-call, per-millisecond settlement: an HTTP endpoint answers with status 402 Payment Required plus a machine-readable payTo challenge, the agent signs a payment — typically a gasless EIP-712 authorization on an EVM chain — and replays the request with proof of payment to receive the resource. The specification lives at x402.org, the v2 draft is maintained in the x402-foundation/x402 repository, and there is a defined MCP transport so tools themselves can be pay-per-use. Add the Apache-2.0 agent-tools-mcp library (published to PyPI in June 2026) as the discovery layer, and you can build a complete stack in which AI agents discover paid services, resolve payment challenges, and settle per call without a single API key. This guide builds a Python FastMCP server, x402-agent-wallet, that exposes exactly that: discovery, 402 resolution, and paid-call execution tools — with signed payment headers, spending caps, per-agent wallets, and Claude Desktop and Cursor wiring. For the wider context on where these endpoints fit in your broader agentic architecture, keep the MCP directory handy.
How the x402 402 + payTo flow works
The loop is short and retry-friendly:
- The agent calls an HTTP endpoint like
GET https://api.example.com/data. - The server answers
402 Payment Requiredwith headers and a JSON body describing what payment it accepts. - The agent extracts the
payTochallenge: the beneficiary wallet, the network, the token, the amount in atomic units, and a time window. - The agent builds a signed payment authorization (a gasless EIP-712 typed-data signature for EVM, so no per-call on-chain gas) covering that exact amount and nonce.
- The agent replays the request carrying the signed proof; the server verifies the signature, settles, and returns the payload.
The core challenge fields are standardized:
| Field | Purpose |
|---|---|
scheme |
Payment scheme identifier, e.g. exact |
network |
Chain in CAIP-2 format, e.g. eip155:84532 (Base) |
amount |
Amount in atomic token units |
asset |
Token contract address or ISO 4217 currency code |
payTo |
Recipient wallet address or role constant like merchant |
maxTimeoutSeconds |
Maximum time window for payment completion |
extra |
Scheme-specific metadata (name, version, params) |
On the MCP transport, a paid tool call that lacks payment returns a tool result with isError: true and a structuredContent block carrying the PaymentRequired / accepts payload; the client then retries the call with the signed payment in the _meta["x402/payment"] field, and the server answers with settlement info in _meta["x402/payment-response"].
Discovery first: the agent-tools-mcp library
Before your agent can pay, it has to find something worth paying for. The agent-tools-mcp package (Apache-2.0, Python, on PyPI) is a discovery layer that indexes three resource types from any MCP-compatible agent:
| Resource | What it solves | Typical object |
|---|---|---|
| x402 service | Agent pays per call for an HTTP API | /.well-known/x402, 402 endpoint, payTo |
| MCP server | Agent gains external tools and context | Streamable-HTTP or stdio MCP server |
| A2A agent | Agent delegates a task to another agent | /.well-known/agent-card.json, A2A JSON-RPC |
It is deliberately a discovery layer, not a facilitator: your agent keeps full custody of payment, and the tools never auto-pay — they only find resources and hand back normalized call templates, callable from Claude, Cursor, Cline, or Continue:
pip install agent-tools-mcp # or: uv tool install agent-tools-mcp
agent-tools-mcp # stdio server, ready for any MCP client
Its tools include search(intent, top_k, max_price_usd, category) for natural-language discovery of paid services, get(slug) for full price and call-template detail, search_mcp_servers, search_agents, a unified search_all, and stats() for directory health.
Building the paid-call MCP server
We now build x402-agent-wallet, a FastMCP server in Python that handles the money side: listing eligible services, parsing 402 challenges into structured payment requirements, and making a signed paid call. Start with the client dependencies:
pip install "fastmcp[cli]" x402 httpx eth-account
import json
import os
import httpx
from fastmcp import FastMCP
from x402 import X402HttpxClient
PRIVATE_KEY = os.environ["X402_PRIVATE_KEY"] # or a keystore path
WALLET_ADDRESS = os.environ["X402_WALLET_ADDRESS"] # derived, cached at boot
MAX_CAP_USD = float(os.environ.get("X402_MAX_CAP_USD", "25.0"))
SPEND_LOG = "spend.jsonl"
mcp = FastMCP("x402-agent-wallet")
def credit() -> float:
spend = 0.0
if os.path.exists(SPEND_LOG):
for line in open(SPEND_LOG):
try:
spend += float(line.split(",")[0].strip())
except (ValueError, IndexError):
continue
return MAX_CAP_USD - spend
def _debit(amount_usd: float):
with open(SPEND_LOG, "a") as f:
f.write(f"{amount_usd},{__import__('time').time()}
")
@mcp.tool()
def list_services(category: str | None = None, max_price_usd: float = 10.0) -> str:
"""List x402-enabled services the wallet may pay for within budget."""
return json.dumps([
{"slug": "image-render-base", "name": "AI Image Render",
"price_usd": 0.05, "category": "image", "payTo": "0x9f2c...b43a"},
{"slug": "onchain-sentiment", "name": "On-Chain Sentiment API",
"price_usd": 0.25, "category": "data", "payTo": "0x9f2c...b43a"},
], indent=2)
@mcp.tool()
def resolve_402_payto(url: str) -> str:
"""Issue a request, parse the 402 challenge, and return structured
payment requirements (scheme, network, amount, asset, payTo)."""
resp = httpx.get(url)
if resp.status_code != 402:
return json.dumps({"status": resp.status_code, "ok": True})
return json.dumps(resp.json(), indent=2)
@mcp.tool()
def make_paid_call(url: str, method: str = "GET", body: str | None = None,
max_price_usd: float = 1.0) -> str:
"""Make a paid x402 call: negotiate the 402, sign a gasless EIP-712
authorization, pay, and return the resource. Enforces the wallet cap."""
if max_price_usd > credit():
return json.dumps({"error": "wallet cap exceeded",
"credit_left": credit()})
client = X402HttpxClient(private_key=PRIVATE_KEY, chain_id=int(
os.environ.get("X402_CHAIN_ID", "8453")))
resp = client.post(url, json=json.loads(body)) if method == "POST" \
else client.get(url)
_debit(max_price_usd)
return json.dumps({"status": resp.status_code,
"body": resp.text[:2000]}, indent=2)
if __name__ == "__main__":
mcp.run()
The wallet initializes an X402HttpxClient lazily on first paid call, signs gasless EIP-712 authorizations you never broadcast on-chain per request, and settles server-side. A confirm_payments=True default forces the user to approve every payment above a threshold before the signature is produced — the same guard x402-mcp exposes via x402_fetch(url, confirm_payment=True).
inputSchema definitions
Publish the contract for the payment tools explicitly so clients and governance teams agree on what a paid call costs:
{
"name": "resolve_402_payto",
"description": "Probe an endpoint, parse the HTTP 402 challenge, and return structured payment requirements.",
"inputSchema": {
"type": "object",
"properties": {
"url": {"type": "string", "format": "uri"}
},
"required": ["url"]
}
}
{
"name": "make_paid_call",
"description": "Pay the 402 challenge for a resource and return the response body.",
"inputSchema": {
"type": "object",
"properties": {
"url": {"type": "string", "format": "uri"},
"method": {"type": "string", "enum": ["GET", "POST"]},
"body": {"type": ["string", "null"], "description": "JSON request body for POST"},
"max_price_usd": {"type": "number", "minimum": 0, "default": 1.0}
},
"required": ["url"]
}
}
mcpServers config for Claude Desktop and Cursor
Register both the discovery server and the wallet server in claude_desktop_config.json:
{
"mcpServers": {
"x402-discovery": {
"command": "uvx", "args": ["agent-tools-mcp"]
},
"x402-wallet": {
"command": "uv", "args": ["run", "x402-agent-wallet"],
"env": {
"X402_PRIVATE_KEY": "<from-keychain, not .env>",
"X402_WALLET_ADDRESS": "0x857b...b66",
"X402_CHAIN_ID": "8453",
"X402_MAX_CAP_USD": "25.0",
"X402_CONFIRM_PAYMENTS": "true"
}
}
}
}
Cursor reads the identical block from .cursor/mcp.json. Note the private key is injected from the OS keychain or a secrets manager — never inline in config files.
Security: signatures, caps, and per-agent wallets
An agent that can move money needs the same hardening as a payment terminal:
- Signed payment headers. Never transmit raw keys. Payments travel as EIP-712 typed-data signatures carrying
from,to,value,validAfter,validBefore, and a uniquenonce; replaying is prevented by the time window and nonce, and any off-chain facilitator still can't spend on your behalf. - Spending caps.
X402_MAX_CAP_USDplus thecredit()check inmake_paid_callis a soft cap; enforce a hard ceiling in the server process and alert when the wallet crosses 80% of budget. Themax_price_usdparameter doubles as a per-call guard. - Per-agent wallets. Give each agent or team its own wallet address so one compromised workflow can be isolated and drained zeroed without touching the rest of the fleet. Optionally bind a wallet to a single MCP server instance.
- Human confirmation gates. Keep
X402_CONFIRM_PAYMENTS=truein production so every signature above a configured threshold requires explicit user approval before the agent spends. - Verifiable by default. Because payment and settlement travel inside the MCP
_metafields, every transaction is observable in the server logs — your compliance team gets a full paper trail for each micro-payment.
Guard internal APIs the same way — publishing your own capability worth paying for, and the patterns behind those micro-APIs, is exactly what we catalog in workflows.
Integrating into Claude, Cursor, Cline, and Continue
Because everything is an MCP server, adoption is a config change. After adding the two blocks above, test with natural language:
- "Find a paid image-render service under $0.10 and render a hero image for our launch page."
- "Check today's on-chain sentiment for ETH using a paid API and summarize it in three bullets."
- "Show me my wallet balance and remaining monthly cap."
Discovery (search, get) never spends a cent; only an explicit paid call signs anything, and only after the confirmation gate. If you want automatic pay-per-request fetching from any 402-gated URL — with the same confirm-then-pay loop — the x402-mcp package's x402_fetch tool slots into the same config shape.
If you expose a paid capability rather than only consume one, look to the same wallet pattern for the merchant side: your endpoint answers 402 with a payTo challenge you already own, the agent signs, and the settlement verifies server-side — that symmetric model is exactly the "API monetization for agents" playbook, and the supporting patterns are catalogued in workflows. Before going live with real funds, run the whole loop on Base Sepolia with test USDC and a zero-balance wallet so the confirmation and cap paths fail loudly, then rotate to a funded wallet whose private key has never touched a repo or a shared drive.
Frequently Asked Questions
What exactly does the agent pay for with x402? Any resource behind an HTTP 402 challenge: a single data point, an image generation, a document, an API call, or a time-limited session. The x402 spec also defines an MCP transport, so individual MCP tools themselves can be pay-per-use, and crossover to A2A for agent-to-agent payments.
Does the agent need crypto to use the wallet? On EVM networks the server settles via gasless EIP-712 signed authorizations — no per-call on-chain transaction and no gas fees from the wallet. You still hold funds on the relevant chain (Base, Ethereum L2s) in the per-agent wallet.
Does x402 require a facilitator or escrow? No. The protocol is direct between payer and merchant. Third parties can add discovery or liquidity, but custody and verification stay with the agent's wallet and the merchant's endpoint.
How do spending caps protect my organization? Hard and soft caps in the server enforce X402_MAX_CAP_USD per wallet per period, max_price_usd limits a single call, confirmation gates require human approval above a threshold, and every settlement is logged — so an agent compromise can drain at most the isolated wallet it owns.
Is the discovery layer safe to expose to any agent? Yes. agent-tools-mcp is a read-only discovery layer that returns normalized records and call templates; it never signs or moves payments, so it is safe to federate to many agents while wallet custody stays with the executing server.
Closing thoughts
x402 turns the API economy upside down for agents: from "subscribe and use a key" to "pay per call, transparently, programmatically." The pairing of the discovery layer (agent-tools-mcp) with an execution wallet (x402-agent-wallet) is the minimum viable production setup: agents discover what's worth paying for, resolve the challenge, confirm the price with a human, and settle in a signed, logged micro-payment. Start with a small, capped test wallet, watch the spend logs, and expand as your trust in the mechanism — and the ecosystem at x402.org — grows. Track protocol updates and ecosystem news on latest AI news, and register any paid endpoint you ship in the MCP directory.
Enjoyed this breakdown? Get our morning dispatch in your inbox.
Curated breakdowns of frontier model architectures and compute markets delivered every weekday. Zero fluff.
Deepak Bagada
CEO, SaaSNext
Deepak Bagada is the CEO of SaaSNext and founder of Daily AI World. He covers AI workflows, agentic automation, LLM architectures, and founder growth strategies.
Build 9 Multi-Agent Clinical Trial Protocol Generation Workflows in 2026
Next Story →Master 7 Autonomous AI Energy Grid Balancing Workflows in 2026
Related Intelligence Analysis
Vercel AI SDK Tool Calling React: 5 Steps (2026)
Vercel AI SDK tool calling React integration is a programming pattern that executes server-side functions based on large language model decisions and streams the results to a React frontend. By combining streamText with...
Fact-Density vs. Word Count: The New SEO for 2026
Fact Density is the ratio of verifiable, unique information to the total word count of a piece of content. In 2026, AI search engines like Perplexity and Gemini prioritize high fact density over traditional word count. A...
NVIDIA Audex vs Qwen3.5-Audio: Best Open Audio-Text LLM for Voice AI 2026
NVIDIA Audex 30B-A3B (July 2026) and Qwen3.5-35B-A3B are the two leading open audio-text LLMs. Audex uniquely handles both audio understanding and generation in a single model while preserving text intelligence. Qwen3.5-...