DEV Community

Cover image for Building GoldBean: How I Created a Pay-Per-Call MCP Server with x402 Micropayments
GoldBean
GoldBean

Posted on

Building GoldBean: How I Created a Pay-Per-Call MCP Server with x402 Micropayments

Building GoldBean: How I Created a Pay-Per-Call MCP Server with x402 Micropayments

When AI agents need to call an API — OCR, text-to-speech, a language model — there's no simple "pay as you go" option. You sign up, create an API key, add a credit card, and commit to a monthly plan. For autonomous agents that make occasional calls, that's overkill. For developers building agent pipelines, it's friction at every step.

I built GoldBean to fix this: an MCP (Model Context Protocol) server that exposes 47 Baidu AI endpoints — 26 paid, 21 free — where payments happen per-call via the x402 protocol using USDC on Base. No API key, no registration, no monthly commitment. Just pay per call.

The Problem

Here's the friction every AI agent developer hits:

  1. API key management: Every AI service requires registration, email verification, and API key generation. Agents need to store and rotate these keys securely.
  2. Monthly subscriptions: Most AI APIs are priced as SaaS subscriptions. An agent making 50 calls/month shouldn't pay $29/month.
  3. Credit card requirements: International developers — especially those outside the US/EU — often can't get approved for credit card-based billing. China-based AI APIs like Baidu's require a Chinese phone number for registration.
  4. No native agent payment: Existing payment infrastructure (Stripe, PayPal) was designed for humans clicking buttons in browsers, not for autonomous agents making machine-to-machine API calls.

The gap is clear: agents need a way to pay for API calls programmatically, at the granularity of a single request, without human intervention.

The Solution: GoldBean MCP Server

GoldBean bridges this gap by combining three technologies:

  • MCP (Model Context Protocol): An open standard that lets AI agents like Claude discover and call external tools. GoldBean exposes its 47 endpoints as MCP tools via SSE transport.
  • x402 Payment Protocol: An HTTP-native micropayment standard. When an agent calls a paid endpoint without sufficient credits, the server returns HTTP 402 (Payment Required) with payment instructions. The agent pays USDC on Base L2, and the server verifies the on-chain transaction before returning the result.
  • Baidu AI APIs: A rich suite of AI services — OCR, TTS, ASR, LLM, image generation — that GoldBean wraps and exposes with unified billing.

The result: an AI agent can discover GoldBean's tools via MCP, call a free endpoint immediately, or pay $0.01–$0.05 per call via crypto for premium endpoints — all without a single API key or registration form.

Architecture Overview

┌─────────────────────────────────────────────────────┐
│                   AI Agent (Claude)                  │
│              MCP Client (SSE transport)               │
└──────────────────────┬──────────────────────────────┘
                       │
                       │ SSE connection to /sse
                       ▼
┌─────────────────────────────────────────────────────┐
│              GoldBean MCP Server (Node.js)            │
│                                                      │
│  ┌─────────┐  ┌──────────────┐  ┌────────────────┐  │
│  │ MCP     │  │ x402 Payment  │  │ Baidu AI       │  │
│  │ Protocol │  │ Middleware    │  │ Integration    │  │
│  │ (SSE)   │  │ (HTTP 402)    │  │ (OCR/TTS/LLM)  │  │
│  └─────────┘  └──────────────┘  └────────────────┘  │
│                                                      │
│  ┌──────────────────────────────────────────────┐   │
│  │         Unified Payment Layer                │   │
│  │  x402 (USDC/Base) | PayPal | Alipay          │   │
│  └──────────────────────────────────────────────┘   │
└──────────────────────┬──────────────────────────────┘
                       │
                       │ nginx reverse proxy
                       ▼
              goldbean-api.xyz (VPS)
Enter fullscreen mode Exit fullscreen mode

Key components:

  • goldbean-mcp-server.js — MCP protocol handler that exposes 47 tools via SSE transport
  • goldbean-x402-middleware.js — x402 payment middleware: EIP-3009 signature verification + on-chain transfer verification + 18 pricing endpoints
  • goldbean-unified-payment.js — Unified payment entry point routing between x402, PayPal, and Alipay
  • goldbean-pricing.js — Centralized pricing configuration (PRICE_MAP)
  • server.js — Main Express server (v8.0.0, ~970 lines) wiring everything together

