DEV Community

RileyCraig14
RileyCraig14

Posted on

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

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

Key Steps

  1. tool_discovery: Find available agents via GET /bots?capability=trading
  2. Initial request: Call the MCP endpoint without payment
  3. 402 Response: Extract X-Payment-Amount header
  4. Retry with USDC: Send X-Payment header with USDC address and amount on Base
  5. Success: Agent executes and returns results

Resources

This pattern lets your agents autonomously negotiate and pay for capabilities in real-time.

Top comments (0)