# MCPaid (v1.5.2) — Complete Developer & AI Agent Documentation

> **The Open Monetization Gateway for Model Context Protocol (MCP)**  
> Turn free MCP tools into pay-per-use APIs in 60 seconds with sub-cent micropayments via HTTP 402, gasless EIP-712 micro-permits (or pre-funded sessions), and relayer-settled Base L2 USDC payouts.

- **Gateway URL:** `https://mcpaid.dev`
- **Settlement Blockchain:** Base L2 Mainnet (Chain ID `8453`)
- **Router Smart Contract:** [`0x406240a9af02596a20ef9779aa214143c794ecee`](https://basescan.org/address/0x406240a9af02596a20ef9779aa214143c794ecee)
- **Settlement Asset:** Circle Native USDC (Base: `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`)
- **Developer Net Payout:** **97.00%** (withdraw from $1.00; gross minus ~$0.02 network fee)
- **Protocol Fee:** **3.00%** (Zero monthly subscriptions or minimum volume)
- **Agent Session Deposit:** **$1.00 minimum** USDC transfer to the treasury (`npx @mcpaid/sdk deposit`)
- **Payout Engine:** Developer-initiated withdrawals settled by an internal 1-minute batch relayer (`* * * * *`)
- **NPM Package:** `@mcpaid/sdk`

---

## Table of Contents

0. [Get started in 5 minutes](#0-get-started-in-5-minutes)
1. [Protocol Architecture & How it Works](#1-protocol-architecture--how-it-works)
2. [For MCP Developers: 4 Monetization Methods](#2-for-mcp-developers-4-monetization-methods)
   - [Developer Prerequisites: Payout Wallet Setup](#developer-prerequisites-payout-wallet-setup)
   - [Option 1: Terminal CLI Edge Deployment (`mcpaid publish`)](#option-1-terminal-cli-edge-deployment-mcpaid-publish)
   - [Option 2: Zero-Code Reverse Proxy & Hardware Tunnel (`mcpaid dev` / `mcpaid start`)](#option-2-zero-code-reverse-proxy--hardware-tunnel-mcpaid-dev--mcpaid-start)
   - [Option 3: Cloudflare Edge Web Dashboard Portal (`mcpaid.dev/dashboard`)](#option-3-cloudflare-edge-web-dashboard-portal-mcpaiddevdashboard)
   - [Option 4: Native TypeScript / Node.js SDK](#option-4-native-typescript--nodejs-sdk)
3. [Configuration Schema (`mcpaid.config.json`)](#3-configuration-schema-mcpaidconfigjson)
4. [For Users & AI Agents: Calling Monetized Tools](#4-for-users--ai-agents-calling-monetized-tools)
   - [Step 1: Generate Dedicated Agent Wallet](#step-1-generate-dedicated-agent-wallet)
   - [Step 2: Fund Wallet with Base L2 USDC](#step-2-fund-wallet-with-base-l2-usdc)
   - [Step 3: Claude Desktop Configuration](#step-3-claude-desktop-configuration)
   - [Step 4: Cursor, Windsurf & IDE Setup](#step-4-cursor-windsurf--ide-setup)
   - [Step 5: Autonomous Python Agent Integration](#step-5-autonomous-python-agent-integration)
   - [Step 6: Autonomous TypeScript Agent Integration](#step-6-autonomous-typescript-agent-integration)
5. [Automated 1-Minute Base L2 Payout Relayer](#5-automated-1-minute-base-l2-payout-relayer)
6. [Edge Receipts & Downstream Payment Enforcement](#6-edge-receipts--downstream-payment-enforcement)
   - [6.1 The Multi-Hop Trust Boundary Problem](#61-the-multi-hop-trust-boundary-problem)
   - [6.2 Architecture Diagram & End-to-End Flow](#62-architecture-diagram--end-to-end-flow)
   - [6.3 Receipt Payload Schema (v1)](#63-receipt-payload-schema-v1)
   - [6.4 Secret Derivation (HKDF-SHA256) & Zero-Downtime Key Rotation](#64-secret-derivation-hkdf-sha256--zero-downtime-key-rotation)
   - [6.5 Verification API Reference](#65-verification-api-reference)
   - [6.6 Multi-Language Downstream Verification Snippets](#66-multi-language-downstream-verification-snippets)
7. [Security, Anti-Hijacking & Origin Protection](#7-security-anti-hijacking--origin-protection)
8. [CLI Command Reference & Frequently Asked Questions (FAQ)](#8-cli-command-reference--frequently-asked-questions-faq)
   - [8.1 Complete CLI Command Reference](#81-complete-cli-command-reference)
   - [8.2 Frequently Asked Questions (FAQ)](#82-frequently-asked-questions-faq)
9. [Support, Security & Business Contacts](#9-support-security--business-contacts)

---

## 0. Get started in 5 minutes

Two paths. Pick one — everything below is reference material.

### Track A: Spend — call a monetized tool (~2 min)

```bash
# 1. Create an agent wallet — --save writes it to ./.env for you
npx -y @mcpaid/sdk@2.1.3 wallet new -a --save

# 2. Fund it with a few dollars of USDC on Base
# (Coinbase → Base network, or https://bridge.base.org)

# 3. Pre-fund a gasless session (min $1.00 → treasury; key auto-loaded from .env)
npx -y @mcpaid/sdk@2.1.3 deposit 2.00

# 4. Call through the bridge — first paid call auto-answers its own 402
npx -y @mcpaid/sdk@2.1.3 bridge --gateway https://mcpaid.dev/mcp/contextwise
```

Paste JSON-RPC on stdin (initialize → tools/list → tools/call). Free tools
just work; paid tools sign a gasless EIP-712 permit — or draw from your
pre-funded session (step 3) with signed spends and no per-call permits.
Claude Desktop instead? Point an MCP entry at the bridge with
`AGENT_PRIVATE_KEY` in env — full config in §4.

### Track B: Earn — monetize your MCP server (~5 min)

```bash
# 1. Scaffold pricing config in your server directory
npx -y @mcpaid/sdk@2.1.3 init
# edit mcpaid.config.json: payoutWallet (your Base address), per-tool prices

# 2. Log in as a developer
npx -y @mcpaid/sdk@2.1.3 login

# 3a. Server already hosted? Point the edge at it:
npx -y @mcpaid/sdk@2.1.3 publish --upstream https://your-server/mcp
# → live at https://mcpaid.dev/mcp/your-server-id

# 3b. Only local? Expose it through a tunnel instead:
npx -y @mcpaid/sdk@2.1.3 dev
# → same result, routed to http://127.0.0.1:3000/mcp on your machine
```

Verify with Track A against your own gateway URL, then watch earnings accrue — withdraw them once you reach the $1.00 minimum (see §5).

---

## 1. Protocol Architecture & How it Works

Traditional credit card payment gateways fail for autonomous AI agents because agents cannot interact with 3D Secure popups or physical cards. MCPaid implements the **HTTP 402 Payment Required** and **EIP-712** standards to create machine-native micropayments:

```
[ AI Agent / LLM Client ]
        |
        | 1. POST /mcp/:serverId (JSON-RPC tools/call)
        v
[ MCPaid Edge Gateway (mcpaid.dev) ]
        |
        | 2. Returns HTTP 402 Challenge (Price: 0.01 USDC, Nonce, EIP-712 domain)
        v
[ AI Agent Evaluates Spend Budget ]
        |
        | 3. Signs off-chain gasless EIP-712 permit (zero ETH gas required)
        v
[ Replays request with X-Payment-Proof: { ... } ]
        |
        | 4. Verifies permit signature & updates D1 ledger (97% Dev / 3% Platform)
        | 5. Proxies request to Developer Upstream MCP Server with X-MCPaid-Gateway: true
        v
[ Developer Upstream MCP Server ]
        |
        | 6. Executes tool and returns JSON-RPC result
        v
[ Agent receives tool execution result in < 5ms ]
```

---

## 2. For MCP Developers: 4 Monetization Methods

### Developer Prerequisites: Payout Wallet Setup
Before deploying your monetized server, ensure you have an EVM wallet address on Base L2 where your 97% USDC revenue cuts will accumulate. Payouts are developer-initiated (dashboard or CLI) with a $1.00 minimum withdrawal — see §5.

```bash
# Generate a dedicated developer payout wallet via MCPaid CLI:
npx @mcpaid/sdk wallet new --developer --save
```
This prints your new Base L2 address and private key, and `--save` writes them to `./.env` as `PAYOUT_ADDRESS` + `PAYOUT_PRIVATE_KEY`. (Save the private key securely in your password manager too.) The public address is what you provide in your `payoutWallet` configuration. (You can also use any existing EVM address from Coinbase, MetaMask, Rabby, or a hardware wallet).

---

### Option 1: Terminal CLI Edge Deployment (`mcpaid publish`)
**Best for:** Developers deploying directly from their terminal or CI/CD pipelines without leaving their coding environment. Provides a completely automated end-to-end setup for your MCP server.

#### End-to-End Setup Instructions:

1. **Authenticate via Terminal OTP:**
```bash
npx @mcpaid/sdk login
```
Enter your developer email and the 6-digit verification code sent to your inbox. Your session is securely stored in `~/.mcpaid/credentials.json`.

2. **Initialize MCPaid Configuration:**
```bash
npx @mcpaid/sdk init
```
Generates a starter `mcpaid.config.json` in your project root.

3. **Configure Your Server & Tool Pricing:**
Edit `mcpaid.config.json`:
```json
{
  "version": "1.0",
  "server": {
    "id": "financial-intel-mcp",
    "name": "Market Intelligence MCP",
    "upstreamUrl": "https://api.mycompany.com/mcp",
    "payoutWallet": "0xYourBaseL2PayoutAddress",
    "network": "base",
    "currency": "USDC",
    "platformFeeBps": 300
  },
  "tools": [
    { "name": "health_ping", "type": "free", "description": "Free latency check" },
    { "name": "get_quote", "type": "fixed", "priceUsd": "0.01", "description": "Real-time stock quote ($0.01/call)" },
    { "name": "run_backtest", "type": "fixed", "priceUsd": "0.10", "description": "Historical backtest ($0.10/call)" }
  ]
}
```

4. **Validate Configuration:**
```bash
npx @mcpaid/sdk validate mcpaid.config.json
```
Verifies JSON formatting, schema compliance, and upstream connectivity.

5. **Publish to MCPaid Global Edge:**
```bash
npx @mcpaid/sdk publish mcpaid.config.json
```
Registers your server and tool catalog across Cloudflare's global edge network (310+ cities). Your server is immediately reachable at:
`https://mcpaid.dev/mcp/financial-intel-mcp`

6. **Manage & Monitor Live Servers:**
```bash
# List all your registered servers
npx @mcpaid/sdk server list

# Verify current authentication state
npx @mcpaid/sdk whoami

# Remove/decommission a server
npx @mcpaid/sdk server remove financial-intel-mcp
```

> **SSRF Protection Rule:** Cloudflare edge isolates prohibit `localhost` or private IP ranges in `upstreamUrl` during `publish`. Cloud deployments must use public HTTPS domains. For local servers, use Option 2 (`mcpaid dev`).

---

### Option 2: Zero-Code Reverse Proxy & Hardware Tunnel (`mcpaid dev` / `mcpaid start`)
**Best for:** Developers running an MCP server locally on their computer (`localhost:3000`) who want to monetize immediately without paying cloud hosting bills.

> `mcpaid dev` tunnels into the hosted `mcpaid.dev` network (3% protocol fee, managed relayer). `mcpaid start` runs a local embedded gateway on your own machine (your fees, your ops). Operating a full Cloudflare edge clone in production requires an operator agreement — see Self-Hosting below.

```bash
# 1. Initialize configuration in your project
npx @mcpaid/sdk init

# 2. Launch the automated encrypted reverse tunnel
npx @mcpaid/sdk dev
```

- MCPaid establishes an encrypted Cloudflare edge tunnel to your local port (`http://127.0.0.1:3000`).
- Your tools are instantly reachable globally at `https://mcpaid.dev/mcp/:serverId`.
- All paid agent calls tunnel securely into your machine with automatic 402 gatekeeping.

To run a local embedded gateway (your machine, your fees/ops):
```bash
npx @mcpaid/sdk start
```
Operating a full production Cloudflare edge clone (own Worker + D1 + router) is covered in SELF-HOSTING.md and requires an operator agreement (see OPERATOR-LICENSE.md).

---

### Option 3: Cloudflare Edge Web Dashboard Portal (`mcpaid.dev/dashboard`)
**Best for:** Developers who prefer a visual UI.
- Visit: `https://mcpaid.dev/dashboard`
- Sign in with passwordless email 2FA (check "Remember this terminal" for a 30-day session).
- Configure your Base L2 Payout Wallet address under **[ EDIT ]**.
- Click **>_ Publish MCP Server** to open the Dynamic Multi-Tool Pricing Builder.
- Add tools, configure per-tool prices ($0.01, $0.05, or Free), and click **Publish**.
- Track accrued USDC balances and click **[ Withdraw to Base L2 ]** once you reach the $1.00 minimum (gross minus ~$0.02 network fee).

---

### Option 4: Native TypeScript / Node.js SDK
**Best for:** Direct programmatic control inside Express, Hono, Fastify, or Cloudflare Workers.

```bash
npm install @mcpaid/sdk
```

```typescript
import { McpaidServer } from '@mcpaid/sdk';
import express from 'express';

const app = express();
app.use(express.json());

const mcpaid = new McpaidServer({
  serverId: 'custom-mcp',
  payoutWallet: '0xYourBaseL2PayoutAddress',
  network: 'base',
  tools: {
    'free_ping': { type: 'free' },
    'premium_analysis': { priceUsd: '0.05' }
  }
});

app.post('/mcp', async (req, res) => {
  const result = await mcpaid.handleRequest(req.body, { headers: req.headers });
  res.status(result.statusCode).json(result.body);
});

app.listen(3000);
```

---

## 3. Configuration Schema (`mcpaid.config.json`)

```json
{
  "version": "1.0",
  "server": {
    "id": "my-mcp-server",
    "name": "My Monetized MCP Server",
    "upstreamUrl": "https://api.mycompany.com/mcp",
    "payoutWallet": "0xYourBaseL2PayoutAddress",
    "network": "base",
    "currency": "USDC",
    "platformFeeBps": 300
  },
  "tools": [
    {
      "name": "ping",
      "type": "free",
      "description": "Free connectivity check"
    },
    {
      "name": "generate_report",
      "type": "fixed",
      "priceUsd": "0.02",
      "description": "Generates market analytics report ($0.02 / call)",
      "circuitBreaker": {
        "maxCallsPerMinute": 30,
        "maxSessionSpendUsd": "5.00",
        "preventDuplicateLoops": true
      }
    }
  ]
}
```

---

## 4. For Users & AI Agents: Calling Monetized Tools

### Step 1: Generate Dedicated Agent Wallet
Never use your personal cold-storage wallet for automated agents. Generate a lightweight key — `--save` writes it straight to `./.env` so every command picks it up automatically:
```bash
npx @mcpaid/sdk wallet new --agent --save
```
Output provides your public EVM address and `AGENT_PRIVATE_KEY` (saved as `AGENT_ADDRESS` + `AGENT_PRIVATE_KEY` in .env).

### Step 2: Fund Wallet with Base L2 USDC
Send $1.00 - $5.00 USDC to the agent's EVM address directly on the **Base** network:
- Withdraw USDC directly from Coinbase to your agent address (select "Base" network).
- Or bridge from Ethereum Mainnet at [https://bridge.base.org](https://bridge.base.org).
- **Zero ETH Gas Needed:** Agents only need USDC! Permit signatures cost $0.00 in gas.

---

### Step 3: Claude Desktop Configuration
Add the monetized MCP server to your Claude Desktop config:
- **macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows:** `%APPDATA%\Claude\claude_desktop_config.json`

```json
{
  "mcpServers": {
    "paid-mcp": {
      "command": "npx",
      "args": [
        "-y",
        "@mcpaid/sdk",
        "agent-proxy",
        "--url",
        "https://mcpaid.dev/mcp/your-server-id"
      ],
      "env": {
        "AGENT_PRIVATE_KEY": "0xYourAgentBasePrivateKeyHere"
      }
    }
  }
}
```

---

### Step 4: Cursor, Windsurf & IDE Setup
In Cursor or Windsurf Settings > Features > MCP:
- **Type:** `command`
- **Command:** `npx -y @mcpaid/sdk agent-proxy --url https://mcpaid.dev/mcp/your-server-id`
- **Environment Variable:** `AGENT_PRIVATE_KEY=0xYourPrivateKey`

---

### Step 5: Autonomous Python Agent Integration

```python
import os, json, requests
from eth_account import Account
from eth_account.messages import encode_typed_data

AGENT_KEY = os.environ["AGENT_PRIVATE_KEY"]
GATEWAY_URL = "https://mcpaid.dev/mcp/financial-intel-mcp"
account = Account.from_key(AGENT_KEY)

# 1. Initial tool call triggers HTTP 402 challenge
req_payload = {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {"name": "get_quote", "arguments": {"symbol": "NVDA"}}
}
res = requests.post(GATEWAY_URL, json=req_payload)

if res.status_code == 402:
    challenge = res.json()["error"]["data"]
    
    # 2. Sign EIP-712 Permit off-chain (0 gas)
    domain_data = {
        "name": "ToolPay MicroPermit",
        "version": "1",
        "chainId": challenge.get("chainId", 8453),
        "verifyingContract": challenge.get("verifyingContract", "0x406240a9af02596a20ef9779aa214143c794ecee")
    }
    types = {
        "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"}
        ]
    }
    message = {
        "serverId": challenge["serverId"],
        "toolName": challenge["toolName"],
        "challengeNonce": challenge["challengeNonce"],
        "amountMicro": int(challenge["amountMicro"]),
        "recipient": challenge["recipientWallet"],
        "deadline": challenge["expiresAt"]
    }
    
    signable = encode_typed_data(domain_data=domain_data, message_types=types, message_data=message)
    signature = account.sign_message(signable).signature.hex()
    
    proof = {
        "scheme": "eip712-permit",
        "challengeNonce": challenge["challengeNonce"],
        "signerWallet": account.address,
        "signature": f"0x{signature}",
        "deadline": challenge["expiresAt"]
    }
    
    # 3. Replay request with authorization
    headers = {"Authorization": f"Bearer {json.dumps(proof)}"}
    final_res = requests.post(GATEWAY_URL, json=req_payload, headers=headers)
    print("Tool Output:", final_res.json())
```

---

### Step 6: Autonomous TypeScript Agent Integration

```typescript
import { ToolPayClientAgent } from '@mcpaid/sdk';

const agent = new ToolPayClientAgent({
  privateKey: process.env.AGENT_PRIVATE_KEY!,
  spendPolicy: {
    autoApprove: true,
    maxPricePerCallUsd: '0.05',
    maxTotalBudgetUsd: '5.00',
  },
});

// 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_quote', arguments: { symbol: 'AAPL' } },
  },
  async (req, proof) => {
    return fetch('https://mcpaid.dev/mcp/financial-intel-mcp', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${JSON.stringify(proof)}`,
      },
      body: JSON.stringify(req),
    });
  }
);
```

---

### Self-Hosting Your Own Gateway?
Using `mcpaid publish`, `mcpaid dev`, and `mcpaid.dev/dashboard` above means the **hosted MCPaid network** (global edge, discovery at `mcpaid.dev/mcp/:id`, managed 60-second relayer, 3.00% protocol fee). Operating your own isolated Cloudflare edge clone in production requires an operator agreement — see `OPERATOR-LICENSE.md` / `SELF-HOSTING.md`. EIP-712 vouchers are bound to the official router (`0x406240a9af02596a20ef9779aa214143c794ecee`); official clients warn on non-official routers.

---

## 5. Automated 1-Minute Base L2 Payout Relayer

MCPaid settles developer payouts with one developer-initiated request plus zero manual ops after that:
1. **Accrual:** As agents invoke tools, 97% net earnings credit instantly to the developer's internal ledger (3% protocol fee accounted per call).
2. **Queued Withdrawal:** Once earnings reach the **$1.00 minimum withdrawal** (`MIN_WITHDRAWAL_MICRO`), developers click **[ Withdraw to Base L2 ]** in the dashboard or run `mcpaid withdraw`. Requests below $1.00 are rejected — dust payouts cost more in Base L2 gas than they are worth, and earnings simply stay in the balance until they accumulate. Nothing is auto-pushed: the 1-minute relayer only settles tickets you create.
3. **Developer-paid network fee:** Every withdrawal deducts a flat Base L2 network fee (default ~$0.02, `WITHDRAWAL_GAS_FEE_MICRO`) from the payout. You receive **gross minus gas** on-chain; the retained fee offsets the ETH gas the relayer fronts (it may not fully cover spikes in congestion). The exact fee is shown in the withdrawal confirmation (dashboard, CLI, and API response).
4. **Automated Batching:** Every 60 seconds (`* * * * *`), an internal Cloudflare Workers cron task triggers the relayer:
   - Queries pending requests.
   - Encodes and broadcasts native ERC-20 `transfer()` calls for the NET amount to the developer's wallet on Base L2.
   - Pushes the confirmed BaseScan transaction hash to the dashboard.
   - Updates status to `SETTLED`.

### Where the money sits (end-to-end)
- **Agent deposits:** Agents pre-fund gasless spending with a verified on-chain USDC transfer **to the platform treasury** (minimum **$1.00**, `MIN_SESSION_DEPOSIT_MICRO`). The full amount is credited to their session; the 3% protocol cut is NOT taken at deposit — it is split per paid call (97% developer / 3% platform in the ledger).
- **Per paid call:** The gross price splits 97/3 in the ledger. No on-chain movement happens per call.
- **Developer withdrawal:** Gross is locked from the developer balance, the gas fee is retained by the treasury, and the relayer sends the net USDC to the developer's payout wallet.

### Freemium free calls are stake-gated
Tools with `freemium.freeCallsPerDay` grant their free quota **only to wallets holding a $1.00+ MCPaid session balance** — key ownership was proven when the stake was deposited on-chain. Unfunded or unidentified callers skip the free tier and go straight to 402 payment. Quota is consumed atomically in D1, so "X free calls per day" holds globally across edge isolates.

---

## 6. Edge Receipts & Downstream Payment Enforcement

### 6.1 The Multi-Hop Trust Boundary Problem

MCPaid's default reverse proxy verifies payments at the edge: an AI agent requests a tool call, receives an HTTP 402 challenge, signs an EIP-712 permit off-chain, and the gateway proxies the request to your upstream MCP server.

However, in production deployments, your upstream MCP server frequently forwards the call to **downstream infrastructure**:
- Committing a state-changing database write (e.g. Cloudflare D1, PostgreSQL, DynamoDB)
- Enqueueing an asynchronous background job, queue message, or heavy GPU pipeline
- Decrementing proprietary third-party API credits or triggering external microservices
- Dispatching webhooks, sending transactional emails, or storing files

In these architectures, the final hop (**Upstream MCP Server → Downstream Backend / Database**) is a **separate trust domain** that the edge gateway never sees. If an unauthorized client or forked CLI hits your downstream backend endpoints directly, static shared tokens or simple `X-MCPaid-Gateway: true` headers are vulnerable:
1. Static secret tokens are easily leaked, logged, or extracted from client binaries.
2. The downstream backend cannot prove that **this specific call** actually paid the required micropayment for the specified tool.
3. Developers would otherwise have to write and maintain hundreds of lines of custom EIP-712 voucher verification and nonce replay tables.

**Edge Receipts** solve this multi-hop trust boundary. Similar to how Stripe emits signed webhooks (`Stripe-Signature`), MCPaid's edge gateway mints a cryptographic receipt upon 402 settlement and passes it via the `X-MCPaid-Receipt` HTTP header. Downstream services verify the receipt and claim the single-use challenge nonce in **5 lines of code**.

---

### 6.2 Architecture Diagram & End-to-End Flow

```
[ Autonomous AI Agent ]
         │
         │ 1. POST /mcp/:serverId (JSON-RPC tools/call)
         ▼
[ MCPaid Edge Gateway (mcpaid.dev) ]
         │
         │ 2. HTTP 402 Challenge (Price: 0.01 USDC, Nonce, EIP-712 Domain)
         ▼
[ AI Agent Pays ]
         │
         │ 3. Signs gasless EIP-712 permit off-chain & replays request
         ▼
[ MCPaid Edge Gateway ]
         │
         │ 4. Settles micropayment on Base L2 ledger (97% Dev / 3% Platform)
         │ 5. Mints HMAC-SHA256 Edge Receipt (canonical JSON, exp: now + 300s)
         │ 6. Injects X-MCPaid-Receipt: <base64url> and proxies upstream
         ▼
[ Developer Upstream MCP Server ]
         │
         │ 7. Forwards X-MCPaid-Receipt header to internal microservice/backend
         ▼
[ Downstream Backend / Database Worker ]
         │
         │ 8. Verifies HMAC-SHA256 signature in 5 lines
         │ 9. Atomically claims challengeNonce in NonceClaimStore (anti-replay)
         ▼
[ Executes state change, commits DB transaction, returns response ]
```

---

### 6.3 Receipt Payload Schema (v1)

Edge receipts are serialized to canonical JSON (recursively sorted keys without extraneous whitespace) and signed using HMAC-SHA256 with the server's receipt secret. The resulting object is base64url-encoded into the `X-MCPaid-Receipt` HTTP header.

```typescript
export interface EdgeReceiptPayload {
  v: 1;                     // Receipt protocol version (integer: 1)
  serverId: string;         // Unique server identifier (e.g. "financial-intel-mcp")
  toolName: string;         // Exact tool name authorized (e.g. "run_backtest")
  challengeNonce: string;   // Settled 402 challenge nonce (binds to edge payment)
  amountMicro: string;      // Settled amount in micro-USDC (e.g. "100000" = 0.100000 USDC)
  recipient: string;        // Developer payout wallet address (0x...)
  treasury: string;         // MCPaid platform treasury wallet (0x49E9...)
  feeBps: number;           // Protocol fee basis points (e.g. 300 = 3.00%)
  chainId: number;          // Settlement EVM chain ID (e.g. 8453 for Base Mainnet)
  settledAt: number;        // Unix epoch timestamp in seconds
  exp: number;              // Expiry timestamp in seconds (default: settledAt + 300s)
  agentWallet?: string;     // Payer wallet address (binds payment to agent identity)
  txId?: string;            // Ledger transaction id of the settlement (edge-minted receipts)
}

export interface EdgeReceipt extends EdgeReceiptPayload {
  sig: string;              // 64-character lowercase hex HMAC-SHA256 signature
}
```

Example Decoded JSON:
```json
{
  "v": 1,
  "serverId": "financial-intel-mcp",
  "toolName": "run_backtest",
  "challengeNonce": "rcpt_k8s2j19x0m27n",
  "amountMicro": "100000",
  "recipient": "0x16d365427b4958579adc3593c4c6e8c0ad6eb759",
  "treasury": "0x49e9fec4e08310fb106de24711abce51028ecbad",
  "feeBps": 300,
  "chainId": 8453,
  "settledAt": 1758120000,
  "exp": 1758120300,
  "agentWallet": "0x9876543210987654321098765432109876543210",
  "txId": "txn_01J9...",
  "sig": "b2f5c9e43...64-char-hex..."
}
```

> **Settlement semantics:** a receipt proves the edge *settled* payment at
> `settledAt`. If the upstream call subsequently fails, the edge refunds the
> settlement — but an already-delivered receipt stays valid until `exp`.
> For high-value backends, log `txId` and reconcile against the ledger;
> a revocation-check endpoint is planned (see Edge Receipts plan §8.2).

---

### 6.4 Secret Derivation (HKDF-SHA256) & Zero-Downtime Key Rotation

To prevent global blast radius if an individual developer's secret is inadvertently leaked, receipt secrets are **scoped per server**:

1. **Deterministic HKDF Derivation**: The gateway derives each server's secret from a master edge secret using HKDF-SHA256 (`info: "mcpaid-edge-receipt-v1:${serverId}"`). The derived secret format is `mcpaid_sec_${64-hex}`.
2. **Zero-Downtime Key Rotation**: When you rotate a secret (`--rotate`), the edge immediately begins signing receipts with the new key version while retaining the previous secret for a **1-hour grace window**. In-flight calls and existing backend workers seamlessly validate during the rollout window.
3. **CLI Secret Management**:

```bash
# Retrieve current server secret
npx @mcpaid/sdk server receipt-secret financial-intel-mcp

# Rotate secret with 1-hour backwards-compatible grace window
npx @mcpaid/sdk server receipt-secret financial-intel-mcp --rotate

# Automatically append or update MCPAID_RECEIPT_SECRET in your local .env
npx @mcpaid/sdk server receipt-secret financial-intel-mcp --env
```

---

### 6.5 Verification API Reference

`@mcpaid/sdk` exports complete verification utilities in `src/edge-receipts.ts`:

#### `verifyEdgeReceipt(env, options): Promise<string | null>`
The primary 5-line verification helper. Returns `null` if verification passes and the nonce is successfully claimed, or returns a descriptive error string if invalid, expired, underpaid, or replayed.

```typescript
import { verifyEdgeReceipt } from '@mcpaid/sdk';

const error = await verifyEdgeReceipt(
  {
    secret: process.env.MCPAID_RECEIPT_SECRET!,
    previousSecret: process.env.MCPAID_PREVIOUS_RECEIPT_SECRET, // Optional 1-hr grace key
    store: myNonceStore,                                         // Optional replay store
  },
  {
    receipt: req.headers['x-mcpaid-receipt'],
    expectedTool: 'run_backtest',                               // Enforces tool binding
    expectedServer: 'financial-intel-mcp',                       // Enforces server binding
    minAmountMicro: '100000',                                   // Enforces minimum payment ($0.10)
    maxAgeSeconds: 300,                                         // Expiry limit (default 300s)
    clockSkewSeconds: 60,                                       // Tolerable clock skew (default 60s)
  }
);

if (error) {
  return res.status(402).json({ error: 'payment_required', message: error });
}
```

#### `parseAndVerifyEdgeReceipt(env, options)`
Low-level parser returning `{ valid: true, receipt: EdgeReceipt }` or `{ valid: false, error: string }`. Useful when downstream business logic needs to inspect `receipt.amountMicro`, `receipt.agentWallet`, or `receipt.settledAt`.

#### `createReceiptMiddleware(options)`
Drop-in HTTP middleware for Express, Connect, or Node.js HTTP servers. Automatically extracts `X-MCPaid-Receipt`, parses, validates, and attaches the verified receipt to `req.mcpaidReceipt`.

#### `MemoryReceiptStore`
In-memory implementation of `NonceClaimStore` for tests, local development, and single-instance Node.js backends. Provides `claimNonce()`, `hasNonce()`, and `pruneExpired()`.

#### `D1ReceiptStore`
High-concurrency SQLite / Cloudflare D1 implementation of `NonceClaimStore`. Uses atomic `INSERT INTO mcpaid_receipt_nonces ... ON CONFLICT(nonce) DO NOTHING` to guarantee single-use replay defense across distributed edge workers.

---

### 6.6 Multi-Language Downstream Verification Snippets

#### 1. Cloudflare Workers (TypeScript / D1)

```typescript
import { verifyEdgeReceipt, D1ReceiptStore } from '@mcpaid/sdk';

export interface Env {
  DB: D1Database;
  MCPAID_RECEIPT_SECRET: string;
  MCPAID_PREVIOUS_RECEIPT_SECRET?: string;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // 5-line payment verification & atomic anti-replay
    const err = await verifyEdgeReceipt(
      {
        secret: env.MCPAID_RECEIPT_SECRET,
        previousSecret: env.MCPAID_PREVIOUS_RECEIPT_SECRET,
        store: new D1ReceiptStore(env.DB),
      },
      {
        receipt: request.headers.get('X-MCPaid-Receipt'),
        expectedTool: 'cloud_sync_push',
        expectedServer: 'contextwise-cloud',
      }
    );

    if (err) {
      return new Response(JSON.stringify({ error: 'payment_required', message: err }), {
        status: 402,
        headers: { 'Content-Type': 'application/json' },
      });
    }

    // Safely perform downstream state changes (e.g. database write)
    return new Response(JSON.stringify({ success: true, message: 'Sync committed' }), {
      headers: { 'Content-Type': 'application/json' },
    });
  },
};
```

#### 2. Express.js Middleware (Node.js)

```typescript
import express from 'express';
import { createReceiptMiddleware, MemoryReceiptStore } from '@mcpaid/sdk';

const app = express();
app.use(express.json());

const store = new MemoryReceiptStore();

app.post(
  '/api/v1/backtest',
  createReceiptMiddleware({
    secret: process.env.MCPAID_RECEIPT_SECRET!,
    expectedTool: 'run_backtest',
    expectedServer: 'financial-intel-mcp',
    store,
  }),
  (req: any, res) => {
    const { amountMicro, agentWallet } = req.mcpaidReceipt;
    console.log(`Executing backtest for agent ${agentWallet} (paid: ${amountMicro} micro-USDC)`);
    res.json({ status: 'completed', result: { sharpeRatio: 2.14, pnl: '+32.4%' } });
  }
);

app.listen(8080, () => console.log('Backend listening on port 8080'));
```

#### 3. Python (FastAPI / Flask)

Verification can also be implemented in zero-dependency Python using standard library `hmac` and `hashlib`:

```python
import base64
import hashlib
import hmac
import json
import os
import time
from fastapi import FastAPI, Header, HTTPException

app = FastAPI()
SECRET = os.environ.get("MCPAID_RECEIPT_SECRET", "")
claimed_nonces = set()

def verify_mcpaid_receipt(receipt_header: str, expected_tool: str, expected_server: str = None) -> dict:
    if not receipt_header:
        raise HTTPException(status_code=402, detail="Missing X-MCPaid-Receipt header")
    
    # Base64url decode with padding
    padded = receipt_header + "=" * ((4 - len(receipt_header) % 4) % 4)
    try:
        raw_json = base64.urlsafe_b64decode(padded.encode()).decode("utf-8")
        receipt = json.loads(raw_json)
    except Exception as e:
        raise HTTPException(status_code=402, detail=f"Malformed receipt encoding: {str(e)}")
    
    # Version and binding checks
    if receipt.get("v") != 1:
        raise HTTPException(status_code=402, detail=f"Unsupported receipt version: {receipt.get('v')}")
    if receipt.get("toolName") != expected_tool:
        raise HTTPException(status_code=402, detail=f"Receipt tool mismatch: {receipt.get('toolName')}")
    if expected_server and receipt.get("serverId") != expected_server:
        raise HTTPException(status_code=402, detail=f"Receipt server mismatch: {receipt.get('serverId')}")
    
    now = int(time.time())
    if now > receipt.get("exp", 0) + 60:
        raise HTTPException(status_code=402, detail="Receipt expired")
    if receipt.get("settledAt", 0) > now + 60:
        raise HTTPException(status_code=402, detail="Receipt timestamp in the future")
    
    # Recompute HMAC-SHA256 signature on canonical JSON (sorted keys without 'sig')
    sig = receipt.pop("sig", None)
    if not sig:
        raise HTTPException(status_code=402, detail="Missing receipt signature")
    
    canonical_json = json.dumps(receipt, sort_keys=True, separators=(",", ":"))
    computed_sig = hmac.new(SECRET.encode("utf-8"), canonical_json.encode("utf-8"), hashlib.sha256).hexdigest()
    
    if not hmac.compare_digest(sig, computed_sig):
        raise HTTPException(status_code=402, detail="Receipt cryptographic signature mismatch")
    
    # Anti-replay check
    nonce = receipt.get("challengeNonce")
    if nonce in claimed_nonces:
        raise HTTPException(status_code=402, detail="Receipt replay attack: challenge nonce already claimed")
    claimed_nonces.add(nonce)
    
    return receipt

@app.post("/v1/db-commit")
def commit_action(x_mcpaid_receipt: str = Header(None)):
    receipt = verify_mcpaid_receipt(x_mcpaid_receipt, expected_tool="db_commit")
    return {"status": "ok", "paid_micro": receipt["amountMicro"], "payer": receipt.get("agentWallet")}
```

---

## 7. Security, Anti-Hijacking & Origin Protection

1. **Origin Verification & Cryptographic Edge Receipts (`X-MCPaid-Gateway` & `X-MCPaid-Receipt`):**  
   MCPaid proxies verified requests to your upstream server with:
   ```http
   X-MCPaid-Gateway: true
   X-MCPaid-Server-Id: your-server-id
   X-MCPaid-Network: base
   X-MCPaid-Receipt: <base64url-encoded-hmac-receipt>
   ```
   - For basic reverse proxies, reject any direct traffic on your upstream server that lacks `X-MCPaid-Gateway: true`.
   - For downstream microservices, databases, or multi-hop pipelines, verify `X-MCPaid-Receipt` using `verifyEdgeReceipt` to cryptographically prove that the call paid the required micropayment and has not been replayed.

2. **Server Anti-Hijacking:**  
   When updating an existing `serverId`, MCPaid validates that the caller matches the registered owner email or user ID. Malicious developers cannot hijack another developer's server.

3. **SSRF Filtering:**  
   Cloudflare Workers blocks private IPs (`127.0.0.1`, `localhost`, `10.x.x.x`, `192.168.x.x`) and cloud metadata endpoints (`169.254.169.254`).

4. **Cross-Chain Isolation:**  
   EIP-712 domain separates Base Sepolia (`84532`) from Base Mainnet (`8453`). Signatures signed on testnet are cryptographically rejected on Mainnet.

---

## 8. CLI Command Reference & Frequently Asked Questions (FAQ)

### 8.1 Complete CLI Command Reference

| Command | Description |
| :--- | :--- |
| `npx @mcpaid/sdk init` | Creates a starter `mcpaid.config.json` template in current directory. |
| `npx @mcpaid/sdk dev` | Launches instant encrypted reverse tunnel to monetize local `localhost:3000` MCP servers. |
| `npx @mcpaid/sdk publish` | Publishes cloud MCP server configuration to the global edge gateway (`mcpaid.dev`). |
| `npx @mcpaid/sdk validate` | Verifies configuration syntax, tools, pricing, and upstream targets. |
| `npx @mcpaid/sdk login` | Authenticates developer terminal session via 6-digit email OTP. |
| `npx @mcpaid/sdk logout` | Revokes local session and clears `~/.mcpaid/credentials.json`. |
| `npx @mcpaid/sdk whoami` | Displays authenticated profile, email verification, and payout wallet. |
| `npx @mcpaid/sdk wallet new --agent` | Generates a new EVM keypair for AI agent usage (add `--save` to write it to ./.env). |
| `npx @mcpaid/sdk wallet new --developer` | Generates a new EVM keypair for receiving developer payouts (add `--save` to write it to ./.env). |
| `npx @mcpaid/sdk server list` | Lists all registered MCP servers owned by your developer account. |
| `npx @mcpaid/sdk server remove <id>` | Disconnects and deletes an MCP server from the edge gateway (clean slate). |
| `npx @mcpaid/sdk server receipt-secret <id> [--rotate] [--env]` | Retrieves or rotates the HMAC-SHA256 Edge Receipt secret for backend verification. |
| `npx @mcpaid/sdk withdraw` | Requests an on-chain withdrawal of accrued USDC earnings (minimum $1.00; you receive gross minus a ~$0.02 network fee). |
| `npx @mcpaid/sdk withdrawals` | Displays historical payouts and live BaseScan transaction receipts. |
| `npx @mcpaid/sdk deposit <usd> [--key 0x...]` | Transfers USDC to the treasury on-chain (min $1.00) and credits a gasless session wallet. Key auto-loads from .env. |
| `npx @mcpaid/sdk bridge --gateway <url>` | Stdio bridge enabling Claude Desktop and Cursor to call paid tools (`agent-proxy --url` alias also works). |

---

### 8.2 Frequently Asked Questions (FAQ)

**Q: Do AI agents need ETH to pay gas fees?**  
No. Agents only need native USDC on Base L2. Micropayments are authorized off-chain using EIP-712 permits ($0.00 gas). The platform relayer handles on-chain batching.

**Q: Can I monetize an MCP server running on my local laptop?**  
Yes! Run `npx @mcpaid/sdk dev`. The CLI creates an encrypted reverse tunnel to your local hardware port without port forwarding, dynamic DNS, or public IPs.

**Q: When and how do developers get paid?**  
Earnings accrue in real time (97% net per call). Request a withdrawal via the dashboard or `npx @mcpaid/sdk withdraw` once you reach the $1.00 minimum — you receive gross minus a ~$0.02 Base L2 network fee, settled on-chain by the 1-minute relayer. You can monitor transaction receipts on BaseScan.

**Q: How does MCPaid prevent users from bypassing the gateway to call my server directly?**  
MCPaid never exposes your upstream URL publicly. When forwarding paid calls, it injects `X-MCPaid-Gateway: true` and the cryptographic `X-MCPaid-Receipt` header. Upstream servers can verify `X-MCPaid-Gateway`, and downstream microservices can verify `X-MCPaid-Receipt` to guarantee that the caller actually paid through the edge gateway.

**Q: How do Edge Receipts protect downstream databases and backend services?**  
If your MCP server triggers database writes, API credits, or asynchronous jobs, checking static headers is not enough. Edge Receipts provide a cryptographically signed HMAC-SHA256 payload bound to the settled challenge nonce, server ID, tool name, and price. Your backend verifies the signature and records the nonce in 5 lines of code, mathematically preventing forked clients or replay attacks.

---

## 9. Support, Security & Business Contacts

For technical assistance, integration troubleshooting, or commercial inquiries:

- **Developer & Technical Support:** [`support@mcpaid.dev`](mailto:support@mcpaid.dev)
  - Integration assistance with Claude Desktop, Cursor, Windsurf, LangChain, or custom autonomous agents
  - MCP reverse proxy setup, local tunnel debugging (`mcpaid dev`), and origin protection
  - Base L2 USDC micropayment and automated 60-second settlement verification
  - Security disclosures and vulnerability reporting
  - Response SLA: Within 24 hours

- **Business, Partnerships & Enterprise:** [`business@mcpaid.dev`](mailto:business@mcpaid.dev)
  - Enterprise volume discounts and high-frequency agent relays
  - Dedicated private edge gateways and custom RPC infrastructure
  - Institutional treasury integration, revenue splits, and ecosystem partnerships
  - Priority business evaluation (Mon–Fri)

- **Official Portals:** [https://mcpaid.dev](https://mcpaid.dev) • [https://mcpaid.dev/docs](https://mcpaid.dev/docs) • [https://mcpaid.dev/dashboard](https://mcpaid.dev/dashboard)

---
*Generated by MCPaid Protocol Gateway (https://mcpaid.dev) • Version 1.5.2*
