零代码实现MCP计费系统:FastAPI-MCP基于使用量的收费方案

零代码实现MCP计费系统:FastAPI-MCP基于使用量的收费方案

【免费下载链接】fastapi_mcp 一种零配置工具,用于自动将 FastAPI 端点公开为模型上下文协议 (MCP) 工具。 【免费下载链接】fastapi_mcp 项目地址: https://gitcode.com/GitHub_Trending/fa/fastapi_mcp

你是否在为API服务的计费问题头疼?还在手动统计调用次数、计算费用?本文将带你了解如何利用FastAPI-MCP快速实现一个基于使用量的MCP工具计费系统,无需复杂配置,轻松解决API收费难题。读完本文,你将掌握:

  • FastAPI-MCP的安装与基础使用
  • 如何追踪MCP工具的调用情况
  • 基于使用量的计费方案设计与实现
  • 完整的计费系统示例代码

准备工作:安装FastAPI-MCP

要开始构建计费系统,首先需要安装FastAPI-MCP。我们推荐使用uv,一个快速的Python包安装器:

uv add fastapi-mcp

如果你习惯使用pip,也可以这样安装:

pip install fastapi-mcp

详细的安装说明可以参考官方文档:docs/getting-started/installation.mdx

FastAPI-MCP基础使用

安装完成后,我们来创建一个简单的FastAPI应用,并集成MCP功能。以下是一个基础示例:

from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

# 添加MCP服务器到FastAPI应用
mcp = FastApiMCP(app)

# 挂载MCP服务器
mcp.mount_http()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

这个简单的示例展示了如何将FastAPI端点自动公开为MCP工具。更详细的基础用法可以参考示例代码:examples/01_basic_usage_example.py

计费系统核心:追踪MCP工具调用

要实现基于使用量的计费,首先需要能够追踪MCP工具的调用情况。我们可以通过添加中间件来记录每次API调用的相关信息,如调用者身份、调用时间、调用的工具等。

实现调用追踪

以下是一个简单的调用追踪中间件示例:

from fastapi import Request
import time
from datetime import datetime

class CallTracker:
    def __init__(self):
        self.calls = []
    
    async def track_call(self, request: Request, tool_name: str, user_id: str):
        start_time = time.time()
        # 在这里记录调用开始的信息
        
        # 返回一个函数,用于在调用结束时记录信息
        async def record_completion(status_code: int):
            duration = time.time() - start_time
            self.calls.append({
                "timestamp": datetime.utcnow(),
                "user_id": user_id,
                "tool_name": tool_name,
                "status_code": status_code,
                "duration": duration
            })
        return record_completion

# 在FastAPI应用中使用
call_tracker = CallTracker()

集成认证与授权

为了准确计费,我们需要识别每个调用者的身份。FastAPI-MCP提供了完善的认证机制,可以轻松集成到计费系统中。

以下是一个基于令牌的认证示例:

from fastapi import Depends
from fastapi.security import HTTPBearer
from fastapi_mcp import FastApiMCP, AuthConfig

# 令牌认证方案
token_auth_scheme = HTTPBearer()

# 创建MCP服务器并启用认证
mcp = FastApiMCP(
    app,
    name="计费系统MCP",
    auth_config=AuthConfig(
        dependencies=[Depends(token_auth_scheme)],
    ),
)

更详细的认证配置可以参考:examples/08_auth_example_token_passthrough.pydocs/advanced/auth.mdx

设计计费方案

基于使用量的计费方案可以有多种形式,以下是一些常见的计费模型:

按调用次数计费

这是最简单直接的计费方式,根据API调用的次数收费。

def calculate_call_based_cost(calls, rate_per_call=0.01):
    """
    按调用次数计算费用
    :param calls: 调用记录列表
    :param rate_per_call: 每次调用的费率
    :return: 总费用
    """
    return len(calls) * rate_per_call

按处理时间计费

对于一些计算密集型的API,按处理时间计费可能更合理。

def calculate_time_based_cost(calls, rate_per_second=0.05):
    """
    按处理时间计算费用
    :param calls: 调用记录列表
    :param rate_per_second: 每秒处理时间的费率
    :return: 总费用
    """
    total_duration = sum(call["duration"] for call in calls)
    return total_duration * rate_per_second

按功能模块计费

如果你的MCP工具包含多个功能模块,可以为不同模块设置不同的费率。