Deployed on a VPS running AlmaLinux with Node.js and nginx as a reverse proxy. The server handles MCP discovery, payment verification, and API proxying in a single process.

How x402 Works — Technical Deep Dive

The x402 protocol turns HTTP 402 — a status code that has existed since 1991 but was never actually used — into a machine-readable payment negotiation. Here's the flow:

1. Agent calls a paid endpoint

POST /paid/baidu-ocr
Content-Type: application/json
x-user-id: anon_7f3a2b

{ "image_url": "https://example.com/receipt.jpg" }
Enter fullscreen mode Exit fullscreen mode

2. Server returns HTTP 402 with payment requirements

If the user has no credits, the server responds with:

HTTP/1.1 402 Payment Required
Content-Type: application/json

{
  "error": "Payment Required",
  "x402": {
    "endpoint": "/paid/baidu-ocr",
    "price": "0.01",
    "currency": "USDC",
    "chain": "base",
    "contract": "0x833589fCD6e6D11208e4D76B3A0b2E9C0bE017E6",
    "receiver": "0x7484...7D98",
    "scheme": "exact"
  },
  "message": "Pay 0.01 USDC on Base to unlock this call"
}
Enter fullscreen mode Exit fullscreen mode

3. Agent pays USDC on Base

The agent (or its wallet facilitator) constructs a transfer:

// Using @goldbean/x402-sdk
import { GoldBeanClient } from '@goldbean/x402-sdk';

const client = new GoldBeanClient({
  privateKey: process.env.WALLET_PRIVATE_KEY,
  rpcUrl: 'https://mainnet.base.org'
});

// The SDK handles: amount calculation → ERC-20 transfer → tx hash generation
const txHash = await client.pay({
  endpoint: '/paid/baidu-ocr',
  amount: '0.01',
  receiver: '0x7484...7D98'
});
Enter fullscreen mode Exit fullscreen mode

4. Server verifies the on-chain transaction

The x402 middleware (goldbean-x402-middleware.js) performs three checks:

async function verifyOnChainTx(txHash, expectedAmount, receiver) {
  // 1. Fetch the transaction receipt from Base RPC
  const receipt = await web3.eth.getTransactionReceipt(txHash);

  // 2. Verify it's a USDC transfer to our wallet
  const transferLog = receipt.logs.find(log => 
    log.topics[0] === TRANSFER_EVENT_SIG &&
    '0x' + log.topics[2].slice(26) === receiver.toLowerCase()
  );

  // 3. Verify the amount matches the endpoint price
  const transferred = web3.utils.toBN(transferLog.data);
  const expected = web3.utils.toBN(
    web3.utils.toWei(expectedAmount, 'mwei') // USDC has 6 decimals
  );

  return transferred.gte(expected);
}
Enter fullscreen mode Exit fullscreen mode

5. Server returns the API response

Once verified, the server grants a temporary credit and proxies the request to Baidu's API:

{
  "words_result": [
    { "words": "Total: $42.50" },
    { "words": "Date: 2025-07-09" }
  ],
  "words_result_num": 2,
  "log_id": 1752453617
}
Enter fullscreen mode Exit fullscreen mode

The entire flow — from 402 response to payment to API result — takes ~3–5 seconds on Base L2.

Getting Started

Option 1: MCP Server for Claude Desktop

Add GoldBean to your Claude Desktop config:

