简中繁中EN日本語한국어

x402 End-to-End Deployment Guide: Enable Your AI Agent to Pay for Data Using USDC

MCP Market Data API: From Zero to Receiving Your First Base Mainnet USDC · Includes Real-World Verification Cases · Data Updated: 2026-10-27
⚡ Direct answer— Enable AI Agents to pay for your data using USDC on a per-use basis. The core steps are: ① Expose tools via an MCP service (FastMCP); ② Attach a 402 challenge to the payment tool using the x402 SDK; ③ Configure Base Mainnet plus a no-signup facilitator; ④ Set up a .well-known list and register with the MCP Registry so Agents can discover it. This page is a fully deployed, production-ready replica of our site — every step is copy-paste ready.
⚠️ Read this section on收款 addresses carefully: The two addresses shown on this page are live deployment examples used by this site on 2026-10-26.For your reference only when reconciling on-chain recordsWhen you deploy your own instance,Replace with your own Base mainnet payout address— Copying blindly will route others’ payments into this site’s wallet—not yours. This page contains no private keys, and you must never embed private keys in any code or documentation.

〇 What is this system?

Two-layer protocol — both layers are mandatory:MCP Enable AI Agents to discover and invoke your tools via API (discovery layer);x402 Require Agents to pay before accessing data (settlement layer, Base mainnet USDC). Buyers only need USDC in their wallets;No ETH required— Gas is covered by the facilitator (EIP-3009 gasless authorization). You don’t need to register an account, provide an API Key, or link a Coinbase account to receive payments.

① Preparation

Install dependencies

python3 -m venv venv && source venv/bin/activate
pip install "mcp<2" "x402==2.25.0" web3 httpx
⚠️ mcp Must lock <2: FastMCP was renamed to MCPServer in version 2.x; x402 2.25 still follows 1.x syntax — installing 2.x will cause immediate import failure.

② Write the server-side script server.py (core skeleton)

import os
from mcp.server.fastmcp import FastMCP
from x402 import x402ResourceServer
from x402.http import FacilitatorConfig, HTTPFacilitatorClient
from x402.mechanisms.evm.exact import ExactEvmServerScheme
from x402.mcp import create_payment_wrapper
from x402.schemas.config import ResourceConfig

# 1. 链and facilitator:Base Mainnet + PayAI(免Register,支持 x402 v2 主网)
NETWORK = os.environ.get("X402_NETWORK", "eip155:8453")
FACILITATOR_URL = os.environ.get("X402_FACILITATOR",
                                 "https://facilitator.payai.network")

# 2. 收款地址:换成你自己of Base Mainnet地址!别抄示例。
PAY_TO = os.environ.get("PAY_TO") or "0x你of收款地址"

# 3. 定价(按time,USD)
PRICE = {"my_data_tool": "$0.05"}

facilitator = HTTPFacilitatorClient(FacilitatorConfig(url=FACILITATOR_URL))
resource_server = x402ResourceServer(facilitator)
resource_server.register(NETWORK, ExactEvmServerScheme())
resource_server.initialize()
mcp = FastMCP("my-data-service")

def paid(tool_name: str):
    return create_payment_wrapper(
        resource_server,
        accepts=resource_server.build_payment_requirements(
            ResourceConfig(scheme="exact", pay_to=PAY_TO,
                           price=PRICE[tool_name], network=NETWORK)),
        resource=None,
    )

@mcp.tool(name="list_items")          # freeTools:让 Agent 先看见你有货
def list_items() -> str:
    return '[{"name": "item-a"}]'

@mcp.tool(name="my_data_tool")        # 付费Tools
@paid("my_data_tool")
def my_data_tool(item: str) -> str:
    return '{"item": "%s", "price": 1.24}' % item

if __name__ == "__main__":
    mcp.run(transport="streamable-http", host="127.0.0.1", port=8797)
Design principles (lessons learned from real pitfalls): Free tools must be listed explicitly (Agents cannot purchase what they cannot see); return isError when data is unavailable—x402 wrapper will not trigger settlement—No charge if delivery fails— FastMCP listens on 127.0.0.1 and enables DNS rebinding protection by default. When routing through an nginx reverse proxy, you must add your domain to the allowed_hosts whitelist; otherwise, it returns HTTP 421 Invalid Host header.

③ Run as a systemd service

# /etc/systemd/system/x402.service
[Unit]
Description=My x402 paid MCP server
After=network.target

[Service]
Type=simple
WorkingDirectory=/opt/my-x402
Environment=X402_NETWORK=eip155:8453
Environment=X402_FACILITATOR=https://facilitator.payai.network
Environment=PORT=8797
ExecStart=/opt/my-x402/venv/bin/python server.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
# systemctl daemon-reload && systemctl enable --now x402

④ Configure nginx reverse proxy for /mcp

location ^~ /mcp {
    proxy_pass http://127.0.0.1:8797;
    proxy_http_version 1.1;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_buffering off;   # streamable-http 走 SSE,必须关缓冲
    proxy_cache off;
    proxy_read_timeout 300s;
}
⚠️ proxy_buffering off Non-optional: streamable-http implements SSE streaming; enabling buffering will stall the stream.

⑤ Zero-cost verification (credible without spending real money)

