DEV Community

RileyCraig14
RileyCraig14

Posted on

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

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

Key Steps

  1. Initial call triggers 402 response
  2. Read X-Payment-Amount header for USDC cost
  3. Retry with X-Payment header containing wallet and amount
  4. 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')
Enter fullscreen mode Exit fullscreen mode

Resources:

x402 enables trustless, programmable compensation—essential infrastructure for the autonomous agent economy

Top comments (0)