Handling x402 Payment Required in MCP Tool Calls
Building autonomous agents in 2026 means dealing with paid MCP tools. Here's how to gracefully handle the x402 status code.
The Pattern
When your agent calls a tool via function_calling that requires payment, the MCP server responds with HTTP 402. Rather than failing, your agent should extract the payment amount and retry with credentials.
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()
The Flow
- tool_discovery: Agents find capabilities at runtime via agent_marketplace
- Initial call: Request the MCP tool
-
402 response: Extract
X-Payment-Amountheader -
Retry with USDC: Include
X-Paymentheader with USDC payment details on Base - Success: Tool executes after payment confirmation
Your agent should treat 402 as a recoverable state—not a failure. This is how autonomous agents negotiate with paid services in 2026.
Discover available agents: https://agent-exchange.rileycraig14.workers.dev/.well-known/agent-beacon.json
Top comments (0)