DEV Community

Cover image for How to Monetize Baidu AI with x402 and MCP: A Complete Tutorial
GoldBean
GoldBean

Posted on

How to Monetize Baidu AI with x402 and MCP: A Complete Tutorial

The Opportunity

Baidu AI offers powerful capabilities — OCR, text-to-speech, LLM chat, image recognition — but monetizing them for a global audience is hard. Chinese AI APIs require a Chinese phone number for registration. International payment gateways don't work natively with AI agent workflows.

What if you could expose Baidu AI to the entire world, charge per call, and let AI agents pay automatically?

That's exactly what GoldBean does. In this tutorial, I'll show you the architecture and code patterns to monetize any AI API with x402 micropayments and MCP protocol.

Prerequisites

  • Node.js 20+
  • Basic understanding of HTTP APIs
  • A Baidu AI account (or any AI API you want to monetize)
  • Optional: a crypto wallet with USDC on Base

Architecture: x402 + MCP + Baidu AI

AI Agent (Claude/Cursor) → MCP Protocol (SSE) → GoldBean Server → Baidu AI API
                                    ↓
                            x402 Payment Layer
                            (USDC on Base L2)
Enter fullscreen mode Exit fullscreen mode

The three layers work together:

  1. MCP Layer: AI agents discover and call tools via Model Context Protocol
  2. x402 Layer: Each paid call triggers an HTTP 402 payment flow — agent pays USDC, server verifies on-chain
  3. AI Backend: Baidu AI processes the request and returns results

Step 1: Setting Up the MCP Server

The MCP server exposes your AI endpoints as tools that AI agents can discover:

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';

const server = new McpServer({
  name: 'goldbean',
  version: '0.4.1',
});

// Register a paid tool
server.tool(
  'baidu_ocr',
  'Extract text from images using Baidu OCR',
  { image_url: z.string().url() },
  async (params) => {
    // Check payment first
    const paid = await checkPayment(request);
    if (!paid) return paymentRequiredResponse('baidu_ocr', 0.01);

    // Call Baidu OCR
    const result = await baiduOCR(params.image_url);
    return { content: [{ type: 'text', text: JSON.stringify(result) }] };
  }
);
Enter fullscreen mode Exit fullscreen mode

Step 2: Implementing x402 Payment Flow

When an agent calls a paid endpoint without credits, return HTTP 402:

function paymentRequiredResponse(endpoint, priceUsd) {
  return {
    status: 402,
    body: {
      error: 'Payment Required',
      x402: {
        endpoint,
        price: priceUsd.toString(),
        currency: 'USDC',
        chain: 'base',
        contract: '0x833589fCD6e6D11208e4D76B3A0b2E9C0bE017E6',
        receiver: process.env.RECEIVER_WALLET,
        scheme: 'exact'
      }
    }
  };
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Verifying On-Chain Payments

After the agent pays, it retries with a transaction hash. Verify it on Base:

const { Web3 } = require('web3');
const w3 = new Web3('https://mainnet.base.org');

const USDC_CONTRACT = '0x833589fCD6e6D11208e4D76B3A0b2E9C0bE017E6';
const TRANSFER_EVENT = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';

async function verifyPayment(txHash, expectedAmount, receiver) {
  const receipt = await w3.eth.getTransactionReceipt(txHash);
  if (!receipt) return false;

  const transferLog = receipt.logs.find(log =>
    log.address.toLowerCase() === USDC_CONTRACT.toLowerCase() &&
    log.topics[0] === TRANSFER_EVENT &&
    '0x' + log.topics[2].slice(26) === receiver.toLowerCase()
  );

  if (!transferLog) return false;

  // USDC has 6 decimals
  const transferred = BigInt(transferLog.data);
  const expected = BigInt(expectedAmount * 1e6);
  return transferred >= expected;
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Using the x402 SDK

To make it easier for developers, I published an SDK:

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

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

// The SDK handles: 402 → pay → retry automatically
const result = await client.call(
  'https://goldbean-api.xyz/paid/baidu-ocr',
  { image_url: 'https://example.com/receipt.jpg' }
);
Enter fullscreen mode Exit fullscreen mode

Step 5: Connecting to Claude Desktop

Add GoldBean as an MCP server:

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

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

Pricing Strategy

Tier Price Best For
Free 20 credits Try before you buy
x402 $0.01-$0.03/call Crypto-native AI agents
PayPal $1+ International credit card users
Alipay CNY 7+ China users

The free tier is critical. When users see HTTP 402, they leave. The free tier builds trust before asking for payment.

Discovery Endpoints

GoldBean implements standard discovery endpoints so AI agents can auto-detect capabilities:

  • /.well-known/x402.json — x402 service discovery
  • /.well-known/mcp.json — MCP tool listing
  • /openapi.json — OpenAPI 3.1 specification
  • llms.txt — LLM-readable service description

These endpoints are essential for interoperability. Tools like Smithery, Glama, and MCP Registry use them to index your service.

Key Lessons

  1. Free tier is not optional — it's survival. Zero conversion on cold 402 responses.
  2. Multi-payment support matters — not everyone has USDC. PayPal and Alipay bridge the gap.
  3. Discovery endpoints drive traffic — being indexed on MCP Registry and awesome-mcp-servers brings organic users.
  4. MCP compatibility is a growth multiplier — Claude Desktop users discover your tools without any marketing.

Try It Now

# Free endpoint - no signup
curl https://goldbean-api.xyz/free/btc-price

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

# Connect to Claude Desktop
# Add "url": "https://goldbean-api.xyz/sse" to your MCP config
Enter fullscreen mode Exit fullscreen mode

Links


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

Top comments (0)