diff --git a/README.md b/README.md index 02d336f..f63626b 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,23 @@ server.tool( --- +## šŸ“¦ 1-Click Production Starter Kit + +Looking for a complete, runnable production MCP server with token-bucket rate limiting, SQLite persistence, and Dodo Payments / Stripe webhook listener? + +Check out [`examples/production-starter-kit/`](examples/production-starter-kit/): +- **`server.ts`**: Metered tools (`financial_report`, `semantic_search`, `ping`) with burst rate limiting and PASETO capability tokens. +- **`webhook-server.ts`**: HTTP webhook listener on port 4001 fulfilling customer credits upon payment. +- **`client-demo.ts`**: Interactive script simulating free calls, paywall trigger, and webhook fulfillment. + +```bash +cd examples/production-starter-kit +npm install +npm run demo +``` + +--- + ## šŸ–¼ļø How the Agent Sees the Paywall When a user in **Claude Desktop**, **Cursor**, or **Windsurf** exhausts their free calls, the agent automatically receives structured markdown prompting the user to top up: diff --git a/examples/production-starter-kit/.env.example b/examples/production-starter-kit/.env.example new file mode 100644 index 0000000..1de9d58 --- /dev/null +++ b/examples/production-starter-kit/.env.example @@ -0,0 +1,20 @@ +# MCP Monetize Production Configuration +MCP_MONETIZE_SECRET=fedcba9876543210fedcba9876543210fedcba9876543210 +MCP_MONETIZE_SQLITE_PATH=./starter_credits.db + +# Live Dodo Payments Credentials +DODO_API_KEY=dodo_live_tIUdfp0CcT-iNZYv.fK0CHP61dzsrp7hEgZxuGYwdMXLbaT7lJreqCf2mDph9NwBQ +DODO_WEBHOOK_SECRET=whsec_sample_secret_replace_with_live +DODO_PRODUCT_ID=pdt_0NrFWlIkkreo5fOBIJWxI +DODO_CHECKOUT_URL=https://checkout.dodopayments.com/buy/pdt_0NrFWlIkkreo5fOBIJWxI + +# Stripe Credentials (Optional) +STRIPE_SECRET_KEY=sk_live_... +STRIPE_WEBHOOK_SECRET=whsec_... + +# Quota & Pricing +FREE_TIER_CALLS=5 +PRICE_LABEL=$5 for 500 requests + +# Webhook Server Port +WEBHOOK_PORT=4001 diff --git a/examples/production-starter-kit/README.md b/examples/production-starter-kit/README.md new file mode 100644 index 0000000..e50c47f --- /dev/null +++ b/examples/production-starter-kit/README.md @@ -0,0 +1,126 @@ +# šŸš€ Production MCP Server Monetization Starter Kit + +> Turn any Model Context Protocol (MCP) server into a paid, rate-limited commercial API in under 5 minutes using `@ritualdev-lab/mcp-monetize`, **Dodo Payments**, and **Stripe**. + +--- + +## ⚔ What's Inside + +| Feature | Description | +| :--- | :--- | +| **šŸ›”ļø Token-Bucket Rate Limiting** | Prevents burst hammering and agent loops with in-memory token buckets (10 burst, 2 refills/sec). | +| **šŸŽ Free Quota Tier** | Allows every new user 5 complimentary requests before requiring paid credit activation. | +| **šŸ’³ Dodo Payments Checkout** | Drop-in hosted checkout links attached to the user's `customer_id` / `userId`. | +| **⚔ Instant Webhook Engine** | Dedicated `webhook-server.ts` listening for `payment.succeeded` and `subscription.active` events with HMAC verification. | +| **šŸ’¾ Persistent SQLite Storage** | Zero-dependency credit store using Node.js built-in `node:sqlite` (`starter_credits.db`). | +| **šŸ”‘ PASETO Capability Tokens** | Sub-millisecond (< 0.2ms) offline cryptographic capability token verification for high-throughput agents. | +| **šŸ”Œ Claude Desktop & Cursor Ready** | Exposes standard JSON-RPC 2.0 stdio transport compatible with Claude Desktop, Cursor, and Windsurf. | + +--- + +## šŸš€ Quickstart in 60 Seconds + +### 1. Install Dependencies +```bash +npm install +``` + +### 2. Configure Environment Variables +Copy the example configuration: +```bash +cp .env.example .env +``` + +Set your live Dodo Payments API key and product ID: +```env +MCP_MONETIZE_SECRET=fedcba9876543210fedcba9876543210fedcba9876543210 +MCP_MONETIZE_SQLITE_PATH=./starter_credits.db +DODO_PRODUCT_ID=pdt_0NrFWlIkkreo5fOBIJWxI +DODO_CHECKOUT_URL=https://checkout.dodopayments.com/buy/pdt_0NrFWlIkkreo5fOBIJWxI +FREE_TIER_CALLS=5 +PRICE_LABEL=$5 for 500 requests +``` + +### 3. Run the End-to-End Simulation +Test the full lifecycle (free calls → paywall hit → simulated checkout top-up → resumed execution): +```bash +npm run demo +``` + +### 4. Run Unit Tests +```bash +npm test +``` + +--- + +## šŸ› ļø How to Monetize Your Own MCP Tools + +Wrap your existing tool handler with `withMcpMonetization`: + +```typescript +import { withMcpMonetization, SqliteTokenStore } from "@ritualdev-lab/mcp-monetize"; + +const store = new SqliteTokenStore("./credits.db", 5); // 5 free calls + +// Your existing MCP tool handler +const rawToolHandler = async (args: { query: string }) => { + return { + content: [{ type: "text", text: `Results for: ${args.query}` }] + }; +}; + +// Monetized handler with Dodo Payments checkout +export const monetizedTool = withMcpMonetization(rawToolHandler, { + provider: "dodo", + checkoutUrl: (userId) => + `https://checkout.dodopayments.com/buy/pdt_YOUR_PRODUCT_ID?customer_id=${encodeURIComponent(userId)}&quantity=1`, + priceLabel: "$5 for 500 calls", + freeTierCalls: 5, + store +}); +``` + +--- + +## 🌐 Running the Background Webhook Listener + +To automatically fulfill credits when customers pay: + +```bash +npm run webhook +``` + +Exposes: +- `POST http://localhost:4001/webhooks/dodo` (configured in Dodo Payments Dashboard) +- `POST http://localhost:4001/webhooks/stripe` (configured in Stripe Dashboard) +- `GET http://localhost:4001/credits/:userId` (inspect current credit balance) + +--- + +## šŸ’» Claude Desktop & Cursor Integration + +Add to your `claude_desktop_config.json`: + +```json +{ + "mcpServers": { + "monetized-starter": { + "command": "npx", + "args": [ + "-y", + "tsx", + "/absolute/path/to/examples/production-starter-kit/server.ts" + ], + "env": { + "MCP_MONETIZE_SQLITE_PATH": "/absolute/path/to/starter_credits.db" + } + } + } +} +``` + +--- + +## šŸ“„ License +Apache-2.0 Ā© [RitualDev Lab](https://ritualdev.in) diff --git a/examples/production-starter-kit/client-demo.ts b/examples/production-starter-kit/client-demo.ts new file mode 100644 index 0000000..d0c132c --- /dev/null +++ b/examples/production-starter-kit/client-demo.ts @@ -0,0 +1,88 @@ +/** + * Interactive Demonstration of MCP Tool Monetization + * + * Runs through the complete monetization lifecycle: + * 1. Free tier calls (1 to 5) succeed seamlessly. + * 2. 6th call triggers the paywall with Dodo checkout redirect. + * 3. Simulates customer checkout and webhook top-up. + * 4. 7th call resumes using paid credits. + */ + +import { createMonetizedMcpServer } from "./server.js"; +import { PaymentWebhookHandler } from "../../src/webhooks.js"; +import * as crypto from "node:crypto"; + +async function runDemo() { + console.log("================================================================="); + console.log("šŸš€ MCP Monetize Starter Kit: Live End-to-End Monetization Demo"); + console.log("=================================================================\n"); + + const server = createMonetizedMcpServer({ + freeTierCalls: 3, // Set to 3 for quick demo + dodoCheckoutUrl: "https://checkout.dodopayments.com/buy/pdt_0NrFWlIkkreo5fOBIJWxI", + priceLabel: "$5 for 500 reports" + }); + + const userId = "dev_sarah_99"; + const tickerSymbols = ["AAPL", "NVDA", "MSFT", "AMZN"]; + + console.log(`šŸ‘¤ User: ${userId} (Allocated: 3 complimentary free-tier reports)\n`); + + // Step 1: Free Tier Calls + for (let i = 0; i < 3; i++) { + const ticker = tickerSymbols[i]; + console.log(`--- [Call #${i + 1}] Requesting Financial Analysis for ${ticker} ---`); + const res = await server.dispatchToolCall("financial_report", { ticker, userId }); + console.log(res.content[0].text); + console.log(); + } + + // Step 2: Quota Exhausted Call (Paywall Trigger) + console.log(`--- [Call #4] Requesting Financial Analysis for ${tickerSymbols[3]} (Quota Exhausted) ---`); + const paywallRes = await server.dispatchToolCall("financial_report", { ticker: tickerSymbols[3], userId }); + console.log(paywallRes.content[0].text); + console.log(); + + // Step 3: Webhook Top-Up Simulation + console.log("šŸ’³ >>> Customer completes checkout on Dodo Payments ($5) <<<"); + const webhookSecret = "whsec_demo_secret_key"; + const webhookHandler = new PaymentWebhookHandler({ + store: server.store, + dodoWebhookSecret: webhookSecret + }); + + const webhookPayload = { + type: "payment.succeeded", + data: { + payment_id: `pay_${Date.now()}`, + status: "succeeded", + amount: 500, + currency: "USD", + customer: { + customer_id: userId, + email: "sarah@example.com" + }, + metadata: { + userId, + credits: 500 + } + } + }; + + const rawBody = JSON.stringify(webhookPayload); + const sig = crypto.createHmac("sha256", webhookSecret).update(rawBody).digest("hex"); + const webhookResult = await webhookHandler.handleDodoWebhook(webhookPayload, sig, rawBody); + + console.log(`āœ… Webhook Fulfillment: Added ${webhookResult.creditsAdded} credits to ${userId}.\n`); + + // Step 4: Resume Execution with Paid Credits + console.log(`--- [Call #5] Requesting Financial Analysis for ${tickerSymbols[3]} (With Paid Credits) ---`); + const paidRes = await server.dispatchToolCall("financial_report", { ticker: tickerSymbols[3], userId }); + console.log(paidRes.content[0].text); + + const status = server.store.getUser(userId); + console.log(`\nšŸŽ‰ Balance: ${status.paidCredits} paid credits remaining | Total calls made: ${status.totalCallsMade}`); + console.log("=================================================================\n"); +} + +runDemo().catch(console.error); diff --git a/examples/production-starter-kit/package.json b/examples/production-starter-kit/package.json new file mode 100644 index 0000000..6acce3b --- /dev/null +++ b/examples/production-starter-kit/package.json @@ -0,0 +1,21 @@ +{ + "name": "mcp-monetize-starter-kit", + "version": "1.0.0", + "description": "Production 1-Click Starter Kit: Turn any Model Context Protocol (MCP) server into a paid API with token-bucket rate limiting and Dodo Payments / Stripe checkout", + "type": "module", + "main": "server.ts", + "scripts": { + "start": "tsx server.ts", + "webhook": "tsx webhook-server.ts", + "demo": "tsx client-demo.ts", + "test": "tsx test.ts" + }, + "dependencies": { + "@ritualdev-lab/mcp-monetize": "^0.1.3" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "tsx": "^4.19.3", + "typescript": "^5.6.0" + } +} diff --git a/examples/production-starter-kit/server.ts b/examples/production-starter-kit/server.ts new file mode 100644 index 0000000..c974a8b --- /dev/null +++ b/examples/production-starter-kit/server.ts @@ -0,0 +1,283 @@ +/** + * Production MCP Server with Paywalls, Rate Limiting & Dodo/Stripe Monetization + * + * Exposes metered MCP tools with: + * - Token-Bucket Rate Limiting (prevents abuse / burst hammering) + * - Free Quota Tier (e.g. 5 complimentary calls) + * - Automated JSON-RPC Paywall with Checkout Redirects + * - Offline PASETO Capability Token validation (< 0.2ms) + * - Persistent SQLite storage (starter_credits.db) + */ + +import * as readline from "node:readline"; +import { withMcpMonetization } from "../../src/middleware.js"; +import { SqliteTokenStore } from "../../src/adapters/sqlite.js"; +import { MemoryTokenStore } from "../../src/store.js"; +import { McpCapabilityTokenManager } from "../../src/capability.js"; +import type { TokenStore, McpToolCallResult } from "../../src/types.js"; + +// 1. Token-Bucket Rate Limiter Configuration +export class TokenBucketRateLimiter { + private buckets: Map = new Map(); + + constructor( + private capacity: number = 10, + private refillRatePerSecond: number = 2 + ) {} + + public consume(key: string, tokens = 1): { allowed: boolean; remaining: number } { + const now = Date.now(); + let bucket = this.buckets.get(key); + + if (!bucket) { + bucket = { tokens: this.capacity, lastRefill: now }; + this.buckets.set(key, bucket); + } else { + // Refill tokens based on elapsed time + const elapsedSeconds = (now - bucket.lastRefill) / 1000; + const refilledTokens = elapsedSeconds * this.refillRatePerSecond; + bucket.tokens = Math.min(this.capacity, bucket.tokens + refilledTokens); + bucket.lastRefill = now; + } + + if (bucket.tokens >= tokens) { + bucket.tokens -= tokens; + return { allowed: true, remaining: Math.floor(bucket.tokens) }; + } + + return { allowed: false, remaining: Math.floor(bucket.tokens) }; + } +} + +export interface StarterKitConfig { + dbPath?: string; + freeTierCalls?: number; + dodoCheckoutUrl?: string; + priceLabel?: string; + capabilitySecret?: string; +} + +export function createMonetizedMcpServer(customConfig?: StarterKitConfig) { + const config = { + dbPath: customConfig?.dbPath || process.env.MCP_MONETIZE_SQLITE_PATH || ":memory:", + freeTierCalls: customConfig?.freeTierCalls ?? Number(process.env.FREE_TIER_CALLS || 5), + dodoCheckoutUrl: + customConfig?.dodoCheckoutUrl || + process.env.DODO_CHECKOUT_URL || + "https://checkout.dodopayments.com/buy/pdt_0NrFWlIkkreo5fOBIJWxI", + priceLabel: customConfig?.priceLabel || process.env.PRICE_LABEL || "$5 for 500 requests", + capabilitySecret: + customConfig?.capabilitySecret || + process.env.MCP_MONETIZE_SECRET || + "fedcba9876543210fedcba9876543210fedcba9876543210" + }; + + // Persistent SQLite Token Store + const store: TokenStore = new SqliteTokenStore(config.dbPath, config.freeTierCalls); + const rateLimiter = new TokenBucketRateLimiter(10, 2); // 10 burst, 2 tokens/sec + const capabilityManager = new McpCapabilityTokenManager(config.capabilitySecret); + + // Raw Tools Implementations + const rawFinancialReport = async (args: { ticker: string; horizonMonths?: number }) => { + return { + content: [ + { + type: "text" as const, + text: `šŸ“Š [PRO REPORT] Financial health assessment for ${args.ticker.toUpperCase()}: +• Runway: 18.4 months +• Operating Margin: +24.8% +• Risk Tier: Low (SOC2 & ISO27001 verified) +• Projection: Positive free cash flow over ${args.horizonMonths || 12} months.` + } + ] + }; + }; + + const rawSemanticSearch = async (args: { query: string; limit?: number }) => { + return { + content: [ + { + type: "text" as const, + text: `šŸ” [SEMANTIC SEARCH] Found ${args.limit || 5} matching vector embeddings for query "${args.query}": +1. Enterprise Authentication & Role-Based Access Control (Score: 0.96) +2. Zero-Leak Sandboxing for Autonomous AI Agents (Score: 0.94) +3. Cryptographic Capability Delegation with PASETO v4 (Score: 0.91)` + } + ] + }; + }; + + // Wrap with MCP Monetization & Rate Limiting + const monetizedFinancialReport = withMcpMonetization( + async (args: any, extra: any) => { + const userId = args.userId || "anonymous"; + const rl = rateLimiter.consume(userId, 2); + if (!rl.allowed) { + return { + content: [ + { + type: "text" as const, + text: `āš ļø Rate limit exceeded. Please wait a few seconds before retrying (Burst capacity: 10, refill: 2/sec).` + } + ], + isError: true + }; + } + return rawFinancialReport(args); + }, + { + provider: "dodo", + checkoutUrl: (userId) => `${config.dodoCheckoutUrl}?customer_id=${encodeURIComponent(userId)}&quantity=1`, + priceLabel: config.priceLabel, + freeTierCalls: config.freeTierCalls, + store, + capabilityManager + } + ); + + const monetizedSemanticSearch = withMcpMonetization( + async (args: any, extra: any) => { + const userId = args.userId || "anonymous"; + const rl = rateLimiter.consume(userId, 1); + if (!rl.allowed) { + return { + content: [ + { + type: "text" as const, + text: `āš ļø Rate limit exceeded. Please wait a few seconds before retrying.` + } + ], + isError: true + }; + } + return rawSemanticSearch(args); + }, + { + provider: "dodo", + checkoutUrl: (userId) => `${config.dodoCheckoutUrl}?customer_id=${encodeURIComponent(userId)}&quantity=1`, + priceLabel: config.priceLabel, + freeTierCalls: config.freeTierCalls, + store, + capabilityManager + } + ); + + // Dispatcher for incoming JSON-RPC or direct execution + const dispatchToolCall = async ( + name: string, + args: Record + ): Promise => { + switch (name) { + case "financial_report": + return monetizedFinancialReport(args, { name: "financial_report" }); + case "semantic_search": + return monetizedSemanticSearch(args, { name: "semantic_search" }); + case "ping": + return { + content: [{ type: "text" as const, text: "pong (free unmetered utility)" }] + }; + default: + return { + content: [{ type: "text" as const, text: `Tool "${name}" not found.` }], + isError: true + }; + } + }; + + const getToolsManifest = () => [ + { + name: "financial_report", + description: "Generates institutional-grade financial analysis. Metered: $5 for 500 reports.", + inputSchema: { + type: "object", + properties: { + ticker: { type: "string", description: "Stock or organization ticker" }, + horizonMonths: { type: "number", description: "Projection horizon in months" }, + userId: { type: "string", description: "User identifier or billing subject" }, + capabilityToken: { type: "string", description: "Optional PASETO capability token" } + }, + required: ["ticker"] + } + }, + { + name: "semantic_search", + description: "Embeddings vector search across technical research. Metered tool.", + inputSchema: { + type: "object", + properties: { + query: { type: "string", description: "Search query" }, + limit: { type: "number", description: "Max results" }, + userId: { type: "string", description: "User identifier or billing subject" } + }, + required: ["query"] + } + }, + { + name: "ping", + description: "Free unmetered connectivity verification.", + inputSchema: { type: "object", properties: {} } + } + ]; + + return { + store, + rateLimiter, + capabilityManager, + dispatchToolCall, + getToolsManifest, + config + }; +} + +// 2. Interactive JSON-RPC Stdio Server Entrypoint +export function startStdioServer() { + const server = createMonetizedMcpServer(); + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + terminal: false + }); + + const sendResponse = (id: any, result: any, error?: any) => { + const payload = error + ? { jsonrpc: "2.0", id, error } + : { jsonrpc: "2.0", id, result }; + process.stdout.write(JSON.stringify(payload) + "\n"); + }; + + rl.on("line", async (line) => { + if (!line.trim()) return; + try { + const msg = JSON.parse(line); + const { id, method, params } = msg; + + if (method === "initialize") { + sendResponse(id, { + protocolVersion: "2024-11-05", + serverInfo: { + name: "mcp-monetize-starter-kit", + version: "1.0.0" + }, + capabilities: { tools: {} } + }); + } else if (method === "tools/list") { + sendResponse(id, { tools: server.getToolsManifest() }); + } else if (method === "tools/call") { + const { name, arguments: toolArgs } = params || {}; + const result = await server.dispatchToolCall(name, toolArgs || {}); + sendResponse(id, result); + } else { + sendResponse(id, null, { code: -32601, message: `Method "${method}" not implemented.` }); + } + } catch (err: any) { + sendResponse(null, null, { code: -32700, message: `Parse error: ${err.message}` }); + } + }); + + console.error("⚔ [mcp-monetize-starter-kit] Stdio JSON-RPC server listening. Connect from Claude Desktop or Cursor."); +} + +// Auto-start when executed directly +if (import.meta.url === `file://${process.argv[1]?.replace(/\\/g, "/")}`) { + startStdioServer(); +} diff --git a/examples/production-starter-kit/test.ts b/examples/production-starter-kit/test.ts new file mode 100644 index 0000000..86e119d --- /dev/null +++ b/examples/production-starter-kit/test.ts @@ -0,0 +1,82 @@ +import { test, describe, before, after } from "node:test"; +import assert from "node:assert"; +import * as crypto from "node:crypto"; +import { createMonetizedMcpServer, TokenBucketRateLimiter } from "./server.js"; +import { createWebhookServer } from "./webhook-server.js"; + +describe("Production MCP Monetize Starter Kit Suite", () => { + test("TokenBucketRateLimiter limits rapid burst calls", () => { + const limiter = new TokenBucketRateLimiter(3, 1); + assert.strictEqual(limiter.consume("user_1", 2).allowed, true); + assert.strictEqual(limiter.consume("user_1", 1).allowed, true); + // Capacity 3 is exhausted + assert.strictEqual(limiter.consume("user_1", 1).allowed, false); + }); + + test("Server provides manifest of all tools", () => { + const server = createMonetizedMcpServer({ freeTierCalls: 2 }); + const manifest = server.getToolsManifest(); + assert.strictEqual(manifest.length, 3); + const names = manifest.map(m => m.name); + assert.ok(names.includes("financial_report")); + assert.ok(names.includes("semantic_search")); + assert.ok(names.includes("ping")); + }); + + test("Executes free tier calls and triggers paywall on exhaustion", async () => { + const server = createMonetizedMcpServer({ freeTierCalls: 2 }); + const userId = "test_user_quota"; + + // Call 1 (Free) + const res1 = await server.dispatchToolCall("financial_report", { ticker: "AAPL", userId }); + assert.ok(res1.content[0].text.includes("[PRO REPORT]")); + assert.strictEqual(res1.isError, undefined); + + // Call 2 (Free) + const res2 = await server.dispatchToolCall("financial_report", { ticker: "MSFT", userId }); + assert.ok(res2.content[0].text.includes("[PRO REPORT]")); + + // Call 3 (Quota Exhausted -> Paywall) + const res3 = await server.dispatchToolCall("financial_report", { ticker: "GOOGL", userId }); + assert.ok(res3.content[0].text.includes("Free Quota Exhausted") || res3.content[0].text.includes("Payment")); + assert.ok(res3.content[0].text.includes("checkout.dodopayments.com")); + }); + + test("Webhook server fulfills Dodo payments and replenishes quota", async () => { + const server = createMonetizedMcpServer({ freeTierCalls: 1 }); + const userId = "test_user_webhook"; + const dodoSecret = "whsec_test_secret_123456789"; + + const { webhookHandler } = createWebhookServer({ + store: server.store, + dodoSecret + }); + + // Exhaust free tier + await server.dispatchToolCall("financial_report", { ticker: "NVDA", userId }); + const blockedRes = await server.dispatchToolCall("financial_report", { ticker: "NVDA", userId }); + assert.ok(blockedRes.content[0].text.includes("checkout.dodopayments.com")); + + // Webhook event + const payload = { + type: "payment.succeeded", + data: { + payment_id: "pay_test_suite_123", + amount: 500, + currency: "USD", + customer: { customer_id: userId }, + metadata: { userId, credits: 50 } + } + }; + const rawBody = JSON.stringify(payload); + const sig = crypto.createHmac("sha256", dodoSecret).update(rawBody).digest("hex"); + + const fulfillment = await webhookHandler.handleDodoWebhook(payload, sig, rawBody); + assert.strictEqual(fulfillment.success, true); + assert.strictEqual(fulfillment.creditsAdded, 50); + + // Resume execution + const allowedRes = await server.dispatchToolCall("financial_report", { ticker: "NVDA", userId }); + assert.ok(allowedRes.content[0].text.includes("[PRO REPORT]")); + }); +}); diff --git a/examples/production-starter-kit/tsconfig.json b/examples/production-starter-kit/tsconfig.json new file mode 100644 index 0000000..5d96ed0 --- /dev/null +++ b/examples/production-starter-kit/tsconfig.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "esModuleInterop": true, + "strict": true, + "skipLibCheck": true + } +} diff --git a/examples/production-starter-kit/webhook-server.ts b/examples/production-starter-kit/webhook-server.ts new file mode 100644 index 0000000..8a8a208 --- /dev/null +++ b/examples/production-starter-kit/webhook-server.ts @@ -0,0 +1,121 @@ +/** + * Dedicated Webhook Fulfillment Server for Dodo Payments & Stripe + * + * Listens for payment notifications, verifies cryptographic signatures, + * and atomically tops up user credits in the shared SQLite database. + */ + +import * as http from "node:http"; +import { PaymentWebhookHandler } from "../../src/webhooks.js"; +import { SqliteTokenStore } from "../../src/adapters/sqlite.js"; +import { McpCapabilityTokenManager } from "../../src/capability.js"; +import type { TokenStore } from "../../src/types.js"; + +const PORT = Number(process.env.WEBHOOK_PORT || 4001); +const SQLITE_PATH = process.env.MCP_MONETIZE_SQLITE_PATH || "./starter_credits.db"; +const DODO_SECRET = process.env.DODO_WEBHOOK_SECRET || "whsec_sample_secret"; +const STRIPE_SECRET = process.env.STRIPE_WEBHOOK_SECRET || "whsec_sample_stripe"; +const CAPABILITY_SECRET = + process.env.MCP_MONETIZE_SECRET || "fedcba9876543210fedcba9876543210fedcba9876543210"; + +export function createWebhookServer(options?: { + store?: TokenStore; + port?: number; + dodoSecret?: string; + stripeSecret?: string; +}) { + const store = options?.store || new SqliteTokenStore(SQLITE_PATH, 5); + const capabilityManager = new McpCapabilityTokenManager(CAPABILITY_SECRET); + + const webhookHandler = new PaymentWebhookHandler({ + store, + dodoWebhookSecret: options?.dodoSecret || DODO_SECRET, + stripeWebhookSecret: options?.stripeSecret || STRIPE_SECRET, + capabilityManager + }); + + const server = http.createServer(async (req, res) => { + const parsedUrl = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`); + const pathname = parsedUrl.pathname; + + const sendJson = (status: number, data: any) => { + res.writeHead(status, { "Content-Type": "application/json" }); + res.end(JSON.stringify(data, null, 2)); + }; + + // Health check + if (pathname === "/health" && req.method === "GET") { + return sendJson(200, { + status: "healthy", + service: "mcp-monetize-webhook-server", + storage: SQLITE_PATH, + endpoints: [ + "POST /webhooks/dodo", + "POST /webhooks/stripe", + "GET /credits/:userId" + ] + }); + } + + // Inspect user credits + if (pathname.startsWith("/credits/") && req.method === "GET") { + const userId = decodeURIComponent(pathname.replace("/credits/", "")); + const user = store.getUser(userId); + return sendJson(200, user); + } + + // Dodo Payments Webhook + if (pathname === "/webhooks/dodo" && req.method === "POST") { + let rawBody = ""; + req.on("data", (chunk) => { rawBody += chunk; }); + req.on("end", async () => { + try { + const sigHeader = + (req.headers["webhook-signature"] as string) || + (req.headers["x-dodo-signature"] as string); + + const payload = JSON.parse(rawBody || "{}"); + const result = await webhookHandler.handleDodoWebhook(payload, sigHeader, rawBody); + + return sendJson(result.success ? 200 : 400, result); + } catch (err: any) { + return sendJson(400, { success: false, error: `Invalid webhook payload: ${err.message}` }); + } + }); + return; + } + + // Stripe Webhook + if (pathname === "/webhooks/stripe" && req.method === "POST") { + let rawBody = ""; + req.on("data", (chunk) => { rawBody += chunk; }); + req.on("end", async () => { + try { + const sigHeader = req.headers["stripe-signature"] as string; + const payload = JSON.parse(rawBody || "{}"); + const result = await webhookHandler.handleStripeWebhook(payload, sigHeader, rawBody); + + return sendJson(result.success ? 200 : 400, result); + } catch (err: any) { + return sendJson(400, { success: false, error: `Invalid webhook payload: ${err.message}` }); + } + }); + return; + } + + return sendJson(404, { error: "Route not found" }); + }); + + return { server, webhookHandler, store }; +} + +// Auto-listen if executed directly +if (import.meta.url === `file://${process.argv[1]?.replace(/\\/g, "/")}`) { + const { server } = createWebhookServer(); + server.listen(PORT, () => { + console.log(`\nšŸ’³ [MCP Monetize Webhook Listener] Online at http://localhost:${PORT}`); + console.log(` Dodo Webhook: http://localhost:${PORT}/webhooks/dodo`); + console.log(` Stripe Webhook: http://localhost:${PORT}/webhooks/stripe`); + console.log(` Health Check: http://localhost:${PORT}/health\n`); + }); +}