def calculate_module_based_cost(calls, module_rates):
    """
    按功能模块计算费用
    :param calls: 调用记录列表
    :param module_rates: 不同模块的费率字典
    :return: 总费用
    """
    total_cost = 0
    for call in calls:
        module = call["tool_name"]
        rate = module_rates.get(module, 0.01)  # 默认费率
        total_cost += rate
    return total_cost

完整计费系统示例

以下是一个完整的FastAPI-MCP计费系统示例,结合了调用追踪、认证和计费功能:

from examples.shared.apps.items import app  # The FastAPI app
from examples.shared.setup import setup_logging
from fastapi import Depends, Request
from fastapi.security import HTTPBearer
from fastapi_mcp import FastApiMCP, AuthConfig
import time
from datetime import datetime

setup_logging()

# 1. 实现调用追踪
class CallTracker:
    def __init__(self):
        self.calls = []
    
    async def track_call(self, request: Request, tool_name: str):
        start_time = time.time()
        user_id = request.state.user_id  # 假设用户ID存储在请求状态中
        
        async def record_completion(status_code: int):
            duration = time.time() - start_time
            self.calls.append({
                "timestamp": datetime.utcnow(),
                "user_id": user_id,
                "tool_name": tool_name,
                "status_code": status_code,
                "duration": duration
            })
        return record_completion

call_tracker = CallTracker()

# 2. 设置认证
token_auth_scheme = HTTPBearer()

async def get_current_user(token=Depends(token_auth_scheme)):
    # 这里可以解析令牌,获取用户信息
    user_id = token.credentials  # 简化处理,实际应用中需要验证令牌
    return user_id

# 3. 创建MCP服务器
mcp = FastApiMCP(
    app,
    name="计费系统MCP",
    auth_config=AuthConfig(
        dependencies=[Depends(get_current_user)],
    ),
    describe_full_response_schema=True,  # 描述完整的响应模式
)

# 4. 添加计费相关端点
@app.get("/billing/calls")
async def get_call_history(user_id: str = Depends(get_current_user)):
    """获取用户的调用历史"""
    user_calls = [call for call in call_tracker.calls if call["user_id"] == user_id]
    return {"user_id": user_id, "calls": user_calls}

@app.get("/billing/cost")
async def calculate_cost(user_id: str = Depends(get_current_user)):
    """计算用户的费用"""
    user_calls = [call for call in call_tracker.calls if call["user_id"] == user_id]
    
    # 按调用次数计费
    call_based_cost = len(user_calls) * 0.01
    
    # 按处理时间计费 (超过1秒的部分)
    total_duration = sum(call["duration"] for call in user_calls if call["duration"] > 1)
    time_based_cost = total_duration * 0.005
    
    total_cost = call_based_cost + time_based_cost
    
    return {
        "user_id": user_id,
        "call_count": len(user_calls),
        "total_duration": total_duration,
        "call_based_cost": call_based_cost,
        "time_based_cost": time_based_cost,
        "total_cost": total_cost
    }

mcp.mount_http()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

更详细的API响应模式配置可以参考:examples/02_full_schema_description_example.py

部署与监控

部署计费系统

FastAPI-MCP应用可以轻松部署到各种环境。部署时,建议将计费数据存储到数据库中,而不是保存在内存中。

监控系统性能

为了确保计费系统的准确性和可靠性,我们需要监控系统的性能。可以使用FastAPI-MCP的完整响应描述功能,结合监控工具进行系统监控。

总结与展望

本文介绍了如何使用FastAPI-MCP快速构建一个基于使用量的MCP工具计费系统。我们从安装FastAPI-MCP开始,逐步实现了调用追踪、用户认证、计费方案设计和完整的系统示例。

未来,我们可以进一步扩展这个计费系统,添加更多高级功能:

  • 实时计费和预警
  • 多维度的计费模型
  • 优惠券和折扣系统
  • 详细的使用报告和分析

通过FastAPI-MCP,我们可以专注于业务逻辑的实现,而无需担心MCP协议的细节,极大地提高了开发效率。

希望本文能帮助你构建出高效、灵活的API计费系统!如果你有任何问题或建议,欢迎参考docs/getting-started/FAQ.mdx或参与项目贡献。

【免费下载链接】fastapi_mcp 一种零配置工具,用于自动将 FastAPI 端点公开为模型上下文协议 (MCP) 工具。 【免费下载链接】fastapi_mcp 项目地址: https://gitcode.com/GitHub_Trending/fa/fastapi_mcp

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值