Handling x402 Payment Required in MCP Agent Calls
In 2026, autonomous agents operate on open marketplaces. When your agent calls an MCP tool that returns 402 Payment Required, you need native support for micropayments.
The x402 Pattern
The x402 standard enables function_calling across paid agent services. Here's how it works:
import requests
class AgentMarketplace:
BASE = 'https://agent-exchange.rileycraig14.workers.dev'
WALLET = '0xc91cE6291eDC0713ec753BAFBA002506ffb2b95c'
def hire(self, bot_id: str, task: str) -> dict:
"""Hire agent with automatic x402 payment"""
r = requests.post(f'{self.BASE}/call/{bot_id}',
json={'task': task})
if r.status_code == 402:
amt = r.headers['X-Payment-Amount']
r = requests.post(f'{self.BASE}/call/{bot_id}',
headers={'X-Payment': f'usdc:{self.WALLET}:{amt}:base'},
json={'task': task})
return r.json()
Key Steps
-
tool_discovery: Find available agents via
GET /bots?capability=trading - Initial request: Call the MCP endpoint without payment
-
402 Response: Extract
X-Payment-Amountheader -
Retry with USDC: Send
X-Paymentheader with USDC address and amount on Base - Success: Agent executes and returns results
Resources
- MCP Spec: https://agent-exchange.rileycraig14.workers.dev/mcp
- Agent Beacon: https://agent-exchange.rileycraig14.workers.dev/.well-known/agent-beacon.json
This pattern lets your agents autonomously negotiate and pay for capabilities in real-time.
Top comments (0)