x402-wallet-mcp
Integrates with Coinbase Onramp to let an agent fund its wallet: the fund_wallet tool generates an Onramp link so USDC can be bought with a debit card or Apple Pay, and payments settle as USDC on Base using the x402 protocol.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@x402-wallet-mcp Get me the top Hacker News stories from the x402 API"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Give Claude Code, Cursor, or any MCP client its own wallet. It discovers x402 endpoints, signs USDC payments on Base, and handles the full HTTP 402 negotiation — so your AI agent can call paid APIs without human intervention.
You: "Get me the top Hacker News stories from the x402 API"
Claude: Using call_endpoint to pay $0.002 USDC...
✓ Payment signed (EIP-3009 TransferWithAuthorization)
✓ Got 10 stories from https://x402.onchainexpat.com/api/x402-tools/hackernews/topWhy This Exists
AI agents need to spend money. Today that means hardcoded API keys, credit cards on file, or manual approval for every request. The x402 protocol fixes this: servers return HTTP 402 with a price, clients sign a USDC payment, and the request goes through. No API keys. No subscriptions. Pay per call.
This project is the missing piece: an open-source MCP server that gives any AI agent a USDC wallet, spending controls, and the ability to pay for x402 APIs autonomously.
Related MCP server: @hpp-io/x402-mcp-bridge
Features
Zero-config wallets — works out of the box with no API keys or signup required
Privy HSM-backed keys — keys never leave Privy's HSM/TEE infrastructure
Three wallet modes — Proxy (zero-config default), Linked (email-recoverable), or Privy direct (BYOK)
Email recovery — link your wallet to an email, recover it on any device via OTP
Full x402 negotiation — handles 402 → sign → retry automatically
EVM exact + commerce (escrow): EIP-3009 TransferWithAuthorization and ReceiveWithAuthorization
Endpoint discovery — fetches
.well-known/x402documents and searches x402scan.comSpending controls — per-call maximum and daily cap with automatic enforcement
Transaction history — append-only log of every payment
Coinbase Onramp — buy USDC with a debit card or Apple Pay, no crypto experience needed
13 MCP tools — everything an agent needs to discover, query, pay, and audit
Quick Start
No API keys or signup required. Just install and go:
Claude Code
claude mcp add x402-wallet -- npx x402-wallet-mcpCursor / Windsurf / Claude Desktop
Add to your MCP config file (.mcp.json, ~/.cursor/mcp.json, or Claude Desktop settings):
{
"mcpServers": {
"x402-wallet": {
"command": "npx",
"args": ["x402-wallet-mcp"]
}
}
}On first run an HSM-backed wallet is automatically provisioned via the x402 provisioning service. Fund your wallet using the fund_wallet tool (generates a Coinbase Onramp link) or send USDC on Base directly to the wallet address.
Link Your Wallet to Email (Recommended)
After setup, use wallet_link to connect your wallet to an email address. This enables recovery on any device:
You: "Link my wallet to my@email.com"
Claude: Verification code sent! Enter the 6-digit code from your email.
You: "123456"
Claude: ✓ Wallet linked to my@email.com. You can recover this wallet on any device.Recover on Another Device
You: "Recover my wallet using my@email.com"
Claude: ✓ Wallet recovered — same address, same balance.If you have multiple wallets linked to the same email, you'll be shown each wallet's address and USDC balance so you can choose which one to load.
Your Keys Are Always Yours
No private key is ever stored on your machine. All keys live in Privy's HSM/TEE secure enclaves — hardware security modules that never expose raw key material.
Once you link your email with wallet_link, you can:
Export your private key at home.privy.io — log in with your email, verify via OTP, and click "Export keys"
Recover your wallet on any device using
wallet_recoverwith the same emailAccess your funds even if this package, the x402 provisioning service, or our website disappears entirely
This works for all wallet modes (proxy, linked, and BYOK). You do not need your own Privy credentials — the default setup is fully recoverable and exportable after linking your email.
Power Users: Bring Your Own Privy Credentials
For full control, sign up for a Privy account and pass your own credentials. This bypasses the proxy and talks directly to Privy:
claude mcp add x402-wallet \
-e PRIVY_APP_ID=your-app-id \
-e PRIVY_APP_SECRET=your-app-secret \
-- npx x402-wallet-mcpHow It Works
┌──────────────┐ 1. POST /api/data ┌──────────────┐
│ │ ──────────────────────────────→ │ │
│ AI Agent │ 2. 402 + price: $0.002 │ x402 Server │
│ (via MCP) │ ←────────────────────────────── │ │
│ │ 3. POST + X-PAYMENT header │ │
│ │ ──────────────────────────────→ │ │
│ │ 4. 200 + data │ │
│ │ ←────────────────────────────── │ │
└──────────────┘ └──────────────┘
│ │
│ sign EIP-3009 │ verify signature
│ TransferWithAuthorization │ settle USDC on Base
▼ ▼
┌──────────────┐ ┌──────────────┐
│ x402-wallet │ │ USDC on │
│ (Privy HSM) │ │ Base │
└──────────────┘ └──────────────┘The agent calls
call_endpointwith a URLThe server returns HTTP 402 with payment requirements (
acceptsarray)x402-wallet-mcp picks the best payment option, checks spending limits, signs an EIP-3009 authorization
Retries the request with the signed payment in the
X-PAYMENTheaderReturns the API response to the agent and logs the transaction
MCP Tools
The server exposes 13 tools that any MCP client can call:
Tool | Description | Key Parameters |
| Make a paid API call (handles full 402 flow) |
|
| Probe pricing without paying |
|
| Search for available x402 APIs |
|
| USDC balance on Base + deposit address | — |
| Wallet mode, addresses, recovery status | — |
| Buy USDC via Coinbase Onramp (debit card / Apple Pay) |
|
| Recent payment log |
|
| Set per-call max and daily cap |
|
| Register a |
|
| Add/remove merchant allowlist entries |
|
| Link wallet to email for recovery |
|
| Recover a linked wallet on any device |
|
| Instructions for exporting private key via Privy | — |
Example: Paid API Call
When an agent calls call_endpoint:
{
"url": "https://x402.onchainexpat.com/api/x402-tools/hackernews/top",
"method": "POST",
"body": "{\"num_stories\": 5}"
}The tool returns:
{
"success": true,
"status": 200,
"amountPaid": "$0.01",
"scheme": "exact",
"network": "eip155:8453",
"data": {
"stories": ["..."]
}
}Spending Controls
Built-in safeguards prevent runaway spending:
Control | Default | Override Env Var |
Per-call maximum | $5.00 USDC |
|
Daily cap | $50.00 USDC |
|
The daily cap resets at midnight UTC. Both limits can also be changed at runtime using the configure_spending tool.
If a payment would exceed either limit, the tool returns an error explaining why — the agent can then ask the user for approval or skip the call.
Payment Schemes
Exact (EIP-3009 TransferWithAuthorization)
The default and most common scheme. Signs a one-time USDC transfer authorization:
Domain: USDC contract on Base (
0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913)Type:
TransferWithAuthorization(from, to, value, validAfter, validBefore, nonce)Expiry: Configurable via
maxTimeoutSeconds(default 60s)Nonce: Random 32 bytes (one-time use)
Commerce / escrow (EIP-3009 ReceiveWithAuthorization)
For endpoints that use x402r's commerce scheme (called escrow before April 2026; both names are accepted, and the payment answers in the name the server offered). Funds are held in escrow and captured by the merchant's operator after the API response:
Type:
ReceiveWithAuthorization(from, to, value, validAfter, validBefore, nonce)to: Token collector contract (not the final recipient). Only x402r's published collectors on Base are accepted, each with its own escrow contract; any other collector is refused before signing, because the collector named in the signature could otherwise redeem it directly.
Nonce: Deterministic, computed from
keccak256(chainId, escrowAddress, paymentInfoHash)Expiry:
validAfter=0,validBefore = preApprovalExpiry = now + maxTimeoutSeconds(capped at one hour). The capture deadline and refund window stay open-ended.Network: Base only
Relabelled offers: some servers label commerce offers
exactbecause x402scan only listsexact. Anexactoffer whose terms name one of those x402r token collectors and an operator is paid as commerce, since paying it as exact would fail. Anexactoffer naming any other collector stays exact.
The tool auto-detects which scheme to use based on the server's accepts array. By default it prefers exact; pass prefer_escrow: true to prefer commerce when both are available.
Configuration
Environment Variables
Variable | Purpose | Required |
| Privy application ID (enables direct Privy mode) | No |
| Privy application secret | No |
| Custom proxy URL (default: | No |
| Max USDC per API call (e.g. | No |
| Max USDC per day (e.g. | No |
| Custom Base RPC endpoint | No |
| Skip email link prompt on first run | No |
No environment variables are required. The wallet works zero-config out of the box, including Coinbase Onramp for buying USDC.
Wallet mode priority: If PRIVY_APP_ID and PRIVY_APP_SECRET are set, the wallet connects directly to Privy. Otherwise, it uses the hosted proxy for zero-config operation.
Data Directory
All persistent data is stored in ~/.x402-wallet/:
~/.x402-wallet/
├── config.json # Settings, wallet ID, endpoint sources
├── history.jsonl # Transaction log (append-only)
├── spending.json # Daily spending tracker
└── endpoints-cache.json # Discovery cache (1hr TTL)Default Configuration
{
"version": 2,
"wallet": { "mode": "proxy" },
"spending": { "perCallMaxUsdc": "5.00", "dailyCapUsdc": "50.00" },
"endpointSources": [
"https://x402.onchainexpat.com",
"https://padelmaps.org",
"https://stableenrich.dev",
"https://stablestudio.dev",
"https://x402.twit.sh"
],
"preferences": { "preferEscrow": false, "preferredNetwork": "evm" }
}Note: The default mode is
"proxy"(zero-config). Usewallet_linkto upgrade to"linked"mode with email recovery and key export. WhenPRIVY_APP_IDandPRIVY_APP_SECRETenv vars are set, the wallet automatically switches to"privy"mode.
Architecture
x402-wallet-mcp/
├── bin/
│ └── x402-wallet-mcp.ts # CLI entry point
├── src/
│ ├── index.ts # Main: wallet + MCP server + stdio
│ ├── server.ts # McpServer with 13 tools
│ ├── wallet/
│ │ ├── types.ts # WalletProvider interface
│ │ ├── factory.ts # Wallet creation (proxy/linked/privy)
│ │ ├── proxy-wallet.ts # Zero-config wallet via hosted proxy
│ │ ├── proxy-api.ts # REST client for proxy service
│ │ ├── privy-wallet.ts # Direct Privy server wallets (HSM/TEE)
│ │ ├── privy-api.ts # REST client for Privy API
│ │ ├── link-api.ts # Email linking & recovery API client
│ │ └── null-wallet.ts # Placeholder for unconfigured state
│ ├── payment/
│ │ ├── evm-exact.ts # EIP-3009 TransferWithAuthorization
│ │ ├── evm-escrow.ts # ReceiveWithAuthorization + nonce
│ │ ├── negotiator.ts # 402 → sign → retry orchestrator
│ │ ├── types.ts # AcceptEntry, PaymentRequired, etc.
│ │ └── constants.ts # USDC addresses, chain IDs
│ ├── discovery/
│ │ ├── well-known.ts # Fetch .well-known/x402
│ │ ├── x402scan.ts # Query x402scan.com
│ │ └── registry.ts # Merge + deduplicate + cache
│ ├── spending/
│ │ ├── tracker.ts # Per-call + daily cap enforcement
│ │ ├── allowlist.ts # Merchant allowlist validation
│ │ └── store.ts # Persist daily spend totals
│ ├── tools/ # 13 MCP tool implementations
│ ├── store/
│ │ ├── config.ts # ~/.x402-wallet/config.json
│ │ ├── history.ts # Append-only JSONL transaction log
│ │ └── paths.ts # Cross-platform path resolution
│ └── utils/
│ ├── logger.ts # stderr-only (stdout = MCP JSON-RPC)
│ ├── http.ts # Fetch with timeout + retries
│ ├── format.ts # USDC atomic ↔ human-readable
│ ├── deposit-qr.ts # QR code generation for deposits
│ └── onramp.ts # Coinbase Onramp URL generation
└── tests/
├── unit/ # 127 tests across 16 files
├── integration/ # Live endpoint tests (costs real USDC)
└── e2e/ # Full MCP server over stdioDevelopment
Prerequisites
Node.js >= 18
npm
Setup
git clone https://github.com/onchainexpat/x402-wallet-mcp.git
cd x402-wallet-mcp
npm installBuild
npm run build # TypeScript → dist/
npm run lint # Type-check without emittingRun in Development
npm run dev # Run with tsx (auto-reloads)Testing
# Unit tests (127 tests, no network calls, no USDC spent)
npm test
# Watch mode
npm run test:watch
# Integration tests (hits real x402 endpoints, costs real USDC)
# Requires a funded wallet
RUN_LIVE_TESTS=1 npm run test:live
# E2E tests (spawns MCP server over stdio, calls all 13 tools)
RUN_E2E_TESTS=1 npx vitest run tests/e2eThe unit test suite covers:
Wallet: Proxy + Privy + Linked API mocking, factory routing, email linking/recovery
Payment: EIP-3009 exact/escrow signing, escrow nonce determinism, full negotiator flow (402 → sign → retry), edge cases (double-402, empty accepts, spending limits)
Spending: per-call max, daily cap, midnight reset, env var overrides, merchant allowlist
Discovery: endpoint merging, deduplication, cache behavior, fetch failure handling
Store: config defaults/persistence, history append/query, USDC formatting, Coinbase onramp URLs
Local Testing with an MCP Client
# Build and run
npm run build
node dist/bin/x402-wallet-mcp.js
# Or use npx to test the published package experience
npx .The server communicates over stdio (JSON-RPC), so you need an MCP client to interact with it. The easiest way is to add it to Claude Code's config and test through the chat.
Terminology
Term | Definition |
x402 | Protocol for HTTP 402 payments — servers price API calls, clients pay with crypto |
MCP | Model Context Protocol — standard for AI tool servers |
EIP-3009 | Ethereum standard for gasless USDC transfers via signed authorizations |
Base | Coinbase's L2 network where USDC payments settle |
Exact | Direct payment scheme — USDC transfers immediately to the server |
Escrow | Protected payment scheme — funds held in smart contract, settled after API response |
Security Considerations
This software manages real cryptocurrency. Review thesecurity policy before using in production.
No keys on your machine: Private keys are never stored locally — not in plaintext, not encrypted, not anywhere on disk. All keys live in Privy's HSM/TEE secure enclaves.
Survivable: If this package, the x402 provisioning service, or our website disappears, go to home.privy.io, log in with your linked email, and export your private key. Your funds are always accessible.
HSM-backed signing: Whether using proxy or direct Privy mode, keys never leave Privy's hardware security modules.
Proxy signing validation: The hosted proxy validates every signing request — only USDC transfers on Base, capped at 100 USDC per transaction.
Spending limits: Enforced locally before signing. Cannot be bypassed by the AI agent.
No stdout leaks: All logging goes to stderr. stdout is reserved for MCP JSON-RPC. Private keys never appear in logs.
Email recovery: OTP-verified, rate-limited, HMAC-derived codes with 10-minute expiry.
Roadmap
Multi-chain support (Ethereum mainnet, Arbitrum, Optimism)
Payment receipts and on-chain verification
Webhook notifications for payments
Rate limiting and circuit breaker patterns
Dashboard UI for spending analytics
Contributing
Contributions are welcome. See CONTRIBUTING.md for guidelines.
Before submitting a PR:
Run
npm testand ensure all 127 tests passRun
npm run lintfor type checkingAdd tests for new functionality
Keep PRs focused — one feature or fix per PR
Related Projects
x402 — The x402 protocol specification by Coinbase
MCP — Model Context Protocol by Anthropic
viem — TypeScript library for Ethereum (used for signing)
x402scan.com — Directory of x402-enabled endpoints
License
Available Tools
13 toolsadd_endpoint_sourceA
Add x402 endpoints. Pass a base_url to add a .well-known/x402 discovery source, or pass endpoint_url to add a single API endpoint directly.
Inputs: base_url, description, endpoint_url.
call_endpointA
Make a paid API call to an x402-protected endpoint. Handles 402 payment negotiation automatically. Payments under the auto-approve threshold (default $0.05) execute silently. Payments over the threshold return a preview — call again with confirmed: true after user approves. Use discover_endpoints first to find the right URL if you don't know it.
Inputs: url (required), body, method, headers, +2 more.
check_balanceA
Check USDC balance on Base and get deposit address. Shows a QR code when balance is zero. When the response contains a qr_base64 field, always render it in an HTML artifact using an tag so the user can see and scan the QR code directly in the chat.
Inputs: no named parameters.
configure_spendingA
View or update spending limits. Set per-call maximum, daily cap, and auto-approve threshold for x402 payments. The auto-approve threshold controls how much can be spent without explicit user confirmation (default: $0.05).
Inputs: daily_cap, per_call_max, auto_approve_threshold.
discover_endpointsA
Search for x402-protected API endpoints by keyword. Use this FIRST when the user asks for any data or service — you likely have a paid endpoint for it. Available categories: crypto intelligence (token approvals, wallet identity, contract decoder, price feeds, token holders, DeFi positions, gas oracle, site trust, NFT metadata, ENS expiry), uncensored AI (chat, reasoning, code, image generation), agent tools (weather, news, stocks, crypto prices, geocoding, GitHub, wiki), residential proxy, SMS verification, and endpoint review. Search by keyword to find the right endpoint URL, then use call_endpoint to call it.
Inputs: query, source.
export_keyA
Get instructions for exporting your wallet's private key. Embedded wallets can be exported at home.privy.io.
Inputs: no named parameters.
fund_walletA
Get a link to buy USDC with a debit card or Apple Pay via Coinbase Onramp. No crypto experience needed. Falls back to deposit address + QR code if unavailable. When the response contains a qr_base64 field, always render it in an HTML artifact using an tag so the user can see and scan the QR code directly in the chat.
Inputs: amount.
manage_allowlistB
View or update the merchant address allowlist. Add trusted merchant addresses, remove them, or toggle the allowlist on/off. When enabled, only allowlisted merchants can receive payments.
Inputs: mode, allow, remove.
query_endpointA
Probe an x402 endpoint to see its pricing and payment requirements without paying. Returns the accept entries showing supported payment methods and prices.
Inputs: url (required), method.
transaction_historyC
View recent payment transactions
Inputs: limit.
wallet_infoA
Get wallet mode, addresses, and status. Returns a QR code for depositing USDC on Base. When the response contains a qr_base64 field, always render it in an HTML artifact using an tag so the user can see and scan the QR code directly in the chat.
Inputs: no named parameters.
wallet_linkA
Link your wallet to an email address for easy recovery. If already linked, shows current status. Step 1: Call with email to send a verification code. Step 2: Call again with session_token, email, and code to complete linking.
Inputs: code, email, session_token.
wallet_recoverA
Recover a previously linked wallet by email. Step 1: Call with email to send a verification code. Step 2: Call again with the session_token, email, and code to complete recovery. If multiple wallets exist, Step 2 returns a list — call again with wallet_id to select one. Do NOT use wallet_link for recovery — it would link your email to the new wallet instead.
Inputs: code, email, wallet_id, session_token.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 13 tools
Most tools target clearly distinct operations: discover_endpoints (search) vs query_endpoint (probe pricing) vs call_endpoint (pay) form a coherent progression, and the descriptions explicitly warn against confusing wallet_link with wallet_recover. The main soft overlap is wallet_info vs check_balance, which both return addresses and QR codes, and add_endpoint_source vs discover_endpoints require reading descriptions to separate adding from searching.
The dominant pattern is verb_noun (check_balance, call_endpoint, configure_spending, manage_allowlist, fund_wallet), which is predictable and readable. Minor deviations exist: wallet_info and transaction_history are noun-only, and wallet_link/wallet_recover put the noun first, but the convention is still easy to infer.
13 tools sits comfortably in the well-scoped range and each tool maps to a real capability: discovery, payment, spending controls, funding, and wallet recovery/export. No tool looks like filler or a duplicate of another's core function.
The surface covers the full lifecycle well: discover/probe/call endpoints, configure spending, allowlist merchants, view history, fund, link, recover, and export keys. Gaps are minor — there is no way to remove or list added endpoint sources, no unlink/revoke for an email link, and no plain USDC transfer tool, but agents can work around these.
Maintenance
Related MCP Connectors
Machine-payable API infrastructure for autonomous agents. Per-call x402 settlement in USDC.
Let an AI agent find and pay for x402 APIs and products in USDC on Base, within owner-set limits.
Pay-per-call tools for autonomous agents, settled in USDC on Base via x402.
x402 pay-per-call APIs over MCP, settled in USDC on Base for autonomous agents and developers.
Related MCP Servers
AlicenseAqualityBmaintenanceEnables AI agents to call paid APIs and settle HTTP 402 payment challenges with USDC on Base, without private keys ever being involved.7444 npmMIT
@hpp-io/x402-mcp-bridgeofficial
AlicenseNot gradedqualityBmaintenanceEnables AI agents to autonomously pay for and discover services using HPP USDC.e over the x402 protocol, without API keys or manual signing.136 npmApache 2.0- AlicenseAqualityBmaintenanceEnables AI agents to discover and pay for x402-gated HTTP APIs, handling 402 Payment Required flows with local signing. Supports EVM and Solana with non-custodial wallet management.3324 npmMIT

m2mcent-sdkofficial
AlicenseAqualityCmaintenanceMonetizes any API or MCP server by wrapping endpoints with the x402 payment protocol, enabling USDC micro-payments from AI agents with atomic settlement on Base L2.2253 npmMIT