# SerenAI x402 Gateway - LLM Integration Guide > This document helps AI assistants understand how to interact with the SerenAI x402 payment gateway for monetized API and database access. ## Overview The SerenAI x402 Gateway enables AI agents to pay for database queries and API access using USDC on Base blockchain via the HTTP 402 Payment Required protocol. Publishers can monetize their data, and AI agents can access it with automatic payment settlement. ## Gateway URL Production: https://api.serendb.com ## x402 MCP Server The recommended way for AI agents to interact with x402-protected resources is through the MCP server. ### Installation ```bash npx @serendb/x402-mcp-server ``` ### Required Environment Variables ``` X402_GATEWAY_URL=https://api.serendb.com WALLET_PRIVATE_KEY=0xYOUR_PRIVATE_KEY ``` ### Claude Desktop Configuration Add to `~/Library/Application Support/Claude/claude_desktop_config.json`: ```json { "mcpServers": { "x402": { "command": "npx", "args": ["@serendb/x402-mcp-server"], "env": { "X402_GATEWAY_URL": "https://api.serendb.com", "WALLET_PRIVATE_KEY": "0xYOUR_KEY" } } } } ``` ### Claude Code Configuration ```bash claude mcp add x402 -s user -e WALLET_PRIVATE_KEY=0xYOUR_KEY -- npx @serendb/x402-mcp-server ``` ### Available MCP Tools 1. **list_publishers** - Discover x402-protected data sources 2. **get_publisher_details** - Get publisher metadata, pricing, and usage examples 3. **get_publisher_pricing_details** - Get detailed pricing configuration 4. **pay_for_query** - Execute API requests with automatic USDC payment 5. **query_database** - Run SQL queries against monetized databases 6. **check_credit_balance** - Check prepaid credit balance 7. **deposit_credits** - Deposit USDC to prepaid balance --- ## Publisher Registration API Publishers can register to monetize their APIs or databases. ### Endpoint ``` POST https://api.serendb.com/agent/publishers Content-Type: application/json ``` ### Publisher Types - `database` - PostgreSQL database with query access - `api` - REST API proxy with per-call pricing - `both` - Combined database and API access ### Registration Schema ```json { "name": "string (required, 1-255 chars)", "email": "string (required, valid email)", "walletAddress": "string (required, 0x + 40 hex chars)", "connectionString": "string (required, valid URL - encrypted at rest)", "publisherType": "database | api | both (default: database)", "resourceName": "string (optional, max 255 chars)", "resourceDescription": "string (optional, max 2000 chars)", "logoUrl": "string (optional, valid URL)", "categories": ["array", "of", "strings"], "upstreamApiUrl": "string (required for api type)", "upstreamApiKey": "string (optional, encrypted at rest)", "pricePerCall": "string (required for api type, decimal USDC)", "pricePerGet": "string (optional, decimal USDC)", "pricePerPost": "string (optional, decimal USDC)", "pricePerPut": "string (optional, decimal USDC)", "pricePerDelete": "string (optional, decimal USDC)", "pricePerPatch": "string (optional, decimal USDC)", "apiKeyHeader": "string (optional, header name for upstream auth)", "apiKeyQueryParam": "string (optional, query param for upstream auth)", "apiKeyHeaders": {"HeaderName": "value"} "(optional, multiple auth headers)", "authType": "static | jwt (default: static)", "jwtAccessKey": "string (required if authType=jwt)", "jwtSecretKey": "string (required if authType=jwt)", "jwtExpirationSeconds": "number (60-86400, default: 1800)", "jwtAlgorithm": "HS256 | HS384 | HS512 (default: HS256)", "allowedPassthroughHeaders": ["array", "of", "header", "names"], "cacheTtlSeconds": "number (0-86400, default: 300)", "usageExample": { "exampleName": { "method": "GET | POST | PUT | DELETE", "path": "/v1/example?param=value", "description": "What this example does", "params": { "paramName": { "required": true, "type": "string | number | boolean | array", "description": "Parameter description" } }, "headers": {"X-Custom": "value"}, "body": {}, "authentication": { "note": "Auth requirements", "requiredHeaders": ["Authorization"] } } }, "billingModel": "x402_per_request | prepaid_credits (default: x402_per_request)", "markupMultiplier": "string (decimal >= 1.0, default: 2.50)", "hourlyRate": "string (required for prepaid_credits billing)", "minimumBalance": "string (decimal, default: 1.00)", "lowBalanceThreshold": "string (decimal, default: 0.50)", "gracePeriodMinutes": "number (0-1440, optional)", "ownershipTrackingEnabled": "boolean (default: false)", "resourceIdResponsePath": "string (JSONPath to resource ID in response)", "resourceIdUrlPattern": "string (URL pattern with :resourceId placeholder)", "protectedOperations": [ {"method": "DELETE", "pattern": "/resources/:id"} ] } ``` ### Response ```json { "publisher": { "id": "uuid", "name": "Publisher Name", "slug": "publisher-name", "email": "email@example.com", "walletAddress": "0x...", "publisherType": "api", "pricePerCall": "0.001", "createdAt": "2024-01-01T00:00:00Z" }, "apiKey": "seren_live_XXXXX (returned only once, save securely)" } ``` --- ## Example: Register an API Publisher ```bash curl -X POST https://api.serendb.com/agent/publishers \ -H "Content-Type: application/json" \ -d '{ "name": "My Data API", "email": "publisher@example.com", "walletAddress": "0x1234567890123456789012345678901234567890", "connectionString": "postgresql://user:pass@host:5432/db", "publisherType": "api", "resourceDescription": "Real-time market data API", "upstreamApiUrl": "https://api.myservice.com", "upstreamApiKey": "sk_live_xxx", "apiKeyHeader": "X-API-Key", "pricePerCall": "0.001", "categories": ["finance", "market-data"], "usageExample": { "getMarkets": { "method": "GET", "path": "/v1/markets?limit=10", "description": "List available markets" } } }' ``` --- ## Example: Register a Database Publisher ```bash curl -X POST https://api.serendb.com/agent/publishers \ -H "Content-Type: application/json" \ -d '{ "name": "Analytics Database", "email": "data@example.com", "walletAddress": "0x1234567890123456789012345678901234567890", "connectionString": "postgresql://user:pass@host:5432/analytics", "publisherType": "database", "resourceDescription": "Historical analytics data", "categories": ["analytics", "historical-data"], "markupMultiplier": "2.50" }' ``` --- ## Database Publisher Management Database publishers have additional endpoints for managing table access and pricing. ### Database Pricing Database queries are priced based on rows returned: ``` Cost = (rows / 1000) * basePricePer1000Rows * markupMultiplier ``` **Pricing Configuration:** - `basePricePer1000Rows` - Base cost per 1000 rows (USDC) - `markupMultiplier` - Publisher's markup (default: 2.50x) ### Update Database Pricing ``` PUT /api/publisher/:publisherId/pricing Authorization: Bearer seren_live_XXXXX Content-Type: application/json { "basePricePer1000Rows": 0.001, "markupMultiplier": 2.50 } ``` ### List Database Tables Introspect all tables in the publisher's database with access control status: ``` GET /api/publisher/:publisherId/databases Authorization: Bearer seren_live_XXXXX ``` **Response:** ```json { "databases": [ { "schema": "public", "table": "users", "rowCount": 10000, "isExposed": true, "isPartnerData": false }, { "schema": "public", "table": "internal_logs", "rowCount": 50000, "isExposed": false, "isPartnerData": false } ] } ``` ### Get Access Control Rules ``` GET /api/publisher/:publisherId/access-control ``` **Response:** ```json { "accessControl": [ { "id": "uuid", "schema": "public", "table": "users", "isExposed": true, "isPartnerData": false, "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } ] } ``` ### Update Table Access Control Control which tables are queryable by AI agents: ``` PUT /api/publisher/:publisherId/access-control Authorization: Bearer seren_live_XXXXX Content-Type: application/json { "schema": "public", "table": "internal_logs", "isExposed": false, "isPartnerData": false } ``` - `isExposed: false` - Hides table from AI agent queries - `isPartnerData: true` - Marks table as partner/sensitive data ### Query Endpoint (For Agents) AI agents execute SQL queries via: ``` POST /agent/database Content-Type: application/json X-PAYMENT: (required after 402 response) { "publisherId": "uuid", "sql": "SELECT * FROM users LIMIT 10" } ``` **Response:** ```json { "rows": [...], "rowCount": 10, "executionTimeMs": 45, "estimatedCost": "0.000025", "actualCost": "0.000025", "transactionHash": "0x..." } ``` --- ## API Publisher Management API publishers proxy requests to upstream APIs with per-call pricing. ### API Pricing API calls are priced per request: - `pricePerCall` - Default price for all methods (USDC) - `pricePerGet`, `pricePerPost`, `pricePerPut`, `pricePerDelete`, `pricePerPatch` - Method-specific overrides ### Update API Pricing ``` PATCH /api/publishers/update Authorization: Bearer seren_live_XXXXX Content-Type: application/json { "pricePerCall": "0.001", "pricePerGet": "0.0005", "pricePerPost": "0.002" } ``` ### Authentication Types **Static API Key (default):** ```json { "authType": "static", "upstreamApiKey": "sk_live_xxx", "apiKeyHeader": "Authorization" } ``` **Multi-Header Auth (e.g., Alpaca):** ```json { "apiKeyHeaders": { "APCA-API-KEY-ID": "your_key_id", "APCA-API-SECRET-KEY": "your_secret" } } ``` **JWT Auth (e.g., Kling AI):** ```json { "authType": "jwt", "jwtAccessKey": "your_access_key", "jwtSecretKey": "your_secret_key", "jwtExpirationSeconds": 1800, "jwtAlgorithm": "HS256" } ``` **Query Parameter Auth:** ```json { "apiKeyQueryParam": "api_key", "upstreamApiKey": "your_key" } ``` ### Passthrough Headers Allow agents to provide their own auth headers: ```json { "allowedPassthroughHeaders": ["Authorization", "X-Custom-Auth"] } ``` ### API Proxy Endpoint (For Agents) AI agents call upstream APIs via: ``` POST /agent/api/:publisherIdOrSlug/* Content-Type: application/json X-PAYMENT: (required after 402 response) { "method": "GET", "path": "/v1/markets?limit=10", "headers": {}, "body": {} } ``` Or direct path proxy: ``` GET /agent/api/:publisherIdOrSlug/v1/markets?limit=10 X-PAYMENT: ``` **Response:** ```json { "data": { ... upstream response ... }, "cost": "0.001", "transactionHash": "0x..." } ``` ### x402 Pass-Through Publishers For upstream services that implement x402 natively: ```json { "publisherType": "api", "upstreamApiUrl": "https://x402.browserbase.com", "pricePerCall": "0" } ``` When `pricePerCall` is 0, the gateway forwards the upstream's 402 payment requirements directly to the agent. --- ## Prepaid Credits Publisher Management Prepaid credits billing allows agents to deposit USDC in advance for session-based or time-based access. ### Prepaid Configuration ```json { "billingModel": "prepaid_credits", "hourlyRate": "0.10", "minimumBalance": "1.00", "lowBalanceThreshold": "0.50", "gracePeriodMinutes": 30 } ``` **Configuration Fields:** - `hourlyRate` - USDC charged per hour of active session - `minimumBalance` - Required balance to start a session - `lowBalanceThreshold` - Warning threshold for low balance - `gracePeriodMinutes` - Grace period before session termination ### Register Prepaid Publisher ```bash curl -X POST https://api.serendb.com/agent/publishers \ -H "Content-Type: application/json" \ -d '{ "name": "Premium Compute Service", "email": "billing@example.com", "walletAddress": "0x1234567890123456789012345678901234567890", "connectionString": "postgresql://user:pass@host:5432/db", "publisherType": "api", "upstreamApiUrl": "https://api.compute.example.com", "billingModel": "prepaid_credits", "hourlyRate": "0.10", "minimumBalance": "1.00", "lowBalanceThreshold": "0.50", "gracePeriodMinutes": 30 }' ``` ### Agent Credit Operations **Check Balance:** ``` GET /api/credits/:publisherId/balance Authorization: Bearer ``` **Response:** ```json { "balance": "5.50", "reserved": "0.10", "available": "5.40", "lowBalanceWarning": false } ``` **Deposit Credits:** ``` POST /api/deposits Content-Type: application/json X-PAYMENT: { "publisherId": "uuid", "amount": "10.00" } ``` **Response:** ```json { "newBalance": "15.50", "depositAmount": "10.00", "transactionHash": "0x..." } ``` ### Update Prepaid Pricing ``` PATCH /api/publishers/update Authorization: Bearer seren_live_XXXXX Content-Type: application/json { "hourlyRate": "0.15", "minimumBalance": "2.00", "lowBalanceThreshold": "1.00", "gracePeriodMinutes": 60 } ``` --- ## Publisher Management Endpoints All management endpoints require authentication: ``` Authorization: Bearer seren_live_XXXXX ``` ### Get Current Publisher ``` GET /api/publishers/me ``` ### Update Publisher ``` PATCH /api/publishers/update ``` ### Update Pricing ``` PUT /api/publisher/:publisherId/pricing ``` ### Upload Logo ``` POST /api/publishers/logo Content-Type: application/json { "logo": "base64_encoded_image_data", "contentType": "image/png | image/jpeg | image/webp | image/svg+xml" } ``` --- ## Public Catalog ### List All Publishers ``` GET https://api.serendb.com/agent/publishers ``` ### Get Publisher by ID or Slug ``` GET https://api.serendb.com/agent/publishers/:publisherIdOrSlug ``` --- ## x402 Payment Flow 1. Agent sends request to gateway (no payment) 2. Gateway returns HTTP 402 with PaymentRequirements header 3. Agent signs EIP-712 transferWithAuthorization message 4. Agent resends request with X-PAYMENT header (base64 encoded) 5. Gateway verifies signature and nonce (replay protection) 6. Gateway executes query/API call 7. Gateway settles payment on-chain via USDC on Base 8. Agent receives response --- ## Pricing Models ### Per-Request (x402_per_request) - Pay for each API call or database query - Price determined by `pricePerCall` or method-specific prices - Database queries priced by rows returned ### Prepaid Credits (prepaid_credits) - Deposit USDC credits in advance - Deducted per request - Supports hourly rate billing for long-running sessions --- ## Categories Common categories for publishers: - finance, market-data, crypto, defi - analytics, historical-data - web-scraping, automation, data-extraction - ai, llm, ml - news, social-media - government, census - x402 (for pass-through x402 endpoints) --- ## Contact - Website: https://serendb.com - Gateway: https://api.serendb.com - GitHub: https://github.com/serenorg - MCP Server: https://github.com/serenorg/x402-mcp-server