x402 lets you meter MCP tools exactly like HTTP APIs. This guide walks through wiring the Nuwa @nuwa-ai/x402 SDK into a Next.js App Router project, verifying the full payment handshake locally, and pointing you to production guardrails. The finished code matches the docs/example Next.js sample that ships in this repo.
Prerequisites
- Node.js 18+ (20 LTS recommended)
pnpm 9+
- An existing or new Next.js App Router project
- A funded Base wallet (use Base Sepolia while testing)
- Facilitator access (
/verify, /settle, /list, /supported)—Coinbase CDP works out of the box
Need a facilitator quickly? The nuwa-protocol/nuwa-x402 repo exposes CDP-compatible endpoints via Docker so you can self-host locally.
1. Install dependencies
From your Next.js project root:
@nuwa-ai/x402 bundles the MCP runtime (mcp-handler) and schema helpers. We add @coinbase/x402 for the default facilitator client, viem for EVM key utilities, and zod to type-check tool inputs.
Create .env.local (Next.js loads this automatically):
Never use a hot mainnet key in development. Fund the derived address with a small amount of USDC on the selected network.
3. Parse env vars once
Add src/lib/env.ts to validate configuration:
Caching prevents re-validating on every request while staying type-safe.
4. Create the paid MCP route
In src/app/mcp/route.ts, wire the handler into the App Router:
Key details:
createPaidMcpHandler takes an initializer callback. Inside it you declare tools with server.paidTool. The helper injects payment checks before your business logic runs.
_meta["x402/payment"] is inspected automatically. Unpaid calls receive a 402 response describing the accepts requirements. Paid calls are verified, then settled, and your response gains _meta["x402/payment-response"].
- Adding a plain
server.tool keeps free functionality alongside paid tools.
If you need browser access, add OPTIONS handling plus CORS headers—see docs/example/src/lib/cors.ts for a drop-in helper. You will need this if you wanna test it with xNUWA.
5. Run and test locally
You can try your mcp with xNUWA app, in the Agent Studio you will find the MCP Debug Tool.