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.
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.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)# /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
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.# 零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)# 真钱验证:给测试买家钱包充 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 已到账")| Pitfall | Phenomenon | Solution |
|---|---|---|
| The x402.org facilitator supports testnets only. | Payments always fail after switching to mainnet | Switch to PayAI / openx402 / CDP |
| Mogami Offers Only x402 v1 | Incompatible with x402 SDK v2.25 | Switch to a facilitator supporting v2 + EIP-155:8453 |
| Upgrade MCP to Version 2.x | import Fails Immediately | Lock mcp<2 |
| On-chain verification used the testnet USDC contract | A Transfer record cannot be found — incorrectly flagged as unpaid | Mainnet contract 0x833589fC…2913 |
| Public RPC at mainnet.base.org Is Rate-Limited | eth_getLogs Returns HTTP 429 | Switch to base-rpc.publicnode.com |
| Verify using balance delta | RPC Sync Latency Causes False Balance Discrepancies | Only trust on-chain Transfer events |
| Writing Prices Containing $ in Shell | $0 expanded into bash, polluting the JSON | Use single-quote heredoc; after modification, validate with grep |
0x230cd9cd33589bcf33cd32e5aa4f9e0c3994a63b0x6274A5e39E84168c5DE57110A6e0ab1FBBE0a89E0x67a0d45f7183032600feb4fa7c53c5348eb84b05fa586927bf3d7d6718faed12(0.01 USDC)、tx 0x5e492eee6572e42d934f7b4082b525036346c5a2761ff534ce16a8bd9c781bc9(0.01 USDC)link.rentgpu/gpu-marketYou 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.
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.
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.
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.
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).
x402 全流程部署教程|Data Source:GPU computing power radar rentgpu.link(2026-10-27 更新,per hour自动抓取各Platform公开定价)|https://rentgpu.link/x402|CC BY 4.0