mcpField
M
MCP Server Development Framework

MCP Server Development Framework

本地服务
github.com/mlzoo开发工具20818 周前更新

关于 MCP Server Development Framework

这是一个基于 FastAPI 与 FastAPI-MCP 的 Python 框架,用于开发企业级 MCP 服务。它将现有 API 端点转换为 AI 模型可调用的工具,适合需要规范化开发流程的团队。

主要功能

  1. 01FastAPI 端点自动转换为 MCP 工具
  2. 02接口与实现分离
  3. 03基于依赖注入的组件组合
  4. 04Mock 与真实实现切换
  5. 05提供示例服务与开发工具链

适用场景

  1. 01将已有 API 改造为 AI 可调用的工具
  2. 02团队统一 MCP 服务的开发规范
  3. 03为 MCP 工具编写单元与集成测试

MCP 相关

框架通过 FastAPI-MCP 将 FastAPI 端点暴露为 MCP 端点,MCP 客户端(如 Cursor、Claude Desktop)可直接连接调用。

配置

本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。

暂未收录安装方式

我们还没有获取到这个服务的安装包或远程地址,请按项目 README 中的说明安装。

代码仓库

工具

还没有获取到工具列表

本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。

详细介绍

MCP 服务开发框架

中文文档

概述

这是一个面向企业级模型上下文协议(MCP)工具开发的专业框架,旨在规范 MCP 服务开发流程,帮助开发者快速构建高质量的 AI 工具。通过集成 FastAPI 和 FastAPI-MCP,该框架可将传统 API 无缝转换为可供 AI 调用的工具。

主要功能
  • MCP 工具标准化:自动将传统 FastAPI 端点转换为可供 AI 模型调用的 MCP 工具
  • 接口与实现分离:支持明确分离接口定义与实现,便于测试和环境切换
  • 依赖注入设计:利用 FastAPI 的依赖注入机制,实现灵活的组件组合与解耦
  • 完整的开发流程:提供从开发、测试到部署的全面工具链支持
  • 示例驱动的文档:通过实际示例展示最佳实践,加快上手进程

该框架特别适用于:

  • AI 工具开发团队
  • 希望将现有 API 转换为 AI 工具的开发者
  • 实施标准化微服务架构的组织

架构

核心架构
┌─────────────┐      ┌───────────────┐      ┌─────────────────┐
│   API Layer │ ──→  │ Service Layer │ ──→  │ Implementation  │
└─────────────┘      └───────────────┘      └─────────────────┘
       ↓
┌─────────────┐
│ MCP Endpoint│ ←── FastAPI-MCP Auto-Conversion
└─────────────┘
主要组件
  • FastAPI 应用:提供 HTTP API 服务基础
  • FastAPI-MCP:将 API 端点转换为 MCP 工具
  • 服务接口层:通过抽象基类定义服务契约
  • 依赖注入提供器:管理服务实例的创建与注入
  • 实现类:包含 Mock 和 Real 实现,并支持基于环境切换

技术栈

  • Python 3.10+:采用最新语言特性和类型注解
  • FastAPI:高性能异步 Web 框架
  • FastAPI-MCP:自动将 FastAPI 端点公开为 MCP 工具
  • 开发工具链:包含代码质量检查和测试工具

快速开始

环境设置

该框架使用 uv 作为包管理器,提供更快的依赖解析和虚拟环境管理。安装说明请参阅 uv 官方文档。

# Install dependencies and set up the development environment
make install
启动示例服务
# Start the development server
make dev

服务运行后,你可以:

  • 在 http://localhost:5000/docs 查看 API 文档
  • 使用 MCP 客户端(例如 Cursor、Claude Desktop)连接到 http://localhost:5000/mcp 端点

项目结构

.
├── main.py                    # Application entry point and route definitions
├── services/                  # Service layer implementations
│   └── parking_service.py     # Example service (replaceable with custom services)
├── pyproject.toml             # Project configuration and dependency definitions
└── Makefile                   # Development and build tasks

MCP 工具开发指南

开发流程概述
  1. 定义服务接口:创建抽象基类以定义服务契约
  2. 实现服务:根据需求开发 Mock 或 Real 实现
  3. 创建 API 端点:使用 FastAPI 开发 API 接口
  4. 启用 MCP 服务:通过 FastAPI-MCP 将端点公开为 AI 工具
服务接口与实现
# 1. Service Interface Definition
from abc import ABC, abstractmethod
from typing import Dict, Any

class DataService(ABC):
    @abstractmethod
    def get_data(self, id: str) -> Dict[str, Any]:
        """Data retrieval interface"""
        pass

# 2A. Mock Implementation - for development and testing
class DataServiceMockImpl(DataService):
    def get_data(self, id: str) -> Dict[str, Any]:
        return {"id": id, "name": "Test Data", "mock": True}

# 2B. Real Implementation - for production environment
class DataServiceImpl(DataService):
    def __init__(self, database_url: str):
        self.db = Database(database_url)

    def get_data(self, id: str) -> Dict[str, Any]:
        return self.db.query("SELECT * FROM data WHERE id = :id", {"id": id})

