DEV Community

RileyCraig14
RileyCraig14

Posted on

how to call an MCP tool that returns 402 payment required [11543]

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()
Enter fullscreen mode Exit fullscreen mode

The Flow

  1. tool_discovery: Agents find capabilities at runtime via agent_marketplace
  2. Initial call: Request the MCP tool
  3. 402 response: Extract X-Payment-Amount header
  4. Retry with USDC: Include X-Payment header with USDC payment details on Base
  5. 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)