How to Add Analytics & Payments to Your Cloudflare MCP Servers
July 7, 2025 
Imagine knowing which of your MCP tools are most popular, identifying performance bottlenecks before they impact user experience, or tracking revenue from premium features with minimal effort. This guide will walk you through seamlessly integrating powerful analytics and even payments into your Cloudflare Model Context Protocol (MCP) servers.
🔍 What are Cloudflare MCP Servers?
Cloudflare allows you to build and deploy Model Context Protocol (MCP) servers. The Model Context Protocol is an open standard designed to connect AI systems with external applications. In this framework:
- MCP Hosts are AI assistants or applications that require external capabilities
- MCP Clients are embedded within these hosts, connecting to MCP servers and invoking tools
- MCP Servers are the applications that expose various functionalities, known as “tools”
// Basic MCP Server Structure
import { McpAgent } from '@cloudflare/agents';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
export class BasicMCP extends McpAgent {
server = new McpServer({
name: 'My MCP Server',
version: '1.0.0'
});
async init() {
this.server.tool('example', 'Example tool', schema, handler);
}
}
Cloudflare MCP servers typically operate as remote MCP connections, meaning MCP clients connect over the Internet using HTTP and Server-Sent Events (SSE), or the newer Streamable HTTP, and authorize access using OAuth.
📊 Why Analytics for Your MCP Servers?
While building robust MCP tools is crucial, understanding their real-world usage provides invaluable feedback. Standard Cloudflare MCP Agents do not inherently provide analytics tracking, user tracking, performance metrics, or error tracking.
Without these insights, you’re operating in the dark about:
- User Behavior - Which tools are users actually engaging with?
- Performance Bottlenecks - Are certain tools slow?
- Error Monitoring - When tools fail, why do they fail?
- Monetization - How do you track payments and revenue effectively?
🚀 Introducing mcp-analytics
The mcp-analytics SDK is specifically designed for Cloudflare MCP Agents, allowing you to add powerful analytics tracking and Stripe payments to your MCP servers with minimal code changes.
Key Features (for all tools, free and paid):
The mcp analytics sdk SDK tracks several key metrics for all your tools, regardless of whether they’re free or paid. This includes:
-
Tool Execution Time: Precisely measures how long each tool takes to execute, helping you identify performance bottlenecks.
-
Success/Failure Status: Records whether each tool call completed successfully or resulted in an error. This provides a clear picture of tool reliability.
-
Input Parameters: Captures the input parameters used in each tool call. Sensitive data is automatically redacted to protect user privacy.
-
Error Details: Provides comprehensive details about any errors encountered during tool execution, aiding in debugging and error resolution.
-
User Tracking: Automatically identifies users via OAuth, enabling you to analyze usage patterns on a per-user basis.
-
Session Tracking: Groups related tool calls within a single user session, providing context to usage patterns.
Additional for Paid Tools:
- Payment events - Records payment lifecycle
- Revenue tracking - Track income by tool and user
- Subscription management - Monitor active subscriptions
- Usage-based billing - Support for metered billing
🛠️ Implementation Guide
Step 1: Installation
npm install mcp-analytics
Step 2: Choose Your Agent Type
You’ll replace the standard McpAgent
class with either:
AnalyticsMcpAgent
- For free tools with analyticsAnalyticsPaidMcpAgent
- For free + paid tools with analytics and payments
Option A: Analytics Only (Free Tools)
import { AnalyticsMcpAgent } from 'mcp-analytics';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
export class MyMCP extends AnalyticsMcpAgent {
server = new McpServer({
name: 'My Analytics-Only MCP',
version: '1.0.0'
});
async init() {
// Replace this.server.tool() with this.analyticsTool()
this.analyticsTool(
'add',
'Add two numbers',
{ a: z.number(), b: z.number() },
async ({ a, b }) => ({
content: [{ type: 'text', text: `Result: ${a + b}` }],
})
);
}
}
Option B: Analytics + Payments (Free + Paid Tools)
import { AnalyticsPaidMcpAgent } from 'mcp-analytics';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
export class MyMCP extends AnalyticsPaidMcpAgent {
server = new McpServer({
name: 'My Analytics + Payments MCP',
version: '1.0.0'
});
async init() {
// Free tool with analytics
this.analyticsTool(
'add',
'Add two numbers',
{ a: z.number(), b: z.number() },
async ({ a, b }) => ({
content: [{ type: 'text', text: `Result: ${a + b}` }],
})
);
// Paid tool with analytics + payments
this.analyticsPaidTool(
'generate_image',
'Generate AI image with premium quality',
{ prompt: z.string() },
async ({ prompt }) => ({
content: [{ type: 'text', text: `Generated image for: ${prompt}` }],
}),
{
checkout: {
success_url: 'https://yoursite.com/success',
line_items: [{ price: 'price_123', quantity: 1 }],
mode: 'payment',
},
paymentReason: 'High-quality AI image generation',
}
);
// Usage-based billing example
this.analyticsPaidTool(
'api_call',
'Make API call with usage-based billing',
{ endpoint: z.string() },
async ({ endpoint }) => ({
content: [{ type: 'text', text: 'API response' }],
}),
{
checkout: {
success_url: 'https://yoursite.com/success',
line_items: [{ price: 'price_usage_123' }],
mode: 'subscription',
},
meterEvent: 'api_call',
paymentReason: 'Pay per API call',
}
);
}
}
Step 3: Configure Environment Variables
Set up the required environment variables:
# Required for analytics
MCP_ANALYTICS_API_KEY=your_analytics_key
# Required for paid tools
STRIPE_SECRET_KEY=your_stripe_key
# Optional
MCP_ANALYTICS_ENABLED=true
ENVIRONMENT=production
For local development (.dev.vars
file):
MCP_ANALYTICS_API_KEY=dev_analytics_key
STRIPE_SECRET_KEY=sk_test_...
ENVIRONMENT=development
For production deployment:
wrangler secret put MCP_ANALYTICS_API_KEY
wrangler secret put STRIPE_SECRET_KEY
🔒 Data Privacy and Security
The mcp-analytics SDK prioritizes data privacy and security:
Automatic Data Sanitization
Sensitive input parameters are automatically redacted:
// These fields are automatically sanitized:
const sensitiveFields = [
'password', 'apiKey', 'creditCard', 'ssn',
'token', 'secret', 'private', 'auth'
];
Disable Result Tracking for Sensitive Tools
// Sensitive tool - disable result tracking for privacy
this.analyticsTool(
'processDocument',
'Process sensitive document',
schema,
callback,
{ trackResults: false } // Tool calls tracked, results ignored
);
📈 Analytics Dashboard Features
Real-time Metrics:
- Tool usage frequency and performance
- Error rates and failure patterns
- User engagement analytics
- Revenue tracking and conversion rates
- Payment success/failure monitoring
Performance Insights:
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Tool Usage │ │ Performance │ │ Revenue │
│ │ │ │ │ │
│ • Call count │ │ • Execution time │ │ • Total revenue │
│ • Success rate │ │ • Error rate │ │ • Conversion │
│ • User patterns │ │ • Bottlenecks │ │ • Subscriptions │
└─────────────────┘ └──────────────────┘ └─────────────────┘
💰 Monetization Strategies
One-time Payments
Perfect for premium features or AI-generated content:
{
checkout: {
success_url: 'https://yoursite.com/success',
line_items: [{ price: 'price_123', quantity: 1 }],
mode: 'payment', // One-time payment
},
paymentReason: 'Premium AI image generation',
}
Subscription Billing
Ideal for ongoing services:
{
checkout: {
success_url: 'https://yoursite.com/success',
line_items: [{ price: 'price_monthly_123' }],
mode: 'subscription',
},
paymentReason: 'Monthly premium access',
}
Usage-based Billing
Perfect for API calls or compute-intensive tools:
{
checkout: {
line_items: [{ price: 'price_usage_123' }],
mode: 'subscription',
},
meterEvent: 'api_call', // Records usage for billing
paymentReason: 'Pay per API call',
}
🎯 Benefits Overview
For Developers
✅ Minimal Code Changes - Only two imports needed
✅ Full Type Safety - Complete TypeScript support
✅ Automatic Detection - Server details detected automatically
✅ OAuth Integration - Works with any OAuth provider
✅ Zero Custom Code - Stripe integration built-in
For Business
✅ User Behavior Analysis - Understand tool popularity
✅ Performance Optimization - Identify bottlenecks
✅ Revenue Analytics - Track income by tool
✅ Payment Insights - Monitor conversion rates
✅ Error Reduction - Proactive issue identification
🛡️ Best Practices
Implementation Tips:
- Use
AnalyticsPaidMcpAgent
for flexibility - Even for free-only tools - Add descriptive information - Clear tool names and descriptions
- Secure environment variables - Use Cloudflare Workers secrets
- Thoughtful result tracking - Disable for sensitive/large data
- Match billing to usage - One-time vs subscription vs usage-based
Security Considerations:
// Example: Disable tracking for sensitive tools
this.analyticsTool(
'decrypt_data',
'Decrypt sensitive data',
schema,
handler,
{ trackResults: false } // Keep results private
);
🔮 Real-world Use Cases
AI Content Generation:
- Image generation ($2 per image)
- Text generation (subscription-based)
- Code generation (usage-based)
API Services:
- External API calls (pay-per-use)
- Data processing (tiered pricing)
- ML model inference (compute-based)
Premium Features:
- Advanced analytics access
- Priority processing
- Custom integrations
📊 Cost Analysis
Choosing the right billing model depends on your tools and how users interact with them. Here’s a breakdown:
One-time Payments: Ideal for premium features or individual purchases. Examples include generating a single high-resolution image or creating a custom report.
Subscription Billing: Best suited for ongoing access to tools or features. Think of API quotas, access to premium toolsets, or continuous data processing.
Usage-based Billing: Perfect for tools where usage varies greatly. This works well for API calls, compute-intensive tasks, or any service where the cost is directly tied to the amount of resources consumed.
🚀 Getting Started Checklist
- Install
mcp-analytics
package - Choose agent type (
AnalyticsMcpAgent
orAnalyticsPaidMcpAgent
) - Replace
this.server.tool()
withthis.analyticsTool()
- Set up environment variables
- Configure Stripe prices (for paid tools)
- Deploy and monitor analytics dashboard
Ready to supercharge your MCP servers with analytics and payments? The Mcp analytics makes it effortless to gain insights and monetize your AI tools while maintaining the performance and security your users expect.