Charge for MCP Tools on Cloudflare Workers with x402
This guide shows you how to monetize Model Context Protocol (MCP) tools deployed on Cloudflare Workers by integrating x402, a protocol for HTTP 402 payments. You’ll learn to set up a payment flow where users pay per request, using a simple step-by-step approach. By the end, you’ll have a working MCP endpoint that requires payment before returning tool results.
What You’ll Need
- A Cloudflare account with Workers enabled (free tier works).
- Node.js and npm installed locally for building and deploying.
- An x402-compatible payment provider (e.g., a Lightning wallet or an API key from a service like OpenNode or Strike).
- Basic familiarity with JavaScript/TypeScript and the MCP protocol.
Step-by-Step
- Set up your MCP tool on Cloudflare Workers
Create a new Worker project using `wrangler init`. Write your MCP tool logic as a standard Worker that handles POST requests. Ensure your tool responds with JSON-RPC formatted responses as per MCP spec. - Install x402 SDK
In your project directory, run `npm install @x402/sdk` (or the appropriate package for your provider). This SDK simplifies creating payment requests and verifying payments. - Configure your payment provider credentials
Add your provider’s API keys or wallet connection string to the Worker’s environment variables via `wrangler secret put`. For example, if using OpenNode, set `OPENNODE_API_KEY`. - Create a payment middleware
Write a function that intercepts incoming requests. Before processing the MCP call, check if the request includes a valid payment proof. If not, respond with HTTP 402 and a `Payment Required` header containing a payment request (e.g., a Lightning invoice). - Generate payment requests
Use the x402 SDK to create a payment request based on your tool’s pricing. For instance, `createInvoice({ amount: 100, memo: ‘MCP tool call’ })`. Return this invoice in the 402 response. - Verify payments
When a request includes a payment proof (e.g., a preimage), verify it using the SDK’s `verifyPayment` function. If valid, proceed to execute your MCP tool and return the result. - Deploy your Worker
Run `wrangler deploy` to push your code. Note your Worker’s URL, which will be your MCP endpoint. - Test with an MCP client
Use an MCP client (like Claude Desktop or a custom script) to call your tool. The client should handle the 402 response by presenting the payment request to the user, then retry with the payment proof.
Common Mistakes
- Not handling 402 responses properly: Your MCP client must be configured to recognize 402 and prompt for payment. If not, the user will see an error.
- Incorrect invoice amount: Ensure your pricing is set in the correct currency unit (e.g., satoshis, not Bitcoin).
- Missing environment variables: Forgetting to set API keys leads to runtime errors. Double-check with `wrangler secret list`.
- Not verifying payment before executing the tool: Always verify the proof before running expensive operations.
Tips
- Use a caching layer for verified payments to avoid repeated verification calls.
- Set a reasonable timeout for payment verification to prevent hanging requests.
- Log all 402 responses to debug client issues.
- Consider offering a free tier with rate limiting to attract users.
- Test with a small amount first to ensure the flow works end-to-end.
Troubleshooting
Issue: MCP client doesn’t prompt for payment.
Check if your client supports HTTP 402. If not, you may need to implement a custom client or use a proxy that handles the payment flow.
Issue: Payment verification fails.
Verify that the proof format matches what your provider expects. Check the SDK documentation for the correct verification method.
Issue: Worker returns 500 error.
Look at the Worker logs in the Cloudflare dashboard. Common causes: missing environment variables, incorrect SDK usage, or network issues with the payment provider.
Issue: Invoice expires too quickly.
Set a longer expiry time in your invoice creation parameters, but balance it with security.
Frequently Asked Questions
What is x402?
x402 is a protocol that standardizes HTTP 402 Payment Required responses, allowing servers to request payment before serving content. It’s often used with cryptocurrencies like Bitcoin Lightning.
Do I need a blockchain node?
No, you use a payment provider’s API to create and verify invoices. The provider handles the blockchain interactions.
Can I use this with any MCP client?
Most MCP clients don’t natively handle 402 yet. You may need to write a small wrapper or use a client that supports it.
How do I set pricing for my tools?
You define the amount in your code, either as a fixed price or based on usage (e.g., per token). You can also adjust it dynamically.
Is there a risk of double-spending?
Payment proofs are single-use and verified against the provider. Once used, they cannot be replayed.
What if the user pays but doesn’t get the result?
Implement idempotency keys or allow refunds via your payment provider. Also, log transaction IDs for support.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.