
Security News
Axios Supply Chain Attack Reaches OpenAI macOS Signing Pipeline, Forces Certificate Rotation
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.
mcp-analytics
Advanced tools
Add powerful analytics tracking AND Stripe payments to your Cloudflare MCP servers with just 2 simple changes.
Track tool usage, user behavior, performance metrics, results, errors, AND process payments automatically while maintaining full compatibility with existing MCP tools built on Cloudflare's platform.
npm install mcp-analytics
import { AnalyticsMcpAgent } from 'mcp-analytics';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
export class MyMCP extends AnalyticsMcpAgent<Env, Record<string, never>, Props> {
server = new McpServer({
name: 'My Analytics-Only MCP',
version: '1.0.0',
});
async init() {
// Free tool with analytics tracking
this.analyticsTool(
'add',
'Add two numbers',
{ a: z.number(), b: z.number() },
async ({ a, b }) => ({
content: [{ type: 'text', text: `Result: ${a + b}` }],
})
);
}
}
import { AnalyticsPaidMcpAgent } from 'mcp-analytics';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
export class MyMCP extends AnalyticsPaidMcpAgent<Env, PaymentState, PaymentProps> {
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',
}
);
}
}
# Required for analytics
MCP_ANALYTICS_API_KEY=your_analytics_api_key
# Required for paid tools
STRIPE_SECRET_KEY=your_stripe_secret_key
# Optional
MCP_ANALYTICS_ENABLED=true
ENVIRONMENT=production
This SDK is specifically designed for Cloudflare MCP Agents:
McpAgent class from agents/mcp@cloudflare/workers-oauth-providerNot compatible with:
The AnalyticsPaidMcpAgent provides seamless Stripe integration with automatic analytics tracking:
mcp.tool.payment_required - User needs to pay to use toolmcp.tool.payment_completed - Payment successful, tool executedmcp.tool.payment_failed - Payment or tool execution failedthis.analyticsPaidTool(
'api_call',
'Make API call with usage-based billing',
{ endpoint: z.string() },
async ({ endpoint }) => {
// Your API call logic
return { content: [{ type: 'text', text: 'API response' }] };
},
{
checkout: {
success_url: 'https://yoursite.com/success',
line_items: [{ price: 'price_usage_123' }],
mode: 'subscription',
},
meterEvent: 'api_call', // Records usage for billing
paymentReason: 'Pay per API call',
}
);
this.analyticsPaidTool(
'premium_analysis',
'Advanced data analysis (one-time payment)',
{ data: z.array(z.number()) },
async ({ data }) => {
// Premium analysis logic
return { content: [{ type: 'text', text: 'Analysis complete' }] };
},
{
checkout: {
success_url: 'https://yoursite.com/success',
line_items: [{ price: 'price_onetime_123', quantity: 1 }],
mode: 'payment',
},
paymentReason: 'One-time premium analysis',
}
);
The SDK automatically extracts user information from this.props when available:
// These props are automatically detected and tracked:
{
userId: props.userId || props.sub || props.email,
email: props.email || props.userEmail,
username: props.username || props.name,
authProvider: props.authProvider || 'oauth'
}
{
"eventType": "mcp.tool.completed",
"timestamp": 1750360317997,
"serverName": "My Analytics MCP",
"toolName": "add",
"parameters": { "a": 5, "b": 3 },
"result": { "content": [{ "type": "text", "text": "8" }] },
"duration": 156,
"success": true,
"userId": "john@gmail.com",
"email": "john@gmail.com"
}
{
"eventType": "mcp.tool.payment_required",
"timestamp": 1750360317997,
"serverName": "My Paid MCP",
"toolName": "generate_image",
"parameters": { "prompt": "sunset over mountains" },
"duration": 89,
"success": false,
"customerId": "cus_stripe123",
"paymentType": "oneTimeSubscription",
"paymentStatus": "required",
"priceId": "price_123",
"userId": "john@gmail.com"
}
{
"eventType": "mcp.tool.payment_completed",
"timestamp": 1750360318997,
"serverName": "My Paid MCP",
"toolName": "generate_image",
"parameters": { "prompt": "sunset over mountains" },
"result": { "content": [{ "type": "text", "text": "Image generated successfully" }] },
"duration": 2340,
"success": true,
"customerId": "cus_stripe123",
"paymentAmount": 999,
"paymentCurrency": "usd",
"paymentSessionId": "cs_stripe456",
"paymentType": "oneTimeSubscription",
"paymentStatus": "paid",
"priceId": "price_123",
"userId": "john@gmail.com"
}
import OAuthProvider from "@cloudflare/workers-oauth-provider";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { AnalyticsPaidMcpAgent, PaymentState, PaymentProps } from "mcp-analytics";
import { z } from "zod";
import { GoogleHandler } from "./google-handler";
type Props = PaymentProps & {
name: string;
email: string;
accessToken: string;
};
type State = PaymentState & {};
export class MyMCP extends AnalyticsPaidMcpAgent<Env, State, Props> {
server = new McpServer({
name: "Demo Analytics + Payments MCP",
version: "1.0.0",
});
initialState: State = {};
async init() {
// Free tool - analytics only
this.analyticsTool(
'add',
'Add two numbers together',
{ a: z.number(), b: z.number() },
async ({ a, b }) => ({
content: [{ type: 'text', text: `${a} + ${b} = ${a + b}` }],
})
);
// Paid tool - analytics + payments
this.analyticsPaidTool(
'generate_emoji',
'Generate an emoji given a single word',
{ object: z.string().describe('one word') },
({ object }) => ({
content: [{ type: 'text', text: generateImage(object) }],
}),
{
checkout: {
success_url: 'https://yoursite.com/success',
line_items: [{ price: 'price_emoji_123' }],
mode: 'subscription',
},
meterEvent: 'image_generation',
paymentReason: 'You get 3 free generations, then we charge 10 cents per generation.',
}
);
}
}
export default new OAuthProvider({
apiRoute: "/sse",
apiHandler: MyMCP.mount("/sse"),
defaultHandler: GoogleHandler,
authorizeEndpoint: "/authorize",
tokenEndpoint: "/token",
clientRegistrationEndpoint: "/register",
});
// Before (Stripe Agent Toolkit)
import { experimental_PaidMcpAgent as PaidMcpAgent } from '@stripe/agent-toolkit/cloudflare';
export class MyMCP extends PaidMcpAgent<Bindings, State, Props> {
async init() {
this.paidTool('tool_name', 'description', schema, callback, options);
}
}
// After (MCP Analytics)
import { AnalyticsPaidMcpAgent } from 'mcp-analytics';
export class MyMCP extends AnalyticsPaidMcpAgent<Env, State, Props> {
async init() {
// Same exact API + automatic analytics
this.analyticsPaidTool('tool_name', 'description', schema, callback, options);
}
}
// Before (Standard Cloudflare MCP Agent)
import { McpAgent } from "agents/mcp";
export class MyMCP extends McpAgent<Env, State, Props> {
async init() {
this.server.tool("add", { a: z.number(), b: z.number() }, callback);
}
}
// After (Analytics-Enabled)
import { AnalyticsMcpAgent } from 'mcp-analytics';
export class MyMCP extends AnalyticsMcpAgent<Env, State, Props> {
async init() {
this.analyticsTool("add", "Add two numbers", { a: z.number(), b: z.number() }, callback);
}
}
// Or for paid tools
import { AnalyticsPaidMcpAgent } from 'mcp-analytics';
export class MyMCP extends AnalyticsPaidMcpAgent<Env, State, Props> {
async init() {
// Free tools
this.analyticsTool("add", "Add two numbers", schema, callback);
// Paid tools
this.analyticsPaidTool("premium", "Premium feature", schema, callback, paymentOptions);
}
}
this.analyticsTool<TSchema extends Record<string, z.ZodType>>(
toolName: string,
toolDescription: string,
paramsSchema: TSchema,
callback: (params: { [K in keyof TSchema]: z.infer<TSchema[K]> }) => any,
options?: {
trackResults?: boolean; // Default: true
batchSize?: number; // Default: 20
flushInterval?: number; // Default: 30000ms
}
): void
Extends AnalyticsMcpAgent with additional payment capabilities:
Same as above - for free tools with analytics tracking.
this.analyticsPaidTool<TSchema extends ZodRawShape>(
toolName: string,
toolDescription: string,
paramsSchema: TSchema,
callback: ToolCallback<TSchema>,
options: {
// Payment configuration (required)
checkout: Stripe.Checkout.SessionCreateParams;
paymentReason: string;
// Optional payment settings
meterEvent?: string; // For usage-based billing
// Optional analytics settings
trackResults?: boolean; // Default: true
batchSize?: number; // Default: 20
flushInterval?: number; // Default: 30000ms
}
): void
Sensitive parameters and results are automatically redacted:
// Input parameters
{
username: "john_doe",
password: "secret123", // ⚠️ Sensitive
apiKey: "sk_test_123", // ⚠️ Sensitive
creditCard: "4111-1111" // ⚠️ Sensitive
}
// Tracked parameters (auto-sanitized)
{
username: "john_doe",
password: "[REDACTED]", // ✅ Protected
apiKey: "[REDACTED]", // ✅ Protected
creditCard: "[REDACTED]" // ✅ Protected
}
password, pass, pwdtoken, apikey, api_keysecret, key, authauthorization, credentialcreditcard, cc, cvv// Normal tool - tracks everything including results
this.analyticsTool('add', 'Add numbers', schema, callback);
// Sensitive tool - disable result tracking for privacy
this.analyticsTool(
'processDocument',
'Process sensitive document',
schema,
callback,
{ trackResults: false } // ← Tool calls tracked, results ignored
);
// Paid sensitive tool - payment tracked, results ignored
this.analyticsPaidTool(
'generateMedicalReport',
'Generate confidential medical report',
schema,
callback,
{
checkout: { /* payment config */ },
paymentReason: 'Medical report generation',
trackResults: false // ← Payment data tracked, results protected
}
);
# Analytics (Required for tracking)
MCP_ANALYTICS_API_KEY=your_analytics_api_key
# Payments (Required for AnalyticsPaidMcpAgent)
STRIPE_SECRET_KEY=your_stripe_secret_key
# Optional Settings
MCP_ANALYTICS_ENABLED=true # Enable/disable analytics
ENVIRONMENT=production # Environment tag
MCP_ANALYTICS_API_URL=https://custom.api.com # Custom analytics endpoint
# Local development (.dev.vars file)
MCP_ANALYTICS_API_KEY=your_key_here
STRIPE_SECRET_KEY=your_stripe_key_here
# Production deployment
npx wrangler secret put MCP_ANALYTICS_API_KEY
npx wrangler secret put STRIPE_SECRET_KEY
| Feature | Standard MCP | AnalyticsMcpAgent | AnalyticsPaidMcpAgent |
|---|---|---|---|
| Basic Tools | ✅ | ✅ | ✅ |
| Analytics Tracking | ❌ | ✅ | ✅ |
| User Tracking | ❌ | ✅ | ✅ |
| Performance Metrics | ❌ | ✅ | ✅ |
| Error Tracking | ❌ | ✅ | ✅ |
| Payment Processing | ❌ | ❌ | ✅ |
| Revenue Tracking | ❌ | ❌ | ✅ |
| Usage Billing | ❌ | ❌ | ✅ |
| Subscription Support | ❌ | ❌ | ✅ |
| Free + Paid Tools | ❌ | ❌ | ✅ |
| Stripe Integration | ❌ | ❌ | ✅ |
| Payment Analytics | ❌ | ❌ | ✅ |
| Setup Complexity | 🟢 Simple | 🟢 Simple | 🟢 Simple |
npm install mcp-analyticsAnalyticsMcpAgentserver.tool → analyticsToolMCP_ANALYTICS_API_KEYnpm install mcp-analyticsAnalyticsPaidMcpAgentanalyticsTool for free toolsanalyticsPaidTool for paid toolsAnalyticsPaidMcpAgent for maximum flexibility (supports both free and paid tools)MIT License - see LICENSE file for details.
Start tracking your MCP analytics and processing payments today! 🚀💳
FAQs
Professional analytics SDK for Model Context Protocol tools
The npm package mcp-analytics receives a total of 0 weekly downloads. As such, mcp-analytics popularity was classified as not popular.
We found that mcp-analytics demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.

Security News
Open source is under attack because of how much value it creates. It has been the foundation of every major software innovation for the last three decades. This is not the time to walk away from it.

Security News
Socket CEO Feross Aboukhadijeh breaks down how North Korea hijacked Axios and what it means for the future of software supply chain security.