{
  "mcpServers": {
    "goldbean": {
      "url": "https://goldbean-api.xyz/sse"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Claude will automatically discover all 47 tools. Free endpoints work immediately. Paid endpoints will return 402 until you add credits.

Option 2: Direct API Call

# Register and get 20 free credits
curl -X POST https://goldbean-api.xyz/paid/user/register

# Call a free endpoint (no payment needed)
curl https://goldbean-api.xyz/free/btc-price

# Call a paid endpoint using your user ID
curl https://goldbean-api.xyz/paid/baidu-ocr \
  -H "x-user-id: YOUR_USER_ID" \
  -H "Content-Type: application/json" \
  -d '{"image_url": "https://example.com/image.jpg"}'
Enter fullscreen mode Exit fullscreen mode

Option 3: Python Integration with x402

import requests
from web3 import Web3

# Step 1: Call the endpoint
resp = requests.post(
    "https://goldbean-api.xyz/paid/baidu-ocr",
    json={"image_url": "https://example.com/receipt.jpg"}
)

# Step 2: If 402, handle payment
if resp.status_code == 402:
    payment_info = resp.json()["x402"]

    # Pay USDC on Base via web3.py
    w3 = Web3(Web3.HTTPProvider("https://mainnet.base.org"))
    usdc = w3.eth.contract(
        address="0x833589fCD6e6D11208e4D76B3A0b2E9C0bE017E6",
        abi=ERC20_ABI
    )

    # Transfer 0.01 USDC (6 decimals)
    tx = usdc.functions.transfer(
        payment_info["receiver"],
        10000  # 0.01 USDC in base units
    ).build_transaction({
        "from": w3.eth.account.address,
        "nonce": w3.eth.get_transaction_count(w3.eth.account.address),
        "gas": 80000,
        "gasPrice": w3.eth.gas_price
    })

    signed = w3.eth.account.sign_transaction(tx, PRIVATE_KEY)
    tx_hash = w3.eth.send_raw_transaction(signed.rawTransaction)

    # Step 3: Retry with payment proof
    resp = requests.post(
        "https://goldbean-api.xyz/paid/baidu-ocr",
        json={"image_url": "https://example.com/receipt.jpg"},
        headers={"x-tx-hash": tx_hash.hex()}
    )

print(resp.json())
Enter fullscreen mode Exit fullscreen mode

Option 4: x402 SDK (Node.js)

npm install @goldbean/x402-sdk
Enter fullscreen mode Exit fullscreen mode
import { GoldBeanClient } from '@goldbean/x402-sdk';

const client = new GoldBeanClient({
  privateKey: process.env.PRIVATE_KEY,
  // Automatically handles 402 → pay → retry
});

const result = await client.call(
  'https://goldbean-api.xyz/paid/baidu-ocr',
  { image_url: 'https://example.com/image.jpg' }
);
Enter fullscreen mode Exit fullscreen mode

Available Endpoints

GoldBean exposes 47 endpoints — 26 paid and 21 free:

Paid Endpoints (26)

Category Endpoint Price Description
OCR /paid/baidu-ocr $0.01 General text recognition
OCR /paid/ocr-medical $0.01 Medical document OCR
OCR /paid/ocr-education $0.01 Exam/handwriting OCR
OCR /paid/ocr-table $0.01 Table structure recognition
TTS /paid/tts $0.02 Text-to-speech (10+ voices)
ASR /paid/asr $0.02 Speech-to-text
ASR /paid/asr-diarization $0.03 Speaker diarization
LLM /paid/llm-chat $0.03 ERNIE 4.0 / Qwen / DeepSeek
LLM /paid/llm-embeddings $0.02 Text embeddings
Image Gen /paid/image-gen $0.03 Stable Diffusion XL
Image Gen /paid/image-enhance $0.02 Image quality enhancement
NLP /paid/sentiment $0.01 Sentiment analysis
NLP /paid/keyword-extract $0.01 Keyword extraction
NLP /paid/summary $0.02 Text summarization
NLP /paid/translation $0.01 Multi-language translation
Vision /paid/image-classify $0.02 Image classification
Vision /paid/object-detect $0.02 Object detection
Vision /paid/face-detect $0.02 Face detection
Document /paid/doc-parser $0.03 Document structure parsing
Document /paid/id-card-ocr $0.01 ID card recognition
Document /paid/bank-card-ocr $0.01 Bank card recognition
Document /paid/business-license $0.01 Business license OCR
Data /paid/ssi-verify $0.05 SSI verification
Data /paid/data-extract $0.02 Unstructured data extraction
API /paid/qrcode-gen $0.01 QR code generation
API /paid/qrcode-parse $0.01 QR code parsing

Free Endpoints (21)

Category Endpoint Description
Crypto /free/btc-price Bitcoin price
Crypto /free/eth-price Ethereum price
Crypto /free/gas-price Current gas price
Utility /free/ip-lookup IP geolocation
Utility /free/exchange-rate Currency exchange rates
Utility /free/timestamp Unix timestamp converter
Utility /free/uuid-gen UUID generator
Utility /free/hash-gen Hash generator (MD5/SHA256)
Utility /free/base64-encode Base64 encoder
Utility /free/base64-decode Base64 decoder
Utility /free/url-encode URL encoder
Utility /free/url-decode URL decoder
Utility /free/json-format JSON formatter
Utility /free/regex-test Regex tester
Utility /free/color-convert Color format converter
Utility /free/lorem-ipsum Lorem ipsum generator
Utility /free/user-agent User agent parser
Utility /free/cron-parser Cron expression parser
Utility /free/jwt-decode JWT decoder
Utility /free/markdown-to-html Markdown to HTML
Utility /free/slugs-gen Slug generator

What I Learned

x402 Protocol Implementation

The x402 spec is conceptually elegant — reuse HTTP 402 for machine-to-machine payments. But the implementation details are non-trivial:

  • USDC has 6 decimals, not 18. A $0.01 payment is 10000 base units, not 10000000000000000. Getting this wrong means payments fail silently or overcharge by 10^12.
  • EIP-3009 signature verification (used for gasless meta-transactions) required implementing transferWithAuthorization signature validation. I extracted this logic into the @goldbean/x402-sdk so others can reuse it.
  • On-chain verification latency: querying a Base RPC for transaction receipts adds ~1–2 seconds. I cache verified transactions to avoid re-verifying on retries.

The Zero Conversion Rate Problem

This was the hardest lesson. In the first 30 days, I saw real traffic — IP 47.82.11.57 (Safari/macOS) hit the paid /paid/ssi-verify endpoint. The server returned 402. The user left.

When a human sees "Payment Required," they bounce. When an agent sees 402, it needs a wallet with USDC and the logic to complete payment — and most agents don't have that yet.

The lesson: free tier as acquisition strategy is not optional — it's survival. The 21 free endpoints exist specifically to let users experience the product before committing to payment. The 20 free credits given at registration serve the same purpose for paid endpoints.

Multi-Payment Support as a Bridge

Not every developer has a crypto wallet. So GoldBean supports three payment methods:

  • x402 (USDC on Base) — for crypto-native agents and developers
  • PayPal — for international users with credit/debit cards
  • Alipay — for China users

The unified payment layer (goldbean-unified-payment.js) routes between these three. This means a developer in San Francisco can pay with PayPal while their agent pays with USDC — same endpoint, different payment rails.

Deployment on a Budget VPS

GoldBean runs on a 1GB RAM VPS ($5/month). The main constraint is memory — Node.js + nginx + monitoring scripts compete for limited RAM. I had to:

  • Tune nginx worker connections to 512
  • Use --max-old-space-size=384 for Node.js
  • Run monitoring scripts on cron rather than as persistent daemons

The architecture (single Node.js process handling MCP + payments + API proxy) works because the workload is I/O-bound (waiting on Baidu APIs and blockchain RPCs), not CPU-bound.

Try It

GoldBean is live and free to try. Here's what you can do right now:

  1. Browse free endpoints — No signup needed:
   curl https://goldbean-api.xyz/free/btc-price
Enter fullscreen mode Exit fullscreen mode
  1. Register for 20 free credits — Use them on any paid endpoint:
   curl -X POST https://goldbean-api.xyz/paid/user/register
Enter fullscreen mode Exit fullscreen mode
  1. Connect to Claude Desktop — Add the MCP server and let Claude discover all 47 tools:
   {
     "mcpServers": {
       "goldbean": {
         "url": "https://goldbean-api.xyz/sse"
       }
     }
   }
Enter fullscreen mode Exit fullscreen mode
  1. Install the x402 SDK — For programmatic payments in your own agent:
   npm install @goldbean/x402-sdk
Enter fullscreen mode Exit fullscreen mode

Links


GoldBean is an independent project. It is not affiliated with or endorsed by Baidu. Built with Node.js, x402 protocol, Express, and the MCP SDK.

Top comments (0)