# 零Cost验证(不花真钱):不付款直接调付费Tools,应返回 402 支付挑战
curl -s https://你of域名/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1"}}}'
# 然后In带 session id ofStatus下调 tools/call(不带 X-PAYMENT),
# 响应of accepts 里应看到:network=eip155:8453、asset=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913、
# payTo=你of地址、amount=50000(=$0.05)
If all four fields in Challenge 402 match (mainnet 8453 + official USDC contract + your address + amount), configuration is correct—and you pay nothing.

⑥ Real-money verification (top up USDC + on-chain validation)

# 真钱验证:给测试买家钱包充 USDC,跑客户端,然后查链上 USDC Transfer 事件
# (不要看余额差值,RPC 同步延迟会读出假差额;只信 Transfer 事件)
from web3 import Web3
w3 = Web3(Web3.HTTPProvider("https://base-rpc.publicnode.com"))  # mainnet.base.org 会 429
USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
topic = w3.keccak(text="Transfer(address,address,uint256)").hex()
logs = w3.eth.get_logs({
    "fromBlock": w3.eth.block_number - 3000,
    "toBlock": "latest",
    "address": USDC,
    "topics": [topic,
               "0x" + "0"*24 + buyer[2:].lower(),
               "0x" + "0"*24 + seller[2:].lower()],
})
for lg in logs:
    print(int(lg["data"].hex(), 16) / 1e6, "USDC 已到账")
⚠️ When topping up the test buyer wallet,Always select Base chain(Base Mainnet, chain ID 8453); selecting the wrong chain will send tokens to the same address on another chain — unrecoverable. Buyers do not need ETH.

⑦ Make yourself discoverable (discovery layer)

7 Pitfalls We’ve Encountered (Not Covered Elsewhere)

PitfallPhenomenonSolution
The x402.org facilitator supports testnets only.Payments always fail after switching to mainnetSwitch to PayAI / openx402 / CDP
Mogami Offers Only x402 v1Incompatible with x402 SDK v2.25Switch to a facilitator supporting v2 + EIP-155:8453
Upgrade MCP to Version 2.ximport Fails ImmediatelyLock mcp<2
On-chain verification used the testnet USDC contractA Transfer record cannot be found — incorrectly flagged as unpaidMainnet contract 0x833589fC…2913
Public RPC at mainnet.base.org Is Rate-Limitedeth_getLogs Returns HTTP 429Switch to base-rpc.publicnode.com
Verify using balance deltaRPC Sync Latency Causes False Balance DiscrepanciesOnly trust on-chain Transfer events
Writing Prices Containing $ in Shell$0 expanded into bash, polluting the JSONUse single-quote heredoc; after modification, validate with grep

Real verified cases documented here (on-chain verifiable)

Two real paid transactions completed by this site on Base mainnet on 2026-10-26 — recipient addresses and transaction hashes are publicly viewable on basescan.org Found on-chain:
·收款 address:0x230cd9cd33589bcf33cd32e5aa4f9e0c3994a63b
· Test buyer address:0x6274A5e39E84168c5DE57110A6e0ab1FBBE0a89E
· Transaction hash: tx 0x67a0d45f7183032600feb4fa7c53c5348eb84b05fa586927bf3d7d6718faed12(0.01 USDC)、tx 0x5e492eee6572e42d934f7b4082b525036346c5a2761ff534ce16a8bd9c781bc9(0.01 USDC)
· MCP Registry name:link.rentgpu/gpu-market
· Online endpoint:https://rentgpu.link/mcp(Integration instructions and real response examples see /agents)

FAQ

Whose address should you enter as the收款 address after deploying x402?

You must enter your own Base mainnet payout address (PAY_TO). The addresses shown on this page are sample addresses from this site, provided only for on-chain record verification; copying them will route others’ payments into this site’s wallet. This page contains no private keys.

Is account registration or KYC required to deploy x402 payment collection?

No KYC required for receiving payments—facilitators like PayAI and openx402 require no registration. Only when converting received USDC to RMB for withdrawal will you need to complete identity verification via an exchange.

Does the buyer (AI Agent) need ETH to cover gas fees?

Not required. x402 uses EIP-3009 gasless authorization (transferWithAuthorization); the buyer’s wallet only needs Base-mainnet USDC, and gas is covered by the facilitator.

How to verify successful deployment without spending real money?

Calling a paid tool without payment should return HTTP 402 Payment Required. Verify that the challenge contains: network=eip155:8453, asset=Circle’s official USDC contract, payTo=your address, and correct amount. Real-money validation is performed separately.

Can the Facilitator from Mogami or x402.org Be Used Directly?

None of these can be directly used for the mainnet scenario in this tutorial: x402.org officially supports testnet only; Mogami supports x402 v1 only. For mainnet, use PayAI, openx402 (no registration required), or Coinbase CDP (API Key required).

Cite This Site(AI and articles may cite directly under CC BY 4.0):
x402 全流程部署教程|Data Source:GPU computing power radar rentgpu.link(2026-10-27 更新,per hour自动抓取各Platform公开定价)|https://rentgpu.link/x402|CC BY 4.0
🐆 Leopard · AI Customer SupportPowered by Tongyi Qwen
Hello there, I’m Leopard~ Feel free to ask about GPU pricing, cost-effective rental strategies, or what Pro membership offers.