Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
20 changes: 20 additions & 0 deletions examples/production-starter-kit/.env.example
Original file line number Diff line number Diff line change
@@ -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
126 changes: 126 additions & 0 deletions examples/production-starter-kit/README.md
Original file line number Diff line number Diff line change
@@ -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 &rarr; paywall hit &rarr; simulated checkout top-up &rarr; 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)
88 changes: 88 additions & 0 deletions examples/production-starter-kit/client-demo.ts
Original file line number Diff line number Diff line change
@@ -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);
21 changes: 21 additions & 0 deletions examples/production-starter-kit/package.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
Loading
Loading