MCP服务器模板

一个用于创建VS Code模型上下文协议(MCP)服务器的Python模板,提供配置管理、日志记录和错误处理等基础功能。

  • by djaboxx
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 djaboxx/template-mcp-server

使用说明

Python MCP服务器模板

使用Python创建VS代码模型上下文协议(MCP)服务器的模板存储库。此模板遵循生产MCP服务器建立的模式和最佳实践。

目的

此模板为构建以下MCP服务器提供了基础:

  • 与VS Code的AI功能集成
  • 遵循生产MCP服务器的既定模式
  • 一致地处理配置、日志记录和错误情况
  • 使用异步Python和MCP工具的最佳实践

建筑

该模板遵循生产MCP服务器中的这些关键架构模式:

  1. 服务配置

    • 用于配置验证的Pydantic模型
    • 基于环境变量的配置
    • 服务器生命周期中的服务客户端初始化
  2. 服务器生命周期

    • 服务器生命周期异步上下文管理器
    • 清洁启动/关闭处理
    • 最终块中的资源清理
  3. 工具实施

    • 基于装饰器的工具注册
    • 一致的错误处理和日志记录
    • 结构化响应格式
  4. 发展模式

    • 全程键入提示
    • 具有可配置级别的详细日志记录
    • 服务状态验证检查

项目结构

基于生产模式的标准MCP服务器结构:

.
├── src/                     # Python source code
│   ├── server.py           # Main MCP server implementation
│   ├── services/           # Service client implementations
│   │   └── client.py       # Your service client code
│   ├── models.py           # Data models and schemas
│   ├── config.py           # Configuration models
│   └── utils/              # Utility functions
├── docs/                   # Documentation
│   └── mcp-server-guide.md # Server implementation guide
├── tests/                  # Test files
├── requirements.txt        # Python dependencies
└── README.md              # Project documentation

代码组织

该模板遵循生产MCP服务器的这些约定:

  1. 服务器入口点 (src/server.py):

    # Configuration models
    class ServiceConfig(BaseModel):
        api_key: str
        # ...
    
    # Server lifespan
    @asynccontextmanager
    async def server_lifespan(server: FastMCP):
        try:
            # Initialize services
            yield
        finally:
            # Cleanup
    
    # FastMCP instance
    mcp = FastMCP(
        name="Your Server",
        instructions="Your server description",
        lifespan=server_lifespan
    )
    
    # Tools
    @mcp.tool()
    async def your_tool(ctx: Context):
        # Tool implementation
    
  2. 服务客户端 (src/services/):

    • 实施特定于服务的客户端
    • 处理身份验证和重试
    • 管理连接状态
  3. 模型 (src/models.py):

    • 定义用于数据验证的Pydantic模型
    • 结构工具输入和输出
    • 定义服务特定类型

实施指南

  1. 配置:

    • 添加配置模型以满足您的服务需求
    • 使用环境变量作为机密
    • 为必填字段添加验证
  2. 服务客户端:

    • 在中实现您的服务客户端 services/
    • 添加连接/重试处理
    • 包括适当的清理
  3. 工具:

    • 使用 @mcp.tool() 装饰器
    • 包括类型提示和文档字符串
    • 遵循错误处理模式:
    @mcp.tool()
    async def your_tool(ctx: Context) -> Dict[str, Any]:
        try:
            # Implementation
            return {"status": "success", "result": result}
        except Exception as e:
            await ctx.error(f"Error: {e}")
            return {"status": "error", "message": str(e)}
    
  4. 错误处理:

    • 使用结构化错误响应
    • 用上下文记录错误
    • 返回用户友好的消息

入门指南

  1. 使用此模板创建新存储库:

    git clone https://github.com/username/template-mcp-server.git your-server
    cd your-server
    
  2. 设置开发环境:

    python -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt
    
  3. 更新中的服务器名称和描述 src/server.py

  4. 添加您的服务配置和客户端

VS代码配置

要将此服务器与VS Code的MCP功能一起使用,请将以下配置添加到您的VS Code中 settings.json:

