@mcpaid/sdk
v2.1.3
Published
MCPaid: Zero-friction MCP monetization and micropayment infrastructure with x402 and blockchain settlement
Maintainers
Readme
MCPaid: Zero-Friction MCP Monetization & Micropayment Infrastructure
MCPaid enables developers of Model Context Protocol (MCP) servers to seamlessly monetize tools with pay-per-use micropayments (e.g. $0.005 / call), gasless AI agent authorizations via HTTP 402 + EIP-712, and automated 60-second on-chain USDC payouts on Base L2.
⚡ Key Capabilities
Sub-5ms Global Edge Gateway (Cloudflare Workers + V8 Isolates):
- High-throughput reverse proxy deployed across 310+ cities worldwide.
- Decorates MCP tool catalogs with pricing schemas and challenges unauthorized calls with RFC-compliant HTTP 402.
- Serverless SQLite persistence via Cloudflare D1 with global read replication and KV challenge nonces with 120s anti-replay TTL.
Gasless Micropayment Vouchers (EIP-712 on Base L2):
- Autonomous AI agents sign typed micro-vouchers off-chain without spending ETH on gas or waiting for block confirmations.
- Native support for Circle USDC on Base Mainnet (
0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913) and Base Sepolia (0x036CbD53842c5426634e7929541eC2318f3dCF7e).
Automated 1-Minute Base L2 Payout Relayer (
* * * * *):- Developers receive 97.00% net revenue on every tool call (3.00% protocol fee).
- Earnings accumulate in real-time in the D1 edge financial ledger.
- When a developer requests a withdrawal, Cloudflare Workers' isolated cron relayer automatically executes the on-chain ERC-20 transfer on Base L2 every 60 seconds, stamping confirmed BaseScan receipts directly into the dashboard.
- Zero HTTP Attack Surface: All payout execution paths run strictly via internal edge cron triggers or authenticated local operator scripts (
mcpaid relayer --run).
Cryptographic Edge Receipts (
X-MCPaid-Receipt) & Downstream Enforcement:- Single-use, tamper-proof HMAC-SHA256 payment receipts injected by the edge gateway on proxied requests.
- Downstream origin backends, microservices, and databases verify payment proofs in 5 lines of code, preventing forked clients or scrapers from bypassing the edge gateway.
- Per-server secret derivation via HKDF-SHA256 (
mcpaid_sec_...) with zero-downtime 1-hour grace window key rotation. - Built-in anti-replay nonce claim store (
MemoryReceiptStore,D1ReceiptStore) and drop-in Express middleware (createReceiptMiddleware).
Zero-Config Live Development Tunnel (
mcpaid dev):- Monetize MCP servers running locally on hardware (
http://127.0.0.1:3000/mcp) without buying domains or renting cloud VPS servers. - Launches an encrypted TLS 1.3 tunnel with an integrated Security Shield that drops direct bypass traffic with
403 Forbidden.
- Monetize MCP servers running locally on hardware (
Server Management & Anti-Hijacking Security:
- Clean-slate server de-registration via Web Dashboard or CLI (
mcpaid server remove <id>). - Ownership verification ensures server IDs cannot be overwritten by unauthorized third parties.
- Passwordless 2FA email authentication with 30-day sliding-window sessions.
- Clean-slate server de-registration via Web Dashboard or CLI (
Agent Safety Circuit Breakers:
- Built-in velocity limiters (sliding 1-minute window).
- Spend ceiling hard caps (
maxPricePerCallUsd,maxTotalBudgetUsd). - Infinite duplicate parameter loop detection.
🚀 Installation
Global CLI
npm install -g @mcpaid/sdk
# or run directly with npx:
npx @mcpaid/sdk --helpTypeScript / Node.js SDK
npm install @mcpaid/sdk📖 Developer Quickstarts
Option A: The 3-Minute Local Developer Quickstart (mcpaid dev)
Monetize an MCP server running on your laptop or workstation without cloud hosting:
- Ensure your local MCP server is running (e.g. on port 3000 at
http://127.0.0.1:3000/mcp). - Generate your configuration & authenticate:
npx @mcpaid/sdk init npx @mcpaid/sdk login - Launch the Live Dev Tunnel & Security Shield:
The CLI creates an encrypted tunnel, registers your server atnpx @mcpaid/sdk devhttps://mcpaid.dev/mcp/:serverId, activates the security shield, and streams live tool executions and earnings to your terminal. - Give your public URL to agents or users:
npx @mcpaid/sdk bridge --gateway https://mcpaid.dev/mcp/:serverId
Option B: Cloud-Deployed Production Server (mcpaid publish)
For MCP servers hosted on public cloud providers (Render, Fly.io, Railway, AWS, Cloudflare Workers):
- Configure
mcpaid.config.json:{ "serverId": "stock-oracle", "name": "Market Intelligence MCP", "upstreamUrl": "https://mcp.yourcompany.com/sse", "payoutWallet": "0xYourBaseL2PayoutAddress", "network": "base", "currency": "USDC", "tools": [ { "toolName": "health_ping", "type": "free" }, { "toolName": "get_stock_quote", "type": "paid", "priceUsd": "0.01" } ] } - Validate and Publish to the Global Edge:
npx @mcpaid/sdk validate npx @mcpaid/sdk publish mcpaid.config.json - Manage & List Live Servers:
npx @mcpaid/sdk server list - Decommission & Remove Servers Anytime:
npx @mcpaid/sdk server remove stock-oracle
Option C: Browser Web Dashboard (mcpaid.dev/dashboard)
Prefer a graphical interface? Manage everything from your browser:
- Passwordless 2FA Login: Enter your developer email and submit the 6-digit verification code. Check "Remember this terminal" for a persistent 30-day session.
- Configure Payout Wallet: Click [ EDIT ] in the dashboard header and set your Base EVM wallet address (
0x...). - Publish Servers: Click >_ Publish MCP Server to open the visual tool pricing builder.
- Disconnect Servers: Click >_ Disconnect Server on any server card to remove it from the network.
- Withdraw Earnings: Click >_ Withdraw to Base L2 to cash out accrued USDC. Within 60 seconds, the automated relayer confirms the transfer on Base Mainnet and stamps the BaseScan transaction link.
🤖 For AI Agents & Users: Calling Monetized Tools
Autonomous agents (Claude Desktop, Cursor, OpenCode, AutoGPT, LangChain, CrewAI) invoke monetized tools using off-chain EIP-712 micro-permits.
1. Generate an Agent Wallet
npx @mcpaid/sdk wallet new --agent --save--save writes the address + key to ./.env (AGENT_ADDRESS, AGENT_PRIVATE_KEY) so
bridge, deposit, and the SDK pick it up automatically. Without --save, set it manually:
AGENT_PRIVATE_KEY=0xYourAgentPrivateKey...2. Fund with Base USDC
- Base Mainnet (Production - 8453):
- Token Contract:
0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 - Withdraw USDC directly from Coinbase selecting the Base network (near-zero fees, instant), or bridge from Ethereum at bridge.base.org.
- Note: Agents only need USDC! Because micro-permits are signed off-chain, agents do not need ETH for gas.
- Token Contract:
- Base Sepolia (Testnet - 84532):
- Token Contract:
0x036CbD53842c5426634e7929541eC2318f3dCF7e - Claim free testnet USDC at faucet.circle.com (select Base Sepolia).
- Token Contract:
3. Connect Claude Desktop
Edit your claude_desktop_config.json (Mac: ~/Library/Application Support/Claude/claude_desktop_config.json):
{
"mcpServers": {
"market-oracle": {
"command": "npx",
"args": [
"-y",
"@mcpaid/sdk",
"bridge",
"--gateway",
"https://mcpaid.dev/mcp/stock-oracle"
],
"env": {
"AGENT_PRIVATE_KEY": "0xYourAgentPrivateKey..."
}
}
}
}4. Connect Cursor / Antigravity
In your project root, create .cursor/mcp.json:
{
"mcpServers": {
"market-oracle": {
"command": "npx -y @mcpaid/sdk bridge --gateway https://mcpaid.dev/mcp/stock-oracle",
"env": {
"AGENT_PRIVATE_KEY": "0xYourAgentPrivateKey..."
}
}
}
}5. Programmatic Integration (TypeScript & Python)
TypeScript Agent SDK
import { ToolPayClientAgent } from '@mcpaid/sdk';
const agent = new ToolPayClientAgent({
privateKey: process.env.AGENT_PRIVATE_KEY as `0x${string}`,
spendPolicy: {
autoApprove: true,
maxPricePerCallUsd: '0.05', // Maximum $0.05 per tool call
maxTotalBudgetUsd: '5.00', // Maximum cumulative spend ceiling
},
});
// Automatically intercepts HTTP 402, signs EIP-712 voucher, and replays tool execution
const result = await agent.executeToolCall(
{
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: { name: 'get_stock_quote', arguments: { symbol: 'AAPL' } },
},
async (req, proof) => {
return fetch('https://mcpaid.dev/mcp/stock-oracle', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${JSON.stringify(proof)}`,
},
body: JSON.stringify(req),
});
}
);Python Autonomous Agent
import json, os, requests
from eth_account import Account
from eth_account.messages import encode_typed_data
GATEWAY_URL = "https://mcpaid.dev/mcp/stock-oracle"
agent = Account.from_key(os.getenv("AGENT_PRIVATE_KEY"))
req = {
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {"name": "get_stock_quote", "arguments": {"symbol": "AAPL"}}
}
# 1. Initial invocation (returns 402 Challenge)
resp = requests.post(GATEWAY_URL, json=req)
if resp.status_code == 402:
challenge = resp.json()["error"]["data"]
# 2. Sign EIP-712 Typed Data off-chain (zero gas)
typed_data = {
"types": {
"EIP712Domain": [
{"name": "name", "type": "string"},
{"name": "version", "type": "string"},
{"name": "chainId", "type": "uint256"},
{"name": "verifyingContract", "type": "address"}
],
"ToolPayment": [
{"name": "serverId", "type": "string"},
{"name": "toolName", "type": "string"},
{"name": "challengeNonce", "type": "string"},
{"name": "amountMicro", "type": "uint256"},
{"name": "recipient", "type": "address"},
{"name": "deadline", "type": "uint256"}
]
},
"primaryType": "ToolPayment",
"domain": {
"name": "ToolPay MicroPermit",
"version": "1",
"chainId": challenge["chainId"],
"verifyingContract": challenge.get("verifyingContract", "0x406240a9af02596a20ef9779aa214143c794ecee")
},
"message": {
"serverId": challenge["serverId"],
"toolName": challenge["toolName"],
"challengeNonce": challenge["challengeNonce"],
"amountMicro": int(challenge["amountMicro"]),
"recipient": challenge["recipientWallet"],
"deadline": int(challenge["expiresAt"])
}
}
signed = agent.sign_message(encode_typed_data(full_message=typed_data))
voucher = {
"scheme": "eip712-permit",
"challengeNonce": challenge["challengeNonce"],
"signerWallet": agent.address,
"signature": signed.signature.hex(),
"deadline": challenge["expiresAt"]
}
# 3. Replay with voucher in Authorization header
headers = {"Authorization": f"Bearer {json.dumps(voucher)}"}
resp = requests.post(GATEWAY_URL, json=req, headers=headers)
print("Tool Result:", resp.json()["result"])🧾 Edge Receipts: Downstream Payment Enforcement
When an agent invokes a paid MCP tool, MCPaid's edge verifies the 402 micropayment, credits your ledger, and proxies the request to your upstream server. But what if your upstream server forwards the call to a downstream backend, database, microservice, or webhook (e.g. committing a database write, enqueueing an expensive job, or calling third-party APIs)?
Without cryptographic proof, your downstream backend cannot distinguish an authorized edge-settled call from an attacker or forked CLI hitting your internal endpoints directly.
Edge Receipts solve this downstream trust boundary:
- When a paid call settles, the edge gateway mints a cryptographically signed receipt and injects it as an
X-MCPaid-ReceiptHTTP header (base64url-encoded JSON). - Your downstream backend verifies the receipt in 5 lines of code with anti-replay defense and tool binding.
[ AI Agent ]
│
│ 1. POST /mcp/:serverId (tools/call)
▼
[ MCPaid Edge Gateway ]
│
│ 2. HTTP 402 Payment Required (Price + Nonce)
▼
[ AI Agent Pays ]
│
│ 3. Signs gasless EIP-712 micro-permit & replays
▼
[ MCPaid Edge Gateway ]
│
│ 4. Settles micropayment on Base L2 ledger (97% Dev / 3% Platform)
│ 5. Mints signed receipt & proxies call with X-MCPaid-Receipt header
▼
[ Downstream Server / Origin Backend ]
│
│ 6. Verifies receipt in 5 lines (HMAC-SHA256 + atomic nonce claim)
▼
[ Commits DB write / executes heavy compute / returns response ]1. Retrieve Your Server's Receipt Secret
Each server has a deterministic receipt secret derived via HKDF-SHA256 from the edge master secret. Retrieve it via the CLI:
# Display your server's receipt secret
npx @mcpaid/sdk server receipt-secret <serverId>
# Rotate secret (previous secret remains valid for 1-hour grace window)
npx @mcpaid/sdk server receipt-secret <serverId> --rotate
# Automatically append or update MCPAID_RECEIPT_SECRET in your local .env
npx @mcpaid/sdk server receipt-secret <serverId> --env2. Downstream Verification Code Snippets
Option A: Express / Node.js Middleware
Use the built-in createReceiptMiddleware for drop-in Express protection:
import express from 'express';
import { createReceiptMiddleware, MemoryReceiptStore } from '@mcpaid/sdk';
const app = express();
app.use(express.json());
// Reject direct scrapers or un-settled calls in 5 lines
app.post(
'/v1/heavy-compute',
createReceiptMiddleware({
secret: process.env.MCPAID_RECEIPT_SECRET!,
expectedTool: 'heavy_compute',
store: new MemoryReceiptStore(), // Prevents replay attacks
}),
(req: any, res) => {
// req.mcpaidReceipt contains verified settlement metadata
res.json({ success: true, payer: req.mcpaidReceipt.agentWallet });
}
);
app.listen(3000);Option B: Cloudflare Worker / Serverless Edge
Validate inside a Cloudflare Worker or Edge Function using verifyEdgeReceipt and SQLite/D1 replay storage:
import { verifyEdgeReceipt, D1ReceiptStore } from '@mcpaid/sdk';
export default {
async fetch(request: Request, env: any): Promise<Response> {
const error = await verifyEdgeReceipt(
{
secret: env.MCPAID_RECEIPT_SECRET,
previousSecret: env.MCPAID_PREVIOUS_RECEIPT_SECRET, // 1-hr rotation grace window
store: new D1ReceiptStore(env.DB), // Atomic SQLite anti-replay
},
{
receipt: request.headers.get('X-MCPaid-Receipt'),
expectedTool: 'cloud_sync_push',
maxAgeSeconds: 300, // 5-minute expiry
}
);
if (error) {
return new Response(JSON.stringify({ error: 'payment_required', message: error }), {
status: 402,
headers: { 'Content-Type': 'application/json' },
});
}
// Proceed with state-changing database write or API call
return new Response(JSON.stringify({ status: 'committed' }), { status: 200 });
},
};Option C: Python Downstream Backend (FastAPI / Flask)
Verify receipts in Python using standard library cryptographic primitives (hmac, hashlib):
import base64, hashlib, hmac, json, os, time
from fastapi import FastAPI, Header, HTTPException
app = FastAPI()
SECRET = os.environ["MCPAID_RECEIPT_SECRET"]
claimed_nonces = set()
def verify_receipt(receipt_header: str, expected_tool: str) -> dict:
if not receipt_header:
raise HTTPException(status_code=402, detail="Missing X-MCPaid-Receipt header")
# Pad base64url string if necessary and decode
padded = receipt_header + "=" * ((4 - len(receipt_header) % 4) % 4)
receipt = json.loads(base64.urlsafe_b64decode(padded).decode("utf-8"))
if receipt.get("v") != 1 or receipt.get("toolName") != expected_tool:
raise HTTPException(status_code=402, detail="Invalid receipt tool or version")
if time.time() > receipt.get("exp", 0) + 60:
raise HTTPException(status_code=402, detail="Receipt expired")
# Recompute HMAC-SHA256 on canonical JSON without 'sig'
sig = receipt.pop("sig", "")
canonical = json.dumps(receipt, sort_keys=True, separators=(",", ":"))
computed = hmac.new(SECRET.encode(), canonical.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(sig, computed):
raise HTTPException(status_code=402, detail="Cryptographic signature mismatch")
nonce = receipt["challengeNonce"]
if nonce in claimed_nonces:
raise HTTPException(status_code=402, detail="Receipt replay attack detected")
claimed_nonces.add(nonce)
return receipt
@app.post("/v1/db-commit")
def commit_action(x_mcpaid_receipt: str = Header(None)):
verified = verify_receipt(x_mcpaid_receipt, expected_tool="db_commit")
return {"status": "success", "amount_paid_micro": verified["amountMicro"]}🛠️ CLI Command Reference
| Command | Arguments / Flags | Description |
| :--- | :--- | :--- |
| mcpaid init | — | Scaffold sample mcpaid.config.json in current directory. |
| mcpaid validate | [config-path] | Validate JSON syntax, pricing rules, and upstream targets. |
| mcpaid dev | [config-path] [--gateway <url>] | Launch zero-config encrypted dev tunnel with local Security Shield. |
| mcpaid tunnel | [port] | Launch standalone Cloudflare tunnel for local port (default: 3000). |
| mcpaid publish | [config-path] [--gateway <url>] | Publish and monetize an MCP server on MCPaid Edge Gateway. |
| mcpaid server list | — | List all MCP servers and pricing rules registered under your account. |
| mcpaid server remove | <server-id> | Disconnect and permanently remove an MCP server (clean slate). |
| mcpaid server receipt-secret | <id> [--rotate] [--env] | Retrieve or rotate HMAC-SHA256 Edge Receipt secret for backend verification. |
| mcpaid login | [--email <addr>] | Sign in with passwordless 2FA email confirmation code. |
| mcpaid whoami | — | Display authenticated developer profile and payout wallet. |
| mcpaid logout | — | Revoke active session token and wipe local credentials. |
| mcpaid withdraw | [amount] | Withdraw accrued USDC earnings to your verified Base L2 wallet. |
| mcpaid withdrawals | — | View payout history, live batch states, and confirmed BaseScan receipts. |
| mcpaid relayer | [--run] | Inspect 1-minute automated relayer status or run a local operator batch. |
| mcpaid wallet new | --developer \| --agent | Generate dedicated EVM keypairs for developer payouts or agent spending. |
| mcpaid wallet status | — | Inspect configured environment wallet addresses and network settings. |
| mcpaid bridge | --gateway <url> [--key <k>] | Pipe local stdio from Claude Desktop or Cursor to remote gateway. |
🔐 Smart Contracts & Base Mainnet Deployment
- Contract:
ToolPayRouter.sol - Network: Base Mainnet (Chain ID
8453) - Contract Address:
0x406240a9af02596a20ef9779aa214143c794ecee - Deployment Tx:
0xdcd1d86775cba316b9d26a5878e3fab4b7bd1f0ebedf382d5bd1d4cef0dce7f7 - Platform Treasury:
0x49E9fEc4e08310Fb106de24711aBCe51028ECbad - Default Take Rate: 3.00% (300 bps)
🧪 Comprehensive Test Suite
MCPaid includes 163 automated unit and integration tests across 25 suites covering edge handlers, cryptographic verifiers, smart contract splits, financial ledgers, edge receipts, and the automated relayer:
npm test# tests 163
# suites 25
# pass 163
# fail 0🛠️ Self-Hosting Your Own Gateway?
Using mcpaid publish, mcpaid dev, and mcpaid.dev/dashboard above means you are on the hosted MCPaid network (global edge, discovery at mcpaid.dev/mcp/:id, managed 60-second relayer, 3.00% protocol fee).
If instead you want to operate your own isolated gateway (your own Cloudflare Worker + D1 + KV + ToolPayRouter contract + treasury), see SELF-HOSTING.md. Note: a self-hosted gateway is a separate network — you lose hosted discovery, dashboard logins, and the managed relayer, and you take on all ops/settlement custody yourself.
📄 License
Apache-2.0 © MCPaid Network. See LICENSE for details.
