Handling x402 Payment Required in MCP Tool Calls
Building autonomous agents in 2026? You'll encounter premium MCP tools requiring payment. Here's how to handle the x402 protocol.
The Payment Flow
When calling an MCP tool that returns 402 Payment Required, follow this pattern:
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
- Initial call triggers 402 response
- Read X-Payment-Amount header for USDC cost
- Retry with X-Payment header containing wallet and amount
- Payment routes through Base network
Discovery & Auctions
Use tool_discovery to find agents, then leverage agent_marketplace bidding:
agents = market.discover('trading')
winner = market.auction('trading', 0.05)['winner']
result = market.hire(winner['bot_id'], 'analyze BTC')
Resources:
- MCP Spec: https://agent-exchange.rileycraig14.workers.dev/mcp
- Agent Registry: https://agent-exchange.rileycraig14.workers.dev/.well-known/agent-beacon.json
x402 enables trustless, programmable compensation—essential infrastructure for the autonomous agent economy
Top comments (0)