{"_id":"402ok-mcp","_rev":"5-653f66847ed5bececaa5b69e6088406f","name":"402ok-mcp","dist-tags":{"latest":"0.1.4"},"versions":{"0.1.0":{"name":"402ok-mcp","version":"0.1.0","keywords":["http-402","payment","mcp","middleware","x402","okx","xlayer","blockchain"],"author":"","license":"MIT","_id":"402ok-mcp@0.1.0","maintainers":[{"name":"kinhunt","email":"kinhunt@gmail.com"}],"homepage":"https://github.com/anthropics/402ok#readme","bugs":{"url":"https://github.com/anthropics/402ok/issues"},"dist":{"shasum":"b9cc18f83cf868d449679af4250956236fbf79d2","tarball":"https://registry.npmjs.org/402ok-mcp/-/402ok-mcp-0.1.0.tgz","fileCount":25,"integrity":"sha512-zhurXYw7Pmbb7sTs0mOqmdPKmZv+hLA8wKY0Plktqf1UAnmNTMo7fsS6+0tvaeLIZq13SJkVHwHNOioCvZdo6g==","signatures":[{"sig":"MEQCICGUT15eZrmWj/KEjZBAG11KxcxsuyV3fwxL68yzUl+6AiBN5bZELMGwLC7zeLgu+66z6dhxSydfW5MJwHyGja/qdw==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":41117},"main":"./dist/index.js","type":"module","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"}},"gitHead":"9c74804a482ed3d85cd2fea16502e46d71e5b689","scripts":{"build":"tsc","watch":"tsc --watch"},"_npmUser":{"name":"kinhunt","email":"kinhunt@gmail.com"},"repository":{"url":"git+https://github.com/anthropics/402ok.git","type":"git"},"_npmVersion":"11.6.2","description":"MCP server middleware for HTTP 402 Payment Required with support for multiple networks including OKX/XLayer","directories":{},"_nodeVersion":"22.12.0","dependencies":{},"_hasShrinkwrap":false,"devDependencies":{"zod":"^3.25.76","typescript":"^5.7.3","@types/node":"^22.13.4","@modelcontextprotocol/sdk":"^1.17.4"},"peerDependencies":{"zod":"^3.25.76","@modelcontextprotocol/sdk":"^1.17.4"},"_npmOperationalInternal":{"tmp":"tmp/402ok-mcp_0.1.0_1764839834342_0.9682972824235652","host":"s3://npm-registry-packages-npm-production"}},"0.1.1":{"name":"402ok-mcp","version":"0.1.1","keywords":["http-402","payment","mcp","middleware","x402","okx","xlayer","blockchain"],"author":"","license":"MIT","_id":"402ok-mcp@0.1.1","maintainers":[{"name":"kinhunt","email":"kinhunt@gmail.com"}],"homepage":"https://github.com/payincom/402ok-mcp#readme","bugs":{"url":"https://github.com/payincom/402ok-mcp/issues"},"dist":{"shasum":"87eeb90b238e2ed2bdea4b100084c921a9167930","tarball":"https://registry.npmjs.org/402ok-mcp/-/402ok-mcp-0.1.1.tgz","fileCount":22,"integrity":"sha512-2rV6pC6rvEnNVWVGlWmCREKElBdGlbuPHUcP0H/RmJmmQLY468dqEfd+/n1+sKES7p+VVQqfcm4fN788oIIJIw==","signatures":[{"sig":"MEYCIQDbvo8A5fy2bc5f3WQ6fhgqozEd8SG46w8BJUb4qTInHQIhAIhdaQX59LVMrYW7ba9bJDKAxEBTXFj3zeokZFU46v+j","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":49011},"main":"./dist/index.js","type":"module","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"}},"gitHead":"722eff07d69b4ccf08cb135f1385e25298cd1133","scripts":{"build":"tsc","watch":"tsc --watch"},"_npmUser":{"name":"kinhunt","email":"kinhunt@gmail.com"},"repository":{"url":"git+https://github.com/payincom/402ok-mcp.git","type":"git"},"_npmVersion":"11.6.2","description":"MCP server middleware for HTTP 402 Payment Required with support for multiple networks including OKX/XLayer","directories":{},"_nodeVersion":"22.12.0","dependencies":{},"_hasShrinkwrap":false,"devDependencies":{"zod":"^3.25.76","typescript":"^5.7.3","@types/node":"^22.13.4","@modelcontextprotocol/sdk":"^1.17.4"},"peerDependencies":{"zod":"^3.25.76","@modelcontextprotocol/sdk":"^1.17.4"},"_npmOperationalInternal":{"tmp":"tmp/402ok-mcp_0.1.1_1764977139963_0.7128231532729923","host":"s3://npm-registry-packages-npm-production"}},"0.1.2":{"name":"402ok-mcp","version":"0.1.2","keywords":["http-402","payment","mcp","middleware","x402","okx","xlayer","blockchain"],"author":"","license":"MIT","_id":"402ok-mcp@0.1.2","maintainers":[{"name":"kinhunt","email":"kinhunt@gmail.com"}],"homepage":"https://github.com/payincom/402ok-mcp#readme","bugs":{"url":"https://github.com/payincom/402ok-mcp/issues"},"dist":{"shasum":"8a54cbd0b4055d4bbe3c91ffe5ea29c355d1dd03","tarball":"https://registry.npmjs.org/402ok-mcp/-/402ok-mcp-0.1.2.tgz","fileCount":22,"integrity":"sha512-8BFJ3hJn2RNcWKwoV5CXOn7RfWxUnbiaf06PPCo28Z6x2arEuYDSD5dLZ2kdqni7m6AYUjZ1vhlt/hhfn9uZ/A==","signatures":[{"sig":"MEUCIFNC2bD1qPEFVCMsDYvoIwk1dcjRlA6/hBqVuAnsffCNAiEA5AT+zFOAOh13DNx3Wl93RndFKxBdjgpgu35S6tUsz4M=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":52807},"main":"./dist/index.js","type":"module","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"}},"gitHead":"e5821e2efc4bc295e872bf2aa4aef331a65891d2","scripts":{"build":"tsc","watch":"tsc --watch"},"_npmUser":{"name":"kinhunt","email":"kinhunt@gmail.com"},"repository":{"url":"git+https://github.com/payincom/402ok-mcp.git","type":"git"},"_npmVersion":"11.6.2","description":"MCP server middleware for HTTP 402 Payment Required with support for multiple networks including OKX/XLayer","directories":{},"_nodeVersion":"22.12.0","dependencies":{},"_hasShrinkwrap":false,"devDependencies":{"zod":"^3.25.76","typescript":"^5.7.3","@types/node":"^22.13.4","@modelcontextprotocol/sdk":"^1.17.4"},"peerDependencies":{"zod":"^3.25.76","@modelcontextprotocol/sdk":"^1.17.4"},"_npmOperationalInternal":{"tmp":"tmp/402ok-mcp_0.1.2_1764978295568_0.20047212104617507","host":"s3://npm-registry-packages-npm-production"}},"0.1.3":{"name":"402ok-mcp","version":"0.1.3","keywords":["http-402","payment","mcp","middleware","x402","okx","xlayer","blockchain"],"author":"","license":"MIT","_id":"402ok-mcp@0.1.3","maintainers":[{"name":"kinhunt","email":"kinhunt@gmail.com"}],"homepage":"https://github.com/payincom/402ok-mcp#readme","bugs":{"url":"https://github.com/payincom/402ok-mcp/issues"},"dist":{"shasum":"5e3653a0c6f018b809ac14ed91f6cc66cae9715d","tarball":"https://registry.npmjs.org/402ok-mcp/-/402ok-mcp-0.1.3.tgz","fileCount":22,"integrity":"sha512-NH2QrXWlgACNe/hpi7oOBhJuruGXf17ODhBAZpFDypjwS1BeVQh6muQRdILtgZ+M3L58orpuvG9qc996eBZNYg==","signatures":[{"sig":"MEUCIHFmloz0+cHtGMVzed3NyDDbo0u0biuc1OgOHbyY21LcAiEAuaRLvfDe7iYxuMGbDb7XteXCy860d/pK0nG2M4ughrg=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":56612},"main":"./dist/index.js","type":"module","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"}},"gitHead":"f32343c7fa7813a47f928addad3eae88682c91b0","scripts":{"build":"tsc","watch":"tsc --watch"},"_npmUser":{"name":"kinhunt","email":"kinhunt@gmail.com"},"repository":{"url":"git+https://github.com/payincom/402ok-mcp.git","type":"git"},"_npmVersion":"11.6.2","description":"MCP server middleware for HTTP 402 Payment Required with support for multiple networks including OKX/XLayer","directories":{},"_nodeVersion":"22.12.0","dependencies":{},"_hasShrinkwrap":false,"devDependencies":{"zod":"^3.25.76","typescript":"^5.7.3","@types/node":"^22.13.4","@modelcontextprotocol/sdk":"^1.17.4"},"peerDependencies":{"zod":"^3.25.76","@modelcontextprotocol/sdk":"^1.17.4"},"_npmOperationalInternal":{"tmp":"tmp/402ok-mcp_0.1.3_1764978446855_0.9732031948478344","host":"s3://npm-registry-packages-npm-production"}},"0.1.4":{"name":"402ok-mcp","version":"0.1.4","description":"MCP server middleware for HTTP 402 Payment Required with support for multiple networks including OKX/XLayer","main":"./dist/index.js","types":"./dist/index.d.ts","type":"module","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"}},"scripts":{"build":"tsc","watch":"tsc --watch"},"repository":{"type":"git","url":"git+https://github.com/payincom/402ok-mcp.git"},"homepage":"https://github.com/payincom/402ok-mcp#readme","bugs":{"url":"https://github.com/payincom/402ok-mcp/issues"},"keywords":["http-402","payment","mcp","middleware","x402","okx","xlayer","blockchain"],"author":"","license":"MIT","peerDependencies":{"@modelcontextprotocol/sdk":"^1.17.4","zod":"^3.25.76"},"dependencies":{},"devDependencies":{"@modelcontextprotocol/sdk":"^1.17.4","@types/node":"^22.13.4","typescript":"^5.7.3","zod":"^3.25.76"},"gitHead":"12475a1a11381233bd8842baa8f614d735831b87","_id":"402ok-mcp@0.1.4","_nodeVersion":"22.12.0","_npmVersion":"11.6.2","dist":{"integrity":"sha512-HkQTncy9nBdDUol5sD2l9gPEVXbUL/d+znDOMPKvwyhMIc8bb9alPkhdRkxVCSqC5LFVNQi+YPUDscYzScANTA==","shasum":"6772b03a800a46be57b8008e951183d4dcc64409","tarball":"https://registry.npmjs.org/402ok-mcp/-/402ok-mcp-0.1.4.tgz","fileCount":22,"unpackedSize":56621,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIFde7KzVwWLV489FfMNEOYlSJexBMyCH6fQfnIFTv5GxAiEAk4st5RkiZnnnyRFzm9Bsdw7peeTlZ1ceh53F4GjvmlE="}]},"_npmUser":{"name":"kinhunt","email":"kinhunt@gmail.com"},"directories":{},"maintainers":[{"name":"kinhunt","email":"kinhunt@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/402ok-mcp_0.1.4_1764978644707_0.40213902666606094"},"_hasShrinkwrap":false}},"time":{"created":"2025-12-04T09:17:14.260Z","modified":"2025-12-05T23:50:45.056Z","0.1.0":"2025-12-04T09:17:14.488Z","0.1.1":"2025-12-05T23:25:40.109Z","0.1.2":"2025-12-05T23:44:55.709Z","0.1.3":"2025-12-05T23:47:27.045Z","0.1.4":"2025-12-05T23:50:44.862Z"},"bugs":{"url":"https://github.com/payincom/402ok-mcp/issues"},"license":"MIT","homepage":"https://github.com/payincom/402ok-mcp#readme","keywords":["http-402","payment","mcp","middleware","x402","okx","xlayer","blockchain"],"repository":{"type":"git","url":"git+https://github.com/payincom/402ok-mcp.git"},"description":"MCP server middleware for HTTP 402 Payment Required with support for multiple networks including OKX/XLayer","maintainers":[{"name":"kinhunt","email":"kinhunt@gmail.com"}],"readme":"# 402ok-mcp\n\nMCP (Model Context Protocol) server middleware for HTTP 402 Payment Required protocol with **XLayer-compatible** multi-network blockchain payment support.\n\n## Features\n\n- 🔥 **XLayer Compatible** - Full support for OKX XLayer network with native facilitator integration\n- ✅ **HTTP 402 Payment Required** - Standard implementation of the x402 protocol for MCP\n- 🌐 **Multi-Network Support** - XLayer, Base, Base Sepolia, and any EVM-compatible networks\n- 🔐 **OKX Facilitator** - Built-in OKX signature authentication for XLayer\n- 🔌 **Standard Facilitator** - Support for x402.org and other standard facilitators\n- 💳 **USDC Payments** - EIP-712 signature-based USDC transfers\n- 🎯 **Paid & Free Tools** - Define both paid and free tools in the same server\n- ⚡ **Complete Lifecycle** - Automatic verify → fulfill → settle flow\n\n## Why XLayer?\n\nXLayer is a Layer 2 blockchain built by OKX, offering:\n- Low transaction fees\n- Fast confirmation times\n- Seamless integration with OKX ecosystem\n- Native USDC support\n\nThis middleware provides **first-class XLayer support** with optimized OKX facilitator integration.\n\n## Installation\n\n```bash\nnpm install 402ok-mcp\n```\n\n## Quick Start\n\n### Pure JSON-RPC HTTP (No SDK Dependency)\n\nMCP is just **JSON-RPC 2.0 over HTTP**. You can build a simple MCP server without `@modelcontextprotocol/sdk`:\n\n```typescript\nimport express from \"express\";\n\nconst app = express();\napp.use(express.json());\n\n// Tool definitions\nconst tools = [\n  {\n    name: \"premium_analysis\",\n    description: \"AI-powered premium analysis\",\n    inputSchema: {\n      type: \"object\",\n      properties: { query: { type: \"string\" } },\n      required: [\"query\"]\n    },\n    price: \"0.01\",  // USDC\n    handler: async (args: any) => `Analysis result for: ${args.query}`\n  }\n];\n\n// JSON-RPC 2.0 handler\napp.post(\"/mcp\", async (req, res) => {\n  const { jsonrpc, method, params, id } = req.body;\n\n  if (jsonrpc !== \"2.0\") {\n    return res.json({ jsonrpc: \"2.0\", error: { code: -32600, message: \"Invalid Request\" }, id });\n  }\n\n  try {\n    let result;\n\n    switch (method) {\n      case \"initialize\":\n        // MCP handshake\n        result = {\n          protocolVersion: \"2024-11-05\",\n          capabilities: { tools: {} },\n          serverInfo: { name: \"paid-mcp-server\", version: \"1.0.0\" }\n        };\n        break;\n\n      case \"tools/list\":\n        // List available tools\n        result = {\n          tools: tools.map(t => ({\n            name: t.name,\n            description: t.description,\n            inputSchema: t.inputSchema\n          }))\n        };\n        break;\n\n      case \"tools/call\":\n        // Call a tool\n        const tool = tools.find(t => t.name === params.name);\n        if (!tool) {\n          throw { code: -32601, message: `Tool not found: ${params.name}` };\n        }\n\n        // Check payment (from _meta)\n        const payment = params._meta?.[\"x402.payment\"];\n\n        if (!payment && tool.price) {\n          // Return 402 payment required\n          result = {\n            isError: true,\n            content: [{\n              type: \"text\",\n              text: JSON.stringify({\n                x402Version: 1,\n                error: \"_meta.x402.payment is required\",\n                accepts: [{\n                  scheme: \"exact\",\n                  network: \"xlayer\",\n                  maxAmountRequired: (parseFloat(tool.price) * 1_000_000).toString(),\n                  payTo: \"0xYourWalletAddress\",\n                  asset: \"0x74b7f16337b8972027f6196a17a631ac6de26d22\",\n                  extra: { name: \"USD Coin\", version: \"2\" }\n                }]\n              })\n            }]\n          };\n        } else {\n          // Execute tool (with payment verification if needed)\n          const output = await tool.handler(params.arguments);\n          result = {\n            content: [{ type: \"text\", text: output }]\n          };\n        }\n        break;\n\n      case \"notifications/initialized\":\n        // Client notification - no response needed\n        return res.status(204).send();\n\n      default:\n        throw { code: -32601, message: `Method not found: ${method}` };\n    }\n\n    res.json({ jsonrpc: \"2.0\", result, id });\n  } catch (error: any) {\n    res.json({\n      jsonrpc: \"2.0\",\n      error: { code: error.code || -32603, message: error.message },\n      id\n    });\n  }\n});\n\napp.listen(3000, () => {\n  console.log(\"Pure JSON-RPC MCP server running on http://localhost:3000/mcp\");\n});\n```\n\n**Key JSON-RPC Methods:**\n\n| Method | Description |\n|--------|-------------|\n| `initialize` | Client handshake, returns server capabilities |\n| `tools/list` | Returns available tools with schemas |\n| `tools/call` | Executes a tool, params include `name`, `arguments`, `_meta` |\n| `notifications/initialized` | Client confirms initialization (no response) |\n\n**Payment Flow via `_meta`:**\n- Payment is passed in `params._meta[\"x402.payment\"]` as base64-encoded JSON\n- If missing, return payment options in the response\n- If present, verify → execute → settle\n\n### Using with SDK (Stdio Transport)\n\n```typescript\nimport { createPaidMcpHandler } from \"402ok-mcp\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { z } from \"zod\";\n\n// Create MCP server with payment support\nconst server = createPaidMcpHandler(\n  (mcp) => {\n    // Define a paid tool\n    mcp.paidTool(\n      \"premium_analysis\",\n      \"Perform premium data analysis\",\n      {\n        payments: [\n          {\n            price: \"0.01\",              // 0.01 USDC\n            chainId: 196,               // XLayer mainnet\n            token: \"0x74b7f16337b8972027f6196a17a631ac6de26d22\", // USDC on XLayer\n            usdcName: \"USD Coin\",\n            usdcVersion: \"2\",\n            network: \"xlayer\",\n            config: {\n              description: \"Premium analysis service\"\n            }\n          }\n        ]\n      },\n      z.object({\n        data: z.string().describe(\"Data to analyze\")\n      }),\n      async (args) => {\n        // Your tool logic here\n        const result = await analyzeData(args.data);\n        return {\n          content: [{ type: \"text\", text: result }]\n        };\n      }\n    );\n\n    // Define a free tool\n    mcp.tool(\n      \"basic_info\",\n      \"Get basic information (free)\",\n      z.object({\n        query: z.string()\n      }),\n      async (args) => {\n        return {\n          content: [{ type: \"text\", text: `Info for: ${args.query}` }]\n        };\n      }\n    );\n  },\n  { name: \"my-paid-mcp-server\", version: \"1.0.0\" },\n  {\n    recipient: \"0xe8fb62154382af0812539cfe61b48321d8f846a8\", // Your wallet\n    facilitators: {\n      xlayer: {\n        url: \"https://www.okx.com\",\n        type: \"okx\",\n        okxCredentials: {\n          apiKey: process.env.OKX_API_KEY!,\n          secretKey: process.env.OKX_SECRET_KEY!,\n          passphrase: process.env.OKX_PASSPHRASE!\n        }\n      }\n    }\n  }\n);\n\n// Connect via stdio transport\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n```\n\n### HTTP Server Mode (StreamableHTTPServerTransport)\n\nDeploy as an HTTP server for web-based MCP clients:\n\n```typescript\nimport express from \"express\";\nimport { randomUUID } from \"node:crypto\";\nimport { createPaidMcpHandler } from \"402ok-mcp\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport { isInitializeRequest } from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\n\nconst app = express();\napp.use(express.json());\n\n// Store active sessions\nconst transports: Record<string, StreamableHTTPServerTransport> = {};\n\n// Server configuration\nconst serverConfig = {\n  recipient: \"0xe8fb62154382af0812539cfe61b48321d8f846a8\",\n  facilitators: {\n    xlayer: {\n      url: \"https://www.okx.com\",\n      type: \"okx\" as const,\n      okxCredentials: {\n        apiKey: process.env.OKX_API_KEY!,\n        secretKey: process.env.OKX_SECRET_KEY!,\n        passphrase: process.env.OKX_PASSPHRASE!\n      }\n    }\n  }\n};\n\n// Tool setup function\nconst setupTools = (mcp: any) => {\n  mcp.paidTool(\n    \"premium_analysis\",\n    \"AI-powered premium analysis\",\n    {\n      payments: [{\n        price: \"0.01\",\n        chainId: 196,\n        token: \"0x74b7f16337b8972027f6196a17a631ac6de26d22\",\n        usdcName: \"USD Coin\",\n        usdcVersion: \"2\",\n        network: \"xlayer\",\n        config: { description: \"Premium AI analysis\" }\n      }]\n    },\n    z.object({ query: z.string() }),\n    async (args) => {\n      return { content: [{ type: \"text\", text: `Analysis: ${args.query}` }] };\n    }\n  );\n};\n\n// Handle MCP requests\napp.post(\"/mcp\", async (req, res) => {\n  const sessionId = req.headers[\"mcp-session-id\"] as string | undefined;\n  let transport: StreamableHTTPServerTransport;\n\n  if (sessionId && transports[sessionId]) {\n    // Reuse existing session\n    transport = transports[sessionId];\n  } else if (!sessionId && isInitializeRequest(req.body)) {\n    // New session initialization\n    transport = new StreamableHTTPServerTransport({\n      sessionIdGenerator: () => randomUUID(),\n      onsessioninitialized: (id) => {\n        transports[id] = transport;\n        console.log(\"Session initialized:\", id);\n      },\n      onsessionclosed: (id) => {\n        delete transports[id];\n        console.log(\"Session closed:\", id);\n      }\n    });\n\n    transport.onclose = () => {\n      if (transport.sessionId) {\n        delete transports[transport.sessionId];\n      }\n    };\n\n    // Create paid MCP server and connect\n    const server = createPaidMcpHandler(\n      setupTools,\n      { name: \"paid-mcp-http-server\", version: \"1.0.0\" },\n      serverConfig\n    );\n    await server.connect(transport);\n  } else {\n    res.status(400).json({\n      jsonrpc: \"2.0\",\n      error: { code: -32000, message: \"Invalid session\" },\n      id: null\n    });\n    return;\n  }\n\n  await transport.handleRequest(req, res, req.body);\n});\n\n// Handle SSE for streaming responses\napp.get(\"/mcp\", async (req, res) => {\n  const sessionId = req.headers[\"mcp-session-id\"] as string;\n  const transport = transports[sessionId];\n  if (transport) {\n    await transport.handleRequest(req, res);\n  } else {\n    res.status(400).send(\"Invalid session\");\n  }\n});\n\n// Handle session cleanup\napp.delete(\"/mcp\", async (req, res) => {\n  const sessionId = req.headers[\"mcp-session-id\"] as string;\n  const transport = transports[sessionId];\n  if (transport) {\n    await transport.handleRequest(req, res);\n  } else {\n    res.status(400).send(\"Invalid session\");\n  }\n});\n\napp.listen(3000, () => {\n  console.log(\"Paid MCP HTTP server running on http://localhost:3000/mcp\");\n});\n```\n\n### Stateless HTTP Mode\n\nFor serverless/edge deployments, use stateless mode:\n\n```typescript\nconst transport = new StreamableHTTPServerTransport({\n  sessionIdGenerator: undefined  // Disable session management\n});\n```\n\n### Multi-Network Setup\n\nAllow users to pay with XLayer OR Base Sepolia:\n\n```typescript\nconst server = createPaidMcpHandler(\n  (mcp) => {\n    mcp.paidTool(\n      \"premium_service\",\n      \"Premium service with multi-network payment\",\n      {\n        payments: [\n          // Option 1: XLayer (recommended for lower fees)\n          {\n            price: \"0.1\",\n            chainId: 196,\n            token: \"0x74b7f16337b8972027f6196a17a631ac6de26d22\",\n            usdcName: \"USD Coin\",\n            usdcVersion: \"2\",\n            network: \"xlayer\",\n            config: {\n              description: \"Pay with XLayer (lower fees)\"\n            }\n          },\n          // Option 2: Base Sepolia\n          {\n            price: \"0.1\",\n            chainId: 84532,\n            token: \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n            usdcName: \"USDC\",\n            usdcVersion: \"2\",\n            network: \"base-sepolia\",\n            config: {\n              description: \"Pay with Base Sepolia\"\n            }\n          }\n        ]\n      },\n      z.object({ input: z.string() }),\n      async (args) => {\n        return { content: [{ type: \"text\", text: \"Result\" }] };\n      }\n    );\n  },\n  { name: \"multi-network-server\", version: \"1.0.0\" },\n  {\n    recipient: \"0xe8fb62154382af0812539cfe61b48321d8f846a8\",\n    facilitators: {\n      xlayer: {\n        url: \"https://www.okx.com\",\n        type: \"okx\",\n        okxCredentials: {\n          apiKey: process.env.OKX_API_KEY!,\n          secretKey: process.env.OKX_SECRET_KEY!,\n          passphrase: process.env.OKX_PASSPHRASE!\n        }\n      },\n      \"base-sepolia\": {\n        url: \"https://x402.org/facilitator\",\n        type: \"standard\"\n      }\n    }\n  }\n);\n```\n\n## How It Works\n\n1. **Client calls MCP tool** → Server checks if tool requires payment\n2. **No payment provided** → Returns error with payment options (x402 format)\n3. **Client signs payment** → Creates EIP-712 signature for USDC transfer\n4. **Client retries with `_meta.x402.payment`** → Includes signed payment\n5. **Server verifies payment** → Calls facilitator to verify signature\n6. **Server executes tool** → Runs your tool logic\n7. **Server settles payment** → Calls facilitator to execute on-chain transfer\n8. **Server returns result** → Includes settlement confirmation in `_meta`\n\nAll of this happens automatically!\n\n## API Reference\n\n### `createPaidMcpHandler(setupTools, serverInfo, config)`\n\nCreates an MCP server with payment support.\n\n#### Parameters\n\n- **setupTools** `(server: PaidMcpServer) => void` - Function to register tools\n- **serverInfo** `{ name: string; version: string }` - Server metadata\n- **config** `ServerConfig` - Server configuration\n\n#### Types\n\n```typescript\ninterface PaymentConfig {\n  price: string;           // Price in USDC (e.g., \"0.1\")\n  chainId: number;         // Network chain ID\n  token: string;           // USDC token contract address\n  usdcName: string;        // USDC contract name (for EIP-712)\n  usdcVersion: string;     // USDC contract version (for EIP-712)\n  network: string;         // Network name (e.g., \"xlayer\")\n  config?: {\n    description?: string;\n    metadata?: Record<string, any>;\n  };\n}\n\ninterface ServerConfig {\n  recipient: string;       // Wallet address to receive payments\n  facilitators: {\n    [network: string]: FacilitatorConfig;\n  };\n}\n\ninterface FacilitatorConfig {\n  url: string;\n  type?: \"okx\" | \"standard\";\n  okxCredentials?: {\n    apiKey: string;\n    secretKey: string;\n    passphrase: string;\n  };\n}\n```\n\n### PaidMcpServer Methods\n\n#### `paidTool(name, description, paymentOptions, paramsSchema, callback)`\n\nRegister a paid tool that requires payment before execution.\n\n#### `tool(name, description, paramsSchema, callback)`\n\nRegister a free tool (no payment required).\n\n## Supported Networks\n\n### XLayer (Recommended)\n- **Mainnet**: Chain ID `196`\n- **Testnet**: Chain ID `195`\n- **USDC Contract**: `0x74b7f16337b8972027f6196a17a631ac6de26d22` (mainnet)\n- **Facilitator**: OKX facilitator with API authentication\n\n### Other Networks\n- **Base**: Standard facilitator\n- **Base Sepolia**: Standard facilitator\n- **Any EVM-compatible network** with USDC support\n\n## Getting OKX Credentials\n\nTo use XLayer with OKX facilitator:\n\n1. Create an OKX account at https://www.okx.com\n2. Go to API settings\n3. Create API key with x402 permissions\n4. Copy API Key, Secret Key, and Passphrase to your `.env`:\n\n```env\nOKX_API_KEY=your_api_key\nOKX_SECRET_KEY=your_secret_key\nOKX_PASSPHRASE=your_passphrase\n```\n\n## Client Integration\n\nMCP clients need to handle the x402 payment flow. When a tool returns an error with payment options:\n\n```typescript\n// Example handling payment in an MCP client\nconst result = await mcpClient.callTool(\"premium_analysis\", { data: \"...\" });\n\nif (result.isError) {\n  const errorData = JSON.parse(result.content[0].text);\n\n  if (errorData.error === \"_meta.x402.payment is required\") {\n    // Get payment options\n    const paymentOptions = errorData.accepts;\n\n    // User signs payment with their wallet\n    const signedPayment = await signPayment(paymentOptions[0]);\n\n    // Retry with payment\n    const paidResult = await mcpClient.callTool(\n      \"premium_analysis\",\n      { data: \"...\" },\n      { _meta: { \"x402.payment\": signedPayment } }\n    );\n  }\n}\n```\n\n## Security\n\n- EIP-712 signature verification for all payments\n- Facilitator double-verification (verify + settle)\n- No direct blockchain access required\n- Automatic payment settlement on successful tool execution only\n- Failed tool execution = no payment settlement\n\n## License\n\nMIT\n\n## Links\n\n- [XLayer Official Site](https://www.okx.com/xlayer)\n- [x402 Protocol](https://x402.org)\n- [MCP Protocol](https://modelcontextprotocol.io)\n- [GitHub Repository](https://github.com/payincom/402ok-mcp)\n","readmeFilename":"README.md"}