"mcp": {
  "inputs": [
    {
      "type": "promptString",
      "id": "service-api-key",
      "description": "Service API Key",
      "password": true
    }
  ],
  "servers": {
    "template-mcp": {
      "type": "stdio",
      "command": "${userHome}/git/template-mcp-server/venv/bin/python",
      "args": [
        "${userHome}/git/template-mcp-server/src/server.py"
      ],
      "env": {
        "SERVICE_API_KEY": "${input:service-api-key}",
        "SERVICE_ENDPOINT": "https://api.example.com",
        "SERVICE_TIMEOUT": "30",
        "LOG_LEVEL": "INFO"
      }
    }
  }
}

配置选项

  • 环境变量:
    • SERVICE_API_KEY:您的服务API密钥(必需)
    • SERVICE_ENDPOINT:服务端点URL(默认值:https://api.example.com)
    • SERVICE_TIMEOUT:请求超时(秒)(默认值:30)
    • LOG_LEVEL:日志记录级别(默认值:INFO)

测试

遵循生产MCP服务器的模式:

  1. 手动测试:

    # Run the server directly
    python src/server.py
    
    # Test with different log levels
    LOG_LEVEL=DEBUG python src/server.py
    
  2. 集成测试:

    # Start server with test configuration
    SERVICE_API_KEY=test-key python src/server.py
    
  3. 开发技巧:

    • 使用VS Code的Python调试器逐步执行工具
    • 在服务客户端中设置断点以调试集成问题
    • 在开发过程中使用DEBUG日志级别进行详细输出

常见模式

通过分析生产MCP服务器,以下是要遵循的关键模式:

  1. 服务客户端状态:

    • 在服务器生命周期内初始化
    • 存储在全局变量中
    • 使用前检查初始化
    • 最后一块清理
  2. 错误处理:

    • 用上下文记录错误
    • 返回结构化错误响应
    • 使用ctx.error()获取用户反馈
    • 包括状态和消息
  3. 配置:

    • 使用Pydantic模型
    • 设置合理的默认值
    • 启动时验证
    • 支持环境覆盖
  4. 工具实施:

    • 使用Args部分清除文档字符串
    • 为所有参数键入提示
    • 结构化响应
    • 一致的错误格式

资源

VS代码配置

要将此服务器与VS Code的MCP(模型上下文协议)功能一起使用,请将以下配置添加到VS Code中 settings.json:

"mcp": {
  "inputs": [
    {
      "type": "promptString",
      "id": "service-api-key",
      "description": "Service API Key",
      "password": true
    }
  ],
  "servers": {
    "template-mcp": {
      "type": "stdio",
      "command": "${userHome}/git/template-mcp-server/venv/bin/python",
      "args": [
        "${userHome}/git/template-mcp-server/src/server.py"
      ],
      "env": {
        "SERVICE_API_KEY": "${input:service-api-key}",
        "SERVICE_ENDPOINT": "https://api.example.com",
        "SERVICE_TIMEOUT": "30",
        "LOG_LEVEL": "INFO"
      }
    }
  }
}

配置选项

  • 环境变量:
    • SERVICE_API_KEY:您的服务API密钥(必需)
    • SERVICE_ENDPOINT:服务端点URL(默认值:https://api.example.com)
    • SERVICE_TIMEOUT:请求超时(秒)(默认值:30)
    • LOG_LEVEL:日志记录级别(默认值:INFO)

先决条件

在使用服务器之前:

  1. 在项目目录中设置Python虚拟环境:

    python -m venv venv
    source venv/bin/activate  # or `venv\Scripts\activate` on Windows
    pip install -r requirements.txt
    
  2. 配置VS代码:

    • 使用stdio配置创建.vcode/mcp.json
    • 在VS Code中设置Python解释器
    • 使用集成终端运行命令
    • 使用VS Code的Python调试器调试MCP服务器
  3. 测试您的MCP服务器:

    • 使用VS Code内置的MCP服务器测试功能
    • 使用断点和VS Code的调试控制台进行调试
    • 监控输出面板中的stdio通信

贡献

  1. 分叉存储库
  2. 创建要素分支
  3. 提交拉取请求

许可证

[您选择的许可证]