# 3. Dependency Injection Configuration
def get_data_service() -> DataService:
    # Choose implementation based on environment
    return DataServiceMockImpl() # or return DataServiceImpl(settings.DATABASE_URL)
API 与 MCP 工具定义
from fastapi import FastAPI, Depends
from fastapi_mcp import FastApiMCP
from pydantic import BaseModel, Field

app = FastAPI()

# Request model
class ItemRequest(BaseModel):
    query: str = Field(..., description="Search query parameter")
    limit: int = Field(10, description="Result limit")

# API endpoint - automatically converted to an MCP tool
@app.post("/items/search", operation_id="search_items")
async def search_items(
    request: ItemRequest,
    service: DataService = Depends(get_data_service)
):
    result = service.search_items(request.query, request.limit)
    return {"items": result["items"], "total": len(result["items"])}

# Create and mount MCP service
mcp = FastApiMCP(
    app,
    name="example-service",
    description="Example MCP service",
    base_url="http://localhost:5000",
    include_operations=["search_items"]
)

# Mount MCP service at specified path
mcp.mount(mount_path="/mcp")

依赖注入详解

FastAPI 的依赖注入系统是该框架的重要组成部分,提供强大且灵活的依赖管理能力。

依赖注入基础

依赖注入是一种设计模式,允许将依赖项(例如服务、数据库连接等)注入使用它们的组件,而不是由组件自行创建和管理依赖项。在 FastAPI 中,依赖注入通过 Depends 函数实现。

from fastapi import Depends

def get_db():
    """Database connection provider"""
    db = connect_to_db()
    try:
        yield db  # Using yield enables lifecycle management of dependencies
    finally:
        db.close()

@app.get("/items/")
async def get_items(db = Depends(get_db)):
    return db.query(Item).all()
依赖类型

FastAPI 支持多种依赖注入类型:

  1. 函数依赖:如上所示,使用函数作为依赖提供者
  2. 类依赖:使用类作为依赖,以实现更复杂的依赖管理
class DatabaseDependency:
    def __init__(self, settings = Depends(get_settings)):
        self.settings = settings

    def __call__(self):
        db = connect_to_db(self.settings.db_url)
        try:
            yield db
        finally:
            db.close()

@app.get("/users/")
async def get_users(db = Depends(DatabaseDependency())):
    return db.query(User).all()
  1. 嵌套依赖:依赖可以依赖于其他依赖,从而形成依赖树
在 MCP 工具开发中的应用

在此框架中,依赖注入主要用于:

  1. 服务实例管理:将服务实现注入 API 端点
  2. 环境适配:根据运行时环境选择不同的服务实现
  3. 资源生命周期管理:管理数据库连接等资源的创建与释放

FastAPI-MCP 的功能

自动生成 MCP 工具

FastAPI-MCP 可以自动将 FastAPI 端点转换为 MCP 工具:

from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

# Define a standard FastAPI endpoint
@app.post("/predict", operation_id="predict_sentiment")
async def predict_sentiment(text: str):
    return {"sentiment": "positive", "confidence": 0.92}

# Create and mount MCP service - automatically converts the above endpoint to an MCP tool
mcp = FastApiMCP(
    app,
    name="sentiment-analysis",
    description="Sentiment analysis service",
    base_url="http://localhost:5000",
    include_operations=["predict_sentiment"]
)

# Mount MCP service at specified path
mcp.mount(mount_path="/mcp")
工具命名最佳实践

MCP 工具名称默认使用 API 端点的 operation_id。我们建议遵循以下命名规范:

  • 使用清晰、描述性强的名称
  • 采用 verb_noun 格式(例如,predict_sentiment、find_nearby_parking)
  • 明确设置 operation_id,而不是依赖自动生成
# Recommended: Explicitly set operation_id
@app.post("/parking/nearby", operation_id="find_nearby_parking")
async def find_nearby(request: NearbyRequest):
    # Implementation logic...
    pass

# Not recommended: Relying on auto-generated operation_id (generates something like "find_nearby_parking_nearby_post")
@app.post("/parking/nearby")
async def find_nearby(request: NearbyRequest):
    # Implementation logic...
    pass

测试与质量保证

此框架支持多层级测试策略:

# Run code quality checks
make check

# Run test suite
make test
测试策略
  • 单元测试:使用 Mock 服务实现测试各个组件
  • 集成测试:测试组件之间的交互
  • API 测试:验证 HTTP 接口行为
  • MCP 工具测试:验证 AI 工具功能

性能优化

为确保 MCP 工具具有高性能,我们建议:

  • 异步处理:利用 FastAPI 的异步功能并发处理请求
  • 缓存策略:为频繁请求的数据实现缓存
  • 批处理:设计支持批量操作的 API,以减少调用频率

贡献指南

欢迎为此框架做出贡献:

  1. Fork 此仓库
  2. 创建功能分支(git checkout -b feature/amazing-feature)
  3. 提交更改(git commit -m 'Add amazing feature')
  4. 推送到该分支(git push origin feature/amazing-feature)
  5. 创建 Pull Request

许可证

MIT 许可证

参考资料

评论

支持 Markdown

第一次接触 MCP?

从协议是什么,到在客户端里装上第一个服务,这几条回答覆盖了大多数入门问题。

一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。