{"slug": "i-built-an-mcp-server-that-charges-ai-agents-per-call-using-x402-micropayments", "title": "I built an MCP server that charges AI agents per call using x402 micropayments", "summary": "A developer built an MCP server that charges AI agents per call using x402 micropayments, a protocol based on EIP-3009 that enables machine-to-machine payments without human sign-up. The server uses a Cloudflare Worker as a paywall proxy, allowing agents to pay automatically with USDC for each tool invocation, with pricing tiers reflecting compute costs.", "body_md": "*By Toolstem*\n\nYou built an MCP server. Agents call it. You pay the API costs. They pay nothing. Every `tools/call`\n\ninvocation burns a few cents of your budget while the agent that triggered it has no idea — and no incentive to care. The standard answer is \"wrap it in a SaaS subscription,\" but that requires a human in the loop to sign up, enter a card, and manage a billing relationship. Most agents don't have humans watching every call. What if the agent just paid for its own data, automatically, without a human anywhere in the loop?\n\nThat's what I built. Here's what I learned.\n\nHTTP 402 — \"Payment Required\" — has existed since 1996. It was reserved for future use and then essentially forgotten for 28 years. The [x402 protocol](https://x402.org) revives it as a machine-to-machine payment standard built on EIP-3009.\n\nThe flow looks like this:\n\n`transferWithAuthorization`\n\n— a pre-authorized USDC transfer that the server can submit on behalf of the agent`X-Payment`\n\nheader containing the signed authorizationNo Stripe account. No OAuth flow. No human sign-up. No waiting for a monthly invoice. The agent pays exactly what it used, settled atomically, without ever needing ETH for gas (the server submits the transfer, so only the server needs a small ETH float for gas — the agent only needs USDC).\n\nThis is the \"HTTP + payment\" primitive that should have existed all along. It's pre-product-market-fit, but the underlying mechanic is sound.\n\nThe core infrastructure is a **Cloudflare Worker acting as a paywall proxy**. It sits between the public internet and your upstream MCP server, intercepting every request before forwarding it.\n\n```\nAgent → Cloudflare Worker (x402 paywall) → Upstream MCP Server → Data sources\n```\n\nThe Worker handles the payment lifecycle:\n\n`X-Payment`\n\nheaderOne non-obvious constraint: ** initialize and tools/list must be free.** Agents need to discover your tool surface before they can decide whether to pay. If you charge for discovery, you never get called at all. Any directory health-check probe (Glama, mcp.so, PulseMCP) also expects a free\n\n`tools/list`\n\nresponse — paywall those and you fall off the listings. The Cloudflare Worker routes those two MCP message types to an unmetered path.**Per-tool pricing** is where the model gets interesting. Our SEC EDGAR server runs three tiers:\n\n| Tool | Tier | Per call |\n|---|---|---|\n`getCompanyFilingsSummary` |\nCheap | $0.005 |\n`getInsiderSignal` |\nStandard | $0.05 |\n`getInstitutionalSignal` |\nStandard | $0.05 |\n`getMaterialEventsDigest` |\nPremium | $0.50 |\n`compareDisclosureSignals` |\nPremium | $0.50 |\n\nA filings summary is one EDGAR lookup. `compareDisclosureSignals`\n\ncross-references insider trades, 13F institutional moves, and 8-K clusters across multiple companies. The compute difference is roughly 100x — so the price difference is 100x. Flat pricing treats them identically, which means you're subsidizing every expensive call with revenue from cheap ones.\n\nThe Finance MCP server (our first server) launched at a flat $0.005 across all tools. Six weeks in, we had $0 revenue. That table above is the lesson.\n\nThe LangChain integration wraps the payment layer into a custom fetch function. Everything else is standard agent code.\n\n**TypeScript / LangChain.js:**\n\n``` js\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { createFinanceTools } from \"langchain-toolstem/finance\";\nimport { createX402Fetch } from \"langchain-toolstem/x402\";\n\n// fetch that auto-signs USDC payments on HTTP 402\nconst fetchPay = await createX402Fetch({\n  privateKey: process.env.X402_PRIVATE_KEY!,\n  maxPaymentUsd: 0.05, // per-call safety cap\n});\n\n// discovers tools live via MCP tools/list (free)\nconst tools = await createFinanceTools({ fetch: fetchPay });\n\nconst agent = createReactAgent({ llm, tools });\n// each tools/call costs $0.01 USDC, settled on Base mainnet\n```\n\nThe `createX402Fetch`\n\nwrapper intercepts any 402 response, signs the EIP-3009 authorization using the agent's private key, and retries transparently. The `maxPaymentUsd`\n\ncap is a safety rail — the agent refuses to sign any authorization above that threshold, protecting against a misconfigured or malicious server quoting an unexpected price.\n\nTools are discovered live via `tools/list`\n\non startup (free, not metered), so the agent always sees the current tool surface without anything hardcoded into the package.\n\n**Python / LangChain:**\n\n``` python\nfrom langchain_toolstem import create_finance_tools, create_x402_httpx_client\n\nclient = create_x402_httpx_client(\"0xYOUR_PRIVATE_KEY\")\ntools = await create_finance_tools(client=client)\n# same pattern — agent signs payments, settles on Base\n```\n\nFor environments where you need a plain `http://`\n\nURL rather than a custom fetch (e.g., `MultiServerMCPClient`\n\n), `createX402Proxy`\n\nspawns a local reverse proxy at `localhost:4021`\n\nthat handles payment signing, so you can point any standard MCP client at it directly.\n\nThe package is [ langchain-toolstem](https://www.npmjs.com/package/langchain-toolstem) on npm (~1,400 installs/month) and\n\n`langchain-toolstem`\n\n**Flat pricing was wrong.** The Finance server ran flat $0.005 per call for six weeks. Zero meaningful revenue. The math is brutal: even if you hit the plateau of ~1,400 monthly active users typical for popular Apify actors, $0.005 flat yields ~$7/month. The ceiling is too low for a server with real API costs underneath it. Tiered pricing maps price to actual compute — it was the right call, and we should have done it from day one.\n\n**The free discovery layer is non-negotiable.** Agents must be able to call `tools/list`\n\nwithout triggering a payment. This isn't just good UX — it's a technical requirement for every MCP directory that health-checks your listing. We had one bug early on where an unbilled discovery path was missing, and the server briefly vanished from Glama's listings because the probe got a 402 instead of a tools manifest.\n\n**The heartbeat problem is real.** Coinbase's x402 Bazaar delists your endpoint if it goes 30 days without a confirmed paid call. For a server that's still building an audience, that's a serious risk — you could drop off the directory just as someone is about to discover you. We solved this with a GitHub Actions cron that runs every 6 hours, makes a real paid call from a funded heartbeat wallet, and posts the result to a log. Cost: roughly $0.06/day in USDC. Insurance against delisting: worth it.\n\nThe heartbeat revealed another bug: our initial implementation was calling `tools/call`\n\nwithout first completing the MCP `initialize`\n\nhandshake. The server was rejecting the call silently. Fixing it required tracing the raw MCP message sequence. A reminder that the protocol has state — it's not a stateless REST API.\n\n**One external paying customer. $0.01.** I want to be direct about this. The payment rail works end-to-end — 49 self-test transactions confirmed on Base mainnet, and one external payment from wallet `0x9CC4`\n\non 2026-06-03 for $0.01. That's the full external revenue picture. The mechanism is proven; adoption is the open question.\n\nWe're self-audited on the security side (no third-party audit yet), and we've run independent AI reviewer passes on the codebase. The x402 verification logic, nonce handling, and private key isolation are the parts that matter most and got the most scrutiny.\n\nx402 is a protocol looking for a distribution moment. The primitive is correct: HTTP-native, cryptographic, machine-to-machine, no humans required. What it lacks is the agent wallet layer becoming standard.\n\nThat moment is approaching. Coinbase AgentKit and CDP wallets are building the infrastructure for agents to hold and spend funds natively. When agent wallets are as common as agent LLM clients, x402 becomes the obvious way to monetize any agent-facing API — a single fetch wrapper is all the integration a developer needs.\n\nUntil then, the pattern is in early-adopter territory. The agents that can use it today are ones whose operators have explicitly provisioned a funded wallet and a private key in their environment. That's not zero — it's the population of developers actively building agentic systems who care about cost attribution.\n\nThe server is live at **mcp.toolstem.com**. Try it with a funded Base wallet. `initialize`\n\nand `tools/list`\n\nare always free — you can inspect the full tool surface before committing a cent.\n\n*The Finance and SEC EDGAR MCP servers are listed in Coinbase's x402 Bazaar. Source: github.com/toolstem/toolstem-mcp-server and github.com/toolstem/toolstem-sec-mcp-server. Walletless demo at toolstem.com/playground.*", "url": "https://wpnews.pro/news/i-built-an-mcp-server-that-charges-ai-agents-per-call-using-x402-micropayments", "canonical_source": "https://dev.to/toolstem/i-built-an-mcp-server-that-charges-ai-agents-per-call-using-x402-micropayments-1lpn", "published_at": "2026-06-16 03:43:35+00:00", "updated_at": "2026-06-16 04:17:20.724790+00:00", "lang": "en", "topics": ["artificial-intelligence", "ai-agents", "developer-tools", "ai-infrastructure"], "entities": ["Toolstem", "Cloudflare", "LangChain", "EIP-3009", "USDC", "Base", "SEC EDGAR", "Glama"], "alternates": {"html": "https://wpnews.pro/news/i-built-an-mcp-server-that-charges-ai-agents-per-call-using-x402-micropayments", "markdown": "https://wpnews.pro/news/i-built-an-mcp-server-that-charges-ai-agents-per-call-using-x402-micropayments.md", "text": "https://wpnews.pro/news/i-built-an-mcp-server-that-charges-ai-agents-per-call-using-x402-micropayments.txt", "jsonld": "https://wpnews.pro/news/i-built-an-mcp-server-that-charges-ai-agents-per-call-using-x402-micropayments.jsonld"}}