Getting Started · Features · Docs · Website · Open Source ·
📊 Cloudflare的MCP分析+支付
只需2个简单的更改,即可将强大的分析跟踪和条纹支付添加到Cloudflare MCP服务器。
跟踪工具使用情况、用户行为、性能指标、结果、错误,并自动处理付款,同时保持与Cloudflare平台上构建的现有MCP工具的完全兼容性。
🚀 快速开始
安装
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, 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 {
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🏗️ 平台要求
此SDK是专门为Cloudflare MCP代理设计的:
- ✅ Cloudflare员工 -部署在Cloudflare的边缘平台上
- ✅ Cloudflare MCP代理 -扩展
McpAgent类从agents/mcp - ✅ 耐用物品 -自动会话管理和状态持久化
- ✅ OAuth提供者库 -内置身份验证
@cloudflare/workers-oauth-provider
不兼容:
- ❌ 本地MCP服务器(基于stdio)
- ❌ 其他云平台(AWS、GCP、Azure)
- ❌ 不带Cloudflare扩展的标准MCP SDK
🎯 什么会被自动跟踪
适用于所有工具(免费+付费)
- ✅ 工具执行时间 -每个工具运行需要多长时间
- ✅ 成功/失败状态 -哪些工具成功或失败
- ✅ 输入参数 -用户提供的数据(敏感数据自动编辑)
- ✅ 工具结果 -工具执行的输出数据(自动净化)
- ✅ 错误详细信息 -工具故障时的完整错误信息
- ✅ 用户信息 -从OAuth props自动识别用户
- ✅ 会话跟踪 -按用户会话对工具调用进行分组
- ✅ 服务器元数据 -自动检测到服务器名称和版本
付费工具的附加功能
- 💳 付款事件 -付款要求、完成、失败
- 💳 付款金额 -美元金额和货币
- 💳 客户数据 -条纹化客户ID和支付会话
- 💳 付款类型 -一次性、订阅、基于使用量的计费
- 💳 收入跟踪 -按工具、用户、服务器跟踪收入
- 💳 订阅状态 -主动订阅和取消
💳 与Stripe的支付集成
这 AnalyticsPaidMcpAgent 提供与自动分析跟踪的无缝Stripe集成:
付款事件类型
mcp.tool.payment_required-用户需要付费才能使用工具mcp.tool.payment_completed-付款成功,工具已执行mcp.tool.payment_failed-付款或工具执行失败
基于使用情况的计费示例
this.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',
}
);🔒 使用OAuth进行用户跟踪
自动用户检测
SDK会自动从中提取用户信息 this.props 如果可用:
// 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'
}适用于任何OAuth提供者
- 谷歌 ✅ (测试)
- Logto ✅ (测试)
- 身份验证0 ✅
- GitHub ✅
- 自定义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 {
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",
});📈 迁移指南
来自Stripe Agent工具包
// Before (Stripe Agent Toolkit)
import { experimental_PaidMcpAgent as PaidMcpAgent } from '@stripe/agent-toolkit/cloudflare';
export class MyMCP extends PaidMcpAgent {
async init() {
this.paidTool('tool_name', 'description', schema, callback, options);
}
}
// After (MCP Analytics)
import { AnalyticsPaidMcpAgent } from 'mcp-analytics';
export class MyMCP extends AnalyticsPaidMcpAgent {
async init() {
// Same exact API + automatic analytics
this.analyticsPaidTool('tool_name', 'description', schema, callback, options);
}
}来自标准Cloudflare MCP代理
// Before (Standard Cloudflare MCP Agent)
import { McpAgent } from "agents/mcp";
export class MyMCP extends McpAgent {
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 {
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 {
async init() {
// Free tools
this.analyticsTool("add", "Add two numbers", schema, callback);
// Paid tools
this.analyticsPaidTool("premium", "Premium feature", schema, callback, paymentOptions);
}
}🔧 api参考
AnalyticsMcpAgent(仅限免费工具)
analyticsTool()
this.analyticsTool>(
toolName: string,
toolDescription: string,
paramsSchema: TSchema,
callback: (params: { [K in keyof TSchema]: z.infer }) => any,
options?: {
trackResults?: boolean; // Default: true
batchSize?: number; // Default: 20
flushInterval?: number; // Default: 30000ms
}
): voidAnalyticsPaidMcAgent(免费+付费工具)
扩展 AnalyticsMcpAgent 具有额外的支付功能:
analyticsTool()
与上述相同-用于分析跟踪的免费工具。
analyticsPaidTool()
this.analyticsPaidTool(
toolName: string,
toolDescription: string,
paramsSchema: TSchema,
callback: ToolCallback,
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🔒 数据隐私与安全
自动数据净化
敏感参数和结果会自动编辑:
// 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 endpointCloudflare部署
# 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📊 益处
对于开发者
- 代码更改最少 -只需要2个更改:导入和方法
- 全型安全 -使用泛型完全支持TypeScript
- 自动服务器检测 -无需重复配置
- 自动用户跟踪 -适用于任何OAuth提供者
- 支付集成 -条纹支付,无需额外代码
- 性能洞察 -查看哪些工具速度较慢
- 误差监控 -工具发生故障时收到通知
- 收入跟踪 -自动跟踪付款和收入
- 灵活跟踪 -禁用敏感工具的结果跟踪
商业版
- 用户行为分析 -哪些工具最受欢迎?
- 性能优化 -识别瓶颈
- 收入分析 -按工具、用户、时间段跟踪收入
- 支付洞察 -转化率、付款失败、客户流失
- 误差减少 -在用户投诉之前解决问题
- 增长洞察 -跟踪用户参与度随时间的变化
🆚 比较
| 功能 | 标准MCP | 分析试剂 | 分析试剂 |
|---|---|---|---|
| 基本工具 | ✅ | ✅ | ✅ |
| 分析跟踪 | ❌ | ✅ | ✅ |
| 用户跟踪 | ❌ | ✅ | ✅ |
| 性能指标 | ❌ | ✅ | ✅ |
| 错误跟踪 | ❌ | ✅ | ✅ |
| 支付处理 | ❌ | ❌ | ✅ |
| 收入跟踪 | ❌ | ❌ | ✅ |
| 使用计费 | ❌ | ❌ | ✅ |
| 订阅支持 | ❌ | ❌ | ✅ |
| 免费+付费工具 | ❌ | ❌ | ✅ |
| 条纹集成 | ❌ | ❌ | ✅ |
| 支付分析 | ❌ | ❌ | ✅ |
| 设置复杂性 | 🟢 简单 | 🟢 简单 | 🟢 简单 |
🚀 入门检查表
仅用于分析
- ✅ 安装:
npm install mcp-analytics - ✅ 从获取API密钥 https://mcpanalytics.dev
- ✅ 导入:
AnalyticsMcpAgent - ✅ 替换:
server.tool→analyticsTool - ✅ 使用部署
MCP_ANALYTICS_API_KEY
用于分析+支付
- ✅ 安装:
npm install mcp-analytics - ✅ 从获取分析密钥 https://mcpanalytics.dev
- ✅ 从获取Stripe密钥 https://stripe.com
- ✅ 导入:
AnalyticsPaidMcpAgent - ✅ 用途:
analyticsTool免费工具 - ✅ 用途:
analyticsPaidTool付费工具 - ✅ 使用API两个密钥进行部署
📈 最佳实践
✅ 做的
- 使用
AnalyticsPaidMcpAgent为了获得最大的灵活性(支持免费和付费工具) - 添加描述性工具名称和描述,以进行更好的分析
- 禁用分析进行测试,以确保回退有效
- 在Cloudflare Workers中设置环境变量
- 禁用大型二进制输出或敏感数据的结果跟踪
- 对API和计算密集型工具使用基于使用量的计费
- 使用一次性付款获得高级功能
❌ 不应该做的
- 不要手动跟踪敏感数据(自动清理会处理它)
- 不要依赖分析来获取关键的应用程序逻辑
- 不要忘记设置API密钥
- 不启用图像/视频生成工具的结果跟踪
- 不要将支付逻辑与工具逻辑混为一谈(SDK会自动处理)
🤝 支持
- 📧 电子邮件: contact@mcpanalytics.dev
- 📖 文档: https://docs.mcpanalytics.dev
______________________________________________________________________
许可证
MIT许可证-请参阅 许可证 文件以获取详细信息。
立即开始跟踪您的MCP分析和处理付款! 🚀💳
