{
  "markdown": "# AgentPay — [agentpay.help](https://agentpay.help)\n\n> **Machine-payable AI microservices via the [402 Payment Required](https://x402.org) protocol (x402 / MPP)**\n>\n> No accounts. No API keys. No OAuth. Pay per call in **USDC on Base**.\n\nAgentPay is an open-source reference implementation of the [Machine Payments Protocol](https://x402.org) — wrapping local AI models behind an HTTP 402 paywall so that AI agents (and humans) can pay for compute on a per-request basis using stablecoins.\n\nBuilt with Express 5, `@x402/express`, and Ollama-served Gemma models. Live on Base mainnet with the PayAI facilitator.\n\n---\n\n## Table of Contents\n\n- [Quick Start](#quick-start)\n- [Architecture](#architecture)\n- [Services & Pricing](#services--pricing)\n- [Tech Stack](#tech-stack)\n- [Deployment](#deployment)\n- [API Reference](#api-reference)\n- [Configuration](#configuration)\n- [Contributing](#contributing)\n- [License](#license)\n\n---\n\n## Quick Start\n\n### Prerequisites\n\n- **Node.js** ≥ 20\n- **Ollama** running locally with the required model pulled\n- A **wallet private key** (for receiving payments)\n\n### 1. Clone & install\n\n```bash\ngit clone https://github.com/your-org/AgentPay.git\ncd AgentPay\nnpm install\n```\n\n### 2. Pull the AI model\n\n```bash\nollama pull gemma3:1b\n# Or use a larger model for better quality:\n# ollama pull gemma4:31b-cloud\n```\n\n### 3. Configure\n\n```bash\ncp .env.example .env\n# Edit .env — set SELLER_ADDRESS to your wallet address\n```\n\n### 4. Start the server\n\n```bash\nnpm start\n# AgentPay listening on :4021\n#   payTo:   0xYourWalletAddress\n#   network: eip155:84532 (Base Sepolia testnet)\n#   facilitator: https://x402.org/facilitator\n```\n\n### 5. Test a paid request\n\n```bash\n# Unpaid request → HTTP 402 (paywall)\ncurl -s -o /dev/null -w \"%{http_code}\" -X POST https://agentpay.help/v1/summarize \\\n  -H 'Content-Type: application/json' \\\n  -d '{\"text\":\"Machine Payments Protocol lets AI agents pay for API calls using the HTTP 402 status code.\"}'\n# → 402\n\n# Automated test (requires buyer wallet with USDC)\nnpm run test:402\n```\n\n### 6. Buy a service (buyer client)\n\n```bash\n# Set your buyer private key in .env\necho \"BUYER_PK=0xYourPrivateKey\" >> .env\n\n# Run the buyer script\nnpm run buyer -- /v1/summarize ./payload.json\n```\n\n---\n\n## Architecture\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│                        AgentPay Architecture                   │\n├─────────────────────────────────────────────────────────────────┤\n│                                                                 │\n│  ┌──────────┐    HTTP POST     ┌───────────────────────────┐    │\n│  │  Client   │ ──────────────► │      Express 5 Server     │    │\n│  │ (Agent /  │   (no auth)     │        (port 4021)        │    │\n│  │  Human)   │                 │                           │    │\n│  └──────────┘                 │  ┌─────────────────────┐  │    │\n│       │                       │  │   Payment Middleware  │  │    │\n│       │                       │  │   (@x402/express)    │  │    │\n│       │                       │  │                      │  │    │\n│       │  ◄── HTTP 402 ───────│  │  • Validates x402    │  │    │\n│       │      (paywall)        │  │    payment headers   │  │    │\n│       │                       │  │  • Verifies on-chain │  │    │\n│       │  ──── signed payment ►│  │    via facilitator   │  │    │\n│       │      (USDC)           │  │                      │  │    │\n│       │                       │  └──────────┬──────────┘  │    │\n│       │  ◄── 200 OK ─────────│             │              │    │\n│       │      (result JSON)    │  ┌──────────▼──────────┐  │    │\n│       │                       │  │   Service Handlers   │  │    │\n│       │                       │  │                      │  │    │\n│       │                       │  │  /v1/summarize       │  │    │\n│       │                       │  │  /v1/classify-ins    │  │    │\n│       │                       │  │  /v1/extract         │  │    │\n│       │                       │  └──────────┬──────────┘  │    │\n│       │                       └─────────────┼─────────────┘    │\n│       │                                     │                   │\n│       │                              ┌──────▼──────┐           │\n│       │                              │   Ollama     │           │\n│       │                              │  (local LLM) │           │\n│       │                              │  gemma3:1b   │           │\n│       │                              └─────────────┘           │\n│       │                                                         │\n│  ┌────▼────────────────────────────────────────────────────┐    │\n│  │                  Payment Flow (x402)                    │    │\n│  │                                                         │    │\n│  │  Client ──► HTTP 402 ──► Facilitator ──► On-Chain ──►   │    │\n│  │                │         (PayAI)       Base Mainnet     │    │\n│  │                ▼                         (USDC)         │    │\n│  │          Payment Required                                │    │\n│  │          (price + accepts[])                             │    │\n│  └─────────────────────────────────────────────────────────┘    │\n│                                                                 │\n│  ┌─────────────────────────────────────────────────────────┐    │\n│  │  Free Endpoints (no paywall)                            │    │\n│  │  • /              — Landing page (HTML)                 │    │\n│  │  • /health        — Health check                        │    │\n│  │  • /stats         — Revenue & usage stats               │    │\n│  │  • /.well-known/x402 — Machine-readable service catalog │    │\n│  └─────────────────────────────────────────────────────────┘    │\n│                                                                 │\n│  ┌─────────────────────────────────────────────────────────┐    │\n│  │  Data Layer                                             │    │\n│  │  • data/ledger.json — Append-only payment ledger        │    │\n│  └─────────────────────────────────────────────────────────┘    │\n└─────────────────────────────────────────────────────────────────┘\n```\n\n**How it works:**\n\n1. Client sends `POST /v1/summarize` (or any paid endpoint) — no auth headers needed\n2. Payment middleware intercepts, returns **HTTP 402** with pricing info (`accepts[]`)\n3. Client constructs a USDC payment, signs it, attaches `X-PAYMENT` header\n4. Facilitator verifies the payment on Base mainnet\n5. Middleware grants access → request proceeds to the service handler\n6. Handler calls Ollama, returns AI-generated result as JSON\n\n---\n\n## Services & Pricing\n\n| Endpoint | Price | Description |\n|----------|-------|-------------|\n| `POST /v1/summarize` | **$0.01** | Summarize text (200–20,000 chars). Returns a ~250-word summary. |\n| `POST /v1/classify-insurance` | **$0.02** | Classify insurance leads: intent, urgency, line-of-business, confidence score. |\n| `POST /v1/sentiment` | **$0.02** | Sentiment analysis: positive/negative/neutral with emotions and keywords. |\n| `POST /v1/extract` | **$0.03** | Extract structured key-value fields from raw text (emails, forms, documents). |\n| `POST /v1/translate` | **$0.03** | Text translation to any language. |\n| `POST /v1/code-review` | **$0.05** | AI code review: bugs, security issues, performance, quality analysis. |\n| `POST /v1/insurance-analysis` | **$0.10** | ⭐ FULL BUNDLE — classification + extraction + summary in one call. |\n\nAll services accept USDC on **Base mainnet** (chain ID `8453`) via the `exact` payment scheme. Testnet (Base Sepolia) is available via configuration.\n\n---\n\n## Tech Stack\n\n| Component | Technology |\n|-----------|-----------|\n| **Runtime** | Node.js ≥ 20 (ESM) |\n| **HTTP Server** | Express 5.2 |\n| **Payment Protocol** | `@x402/express` 2.22, `@x402/evm`, `@x402/fetch`, `@x402/extensions` |\n| **Blockchain** | Base (OP Stack L2), USDC stablecoin |\n| **Facilitator** | PayAI x402 facilitator (`x402.org/facilitator`) |\n| **AI Runtime** | Ollama (local inference) |\n| **LLM** | Gemma 3 1B (default) / Gemma 4 31B (recommended) |\n| **Wallet** | `viem` (Ethereum client library) |\n| **Config** | dotenv |\n\n---\n\n## Deployment\n\n### Local Development\n\n```bash\n# Base Sepolia testnet (recommended for development)\ncp .env.example .env\n# Edit .env: PAYMENT_NETWORK=eip155:84532\nnpm start\n```\n\n### Production (Base Mainnet)\n\n```bash\n# Edit .env for mainnet\nPAYMENT_NETWORK=eip155:8453       # Base mainnet\nSELLER_ADDRESS=0xYourMainnetWallet\nOLLAMA_URL=http://127.0.0.1:11434\nMODEL_SUMMARIZE=gemma4:31b-cloud  # Use larger model for quality\nMODEL_CLASSIFY=gemma4:31b-cloud\nMODEL_EXTRACT=gemma4:31b-cloud\n```\n\n### Docker (recommended for production)\n\n```dockerfile\nFROM node:20-slim\nWORKDIR /app\nCOPY package*.json ./\nRUN npm ci --omit=dev\nCOPY src/ ./src/\nCOPY data/ ./data/\nEXPOSE 4021\nHEALTHCHECK CMD curl -f https://agentpay.help/health || exit 1\nCMD [\"node\", \"src/server.js\"]\n```\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `PORT` | No | `4021` | Server port |\n| `SELLER_ADDRESS` | **Yes** | — | Wallet address to receive USDC payments |\n| `PAYMENT_NETWORK` | No | `eip155:84532` | Blockchain network (`eip155:8453` for mainnet) |\n| `FACILITATOR_URL` | No | `https://x402.org/facilitator` | x402 facilitator endpoint |\n| `OLLAMA_URL` | No | `http://127.0.0.1:11434` | Ollama API base URL |\n| `MODEL_SUMMARIZE` | No | `gemma3:1b` | Model for summarize endpoint |\n| `MODEL_CLASSIFY` | No | `gemma3:1b` | Model for classify-insurance endpoint |\n| `MODEL_EXTRACT` | No | `gemma3:1b` | Model for extract endpoint |\n| `PUBLIC_URL` | No | — | Public URL for discovery metadata |\n\n---\n\n## API Reference\n\n### Free Endpoints\n\n#### `GET /`\n\nLanding page with service catalog and usage stats.\n\n#### `GET /health`\n\nHealth check.\n\n```json\n{ \"ok\": true, \"ts\": \"2025-01-01T00:00:00.000Z\" }\n```\n\n#### `GET /stats`\n\nRevenue and usage statistics.\n\n```json\n{\n  \"requests_paid\": 42,\n  \"gross_usd\": 0.84,\n  \"by_service\": { \"summarize\": 0.42, \"classify-insurance\": 0.28, \"extract\": 0.14 },\n  \"last_20\": [...]\n}\n```\n\n#### `GET /.well-known/x402`\n\nMachine-readable service catalog (Bazaar discovery extension). Use this for automated service discovery by AI agents.\n\n```json\n{\n  \"name\": \"AgentPay\",\n  \"description\": \"Pay-per-call AI microservices (x402 / MPP)\",\n  \"endpoints\": [\n    { \"path\": \"/v1/summarize\", \"method\": \"POST\", \"price\": \"$0.01\", \"description\": \"Summarize text (200-20k chars)\" },\n    { \"path\": \"/v1/classify-insurance\", \"method\": \"POST\", \"price\": \"$0.02\", \"description\": \"Insurance lead classification\" },\n    { \"path\": \"/v1/extract\", \"method\": \"POST\", \"price\": \"$0.03\", \"description\": \"Structured field extraction\" }\n  ]\n}\n```\n\n---\n\n### Paid Endpoints\n\nAll paid endpoints require a valid x402 payment in the `X-PAYMENT` header. Unpaid requests receive **HTTP 402 Payment Required**.\n\n#### `POST /v1/summarize` — **$0.01**\n\nSummarize text into a concise ~250-word output.\n\n**Request:**\n\n```json\n{\n  \"text\": \"Your text to summarize (200-20000 characters)...\"\n}\n```\n\n**Response (200 OK):**\n\n```json\n{\n  \"summary\": \"The text discusses...\",\n  \"words\": 247\n}\n```\n\n**Errors:**\n- `400` — Missing `text` field or text exceeds 20,000 characters\n- `402` — Payment required (see x402 protocol)\n- `502` — Upstream AI model failed\n\n---\n\n#### `POST /v1/classify-insurance` — **$0.02**\n\nClassify an insurance lead or customer message.\n\n**Request:**\n\n```json\n{\n  \"text\": \"I was in a car accident last week and need to file a claim urgently...\"\n}\n```\n\n**Response (200 OK):**\n\n```json\n{\n  \"intent\": \"claim\",\n  \"urgency\": \"high\",\n  \"line\": \"auto\",\n  \"confidence\": 0.92\n}\n```\n\n**Possible values:**\n- `intent`: `quote_request` | `renewal` | `claim` | `complaint` | `other`\n- `urgency`: `low` | `medium` | `high`\n- `line`: `auto` | `home` | `life` | `health` | `commercial` | `other`\n\n---\n\n#### `POST /v1/extract` — **$0.03**\n\nExtract structured fields from raw text (emails, forms, documents).\n\n**Request:**\n\n```json\n{\n  \"text\": \"From: john@example.com\\nSubject: Policy #12345 renewal\\nDear customer, your auto policy expires on March 15...\",\n  \"fields\": [\"email\", \"policy_number\", \"expiry_date\"]\n}\n```\n\n**Response (200 OK):**\n\n```json\n{\n  \"email\": \"john@example.com\",\n  \"policy_number\": \"12345\",\n  \"expiry_date\": \"March 15\"\n}\n```\n\nIf `fields` is omitted, all extractable key-value pairs are returned.\n\n---\n\n### Client Library (Buyer)\n\nUse `@x402/fetch` to automatically handle the 402 → payment → retry flow:\n\n```javascript\nimport { wrapFetchWithPayment, x402Client } from \"@x402/fetch\";\nimport { ExactEvmScheme } from \"@x402/evm/exact/client\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nconst signer = privateKeyToAccount(process.env.BUYER_PK);\nconst client = x402Client.fromConfig({\n  schemes: [{ network: \"eip155:*\", client: new ExactEvmScheme(signer) }],\n});\n\nconst payFetch = wrapFetchWithPayment(globalThis.fetch, client);\n\n// This automatically handles the 402 → payment → retry flow\nconst res = await payFetch(\"https://agentpay.help/v1/summarize\", {\n  method: \"POST\",\n  headers: { \"Content-Type\": \"application/json\" },\n  body: JSON.stringify({ text: \"Your text here...\" }),\n});\n\nconst result = await res.json();\nconsole.log(result.summary);\n```\n\n---\n\n## Contributing\n\nContributions are welcome! This is an open-source reference implementation of the x402 / MPP protocol.\n\n### Development Setup\n\n```bash\ngit clone https://github.com/your-org/AgentPay.git\ncd AgentPay\nnpm install\ncp .env.example .env\n# Edit .env with your test wallet and Base Sepolia settings\nnpm start\n```\n\n### Adding a New Service\n\n1. Define the payment middleware entry in `src/server.js` under the `paymentMiddleware()` call\n2. Add the route handler after the middleware block\n3. Register the endpoint in `/.well-known/x402` discovery\n4. Add to the landing page HTML\n\n### Guidelines\n\n- **Keep it simple.** This is a reference implementation — clarity over complexity.\n- **Test on Base Sepolia first.** Use the testnet before going to mainnet.\n- **Use `@x402/` packages.** Don't reinvent payment verification.\n- **Append-only ledger.** Never modify `data/ledger.json` — only append.\n\n### Reporting Issues\n\nOpen a GitHub issue with:\n- Steps to reproduce\n- Expected vs. actual behavior\n- Environment (Node version, OS, model used)\n\n---\n\n## License\n\nMIT\n\n---\n\n## Resources\n\n- [x402 Protocol Spec](https://x402.org) — The Machine Payments Protocol\n- [PayAI Facilitator](https://x402.org/facilitator) — Payment verification service\n- [Base Network](https://base.org) — OP Stack L2 where USDC payments settle\n- [Ollama](https://ollama.com) — Local LLM inference engine\n- [viem](https://viem.sh) — TypeScript Ethereum client\n",
  "bytes": 14703,
  "sha": "5787882d05039d9d6c2c5522583aa992a10225c10e92bb0e1693e65e1f456e1e",
  "repo_slug": "ronaldanton/x402-shop",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_help_agentpay_agentpay_e856022d/readme"
}