使用说明
MCP模板
Python中的生产就绪MCP(模型上下文协议)服务器模板,具有注册表集成、全面的配置管理和可扩展性模式。
特性
- 生产准备就绪:企业级错误处理、结构化日志记录和优雅关机
- 注册表集成:自动服务器注册、心跳和注销
- 配置管理:基于YAML的配置,带有环境变量覆盖和Pydantic验证
- 可扩展架构:易于扩展工具、资源和提示的基类
- 类型安全:整个代码库中的完整类型提示
- 开发者体验:全面的CLI、广泛的文档和示例实现
- 测试:使用pytest的单元和集成测试示例
快速开始
安装
# Clone or copy this template
cd mcp-template
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -e ".[dev]"
# Or using requirements.txt
pip install -r requirements-dev.txt
初始化配置
# Initialize default configuration
mcp-template init
# This creates:
# - config/config.yaml (server configuration)
# - .env (environment variables)
运行服务器
# Run with default configuration
mcp-template run
# Run with custom config
mcp-template run --config path/to/config.yaml
# Run in debug mode
mcp-template run --debug
# Validate configuration
mcp-template validate
# Check health
mcp-template health
项目结构
mcp-template/
├── src/mcp_template/
│ ├── core/ # Core server components
│ │ ├── server.py # Base MCP server implementation
│ │ ├── settings.py # Pydantic settings models
│ │ ├── config_loader.py # Configuration loader
│ │ └── logger.py # Structured logging setup
│ ├── registry/ # Registry integration
│ │ ├── base.py # Registry client interface
│ │ ├── http_client.py # HTTP registry implementation
│ │ └── manager.py # Registry lifecycle manager
│ ├── tools/ # MCP tools
│ │ ├── calculator.py # Example calculator tool
│ │ └── search.py # Example search tool
│ ├── resources/ # MCP resources
│ │ ├── config.py # Configuration resource
│ │ └── status.py # Status resource
│ ├── prompts/ # MCP prompts
│ │ └── example.py # Example prompt
│ ├── app.py # Main application
│ └── cli.py # Command-line interface
├── config/
│ └── config.yaml # Server configuration
├── tests/
│ ├── unit/ # Unit tests
│ └── integration/ # Integration tests
├── pyproject.toml # Project metadata and dependencies
├── requirements.txt # Production dependencies
├── requirements-dev.txt # Development dependencies
├── Makefile # Development commands
└── README.md # This file
配置
配置文件(config/config.yaml)
主配置文件支持:
- 服务器设置:名称、版本、描述、调试模式
- 日志记录:级别、格式(JSON/text)、文件输出
- 注册表:URL、身份验证、心跳设置、元数据
- 工具/资源/提示:启用/禁用特定组件
例子:
server:
name: "my-mcp-server"
version: "0.1.0"
description: "My custom MCP server"
logging:
level: "INFO"
format: "json"
registry:
enabled: true
url: "https://registry.example.com/api/v1"
auth:
type: "api_key"
api_key: "${REGISTRY_API_KEY}"
heartbeat:
enabled: true
interval: 60
tools:
enabled:
- "example_calculator"
- "example_search"
环境变量
使用双下划线作为分隔符的环境变量覆盖配置:
# Override server name
export SERVER__NAME="production-server"
# Override registry URL
export REGISTRY__URL="https://prod-registry.example.com"
# Set API key
export REGISTRY__AUTH__API_KEY="your-api-key"
# Override logging level
export LOGGING__LEVEL="DEBUG"
环境变量文件(.env)
创建一个 .env 本地开发文件:
# Registry
REGISTRY_API_KEY=your-api-key-here
# Server overrides
SERVER__DEBUG=false
# Logging
LOGGING__LEVEL=INFO
添加自定义组件
添加新工具
- 在中创建新文件
src/mcp_template/tools/:
# src/mcp_template/tools/my_tool.py
import mcp.types as types
async def my_tool_handler(arguments: dict) -> str:
"""Handle the tool call."""
# Your implementation here
return "Result"
MY_TOOL_SCHEMA = types.Tool(
name="my_tool",
description="Description of what the tool does",
inputSchema={
"type": "object",
"properties": {
"param1": {
"type": "string",
"description": "Parameter description"
}
},
"required": ["param1"]
}
)
- 在中注册
src/mcp_template/app.py:
from .tools.my_tool import my_tool_handler, MY_TOOL_SCHEMA
# In MCPTemplateApp._register_components():
self.server.register_tool(
"my_tool",
my_tool_handler,
MY_TOOL_SCHEMA,
)
- 在中启用它
config/config.yaml:
tools:
enabled:
- "my_tool"
添加新资源
类似的模式-创建处理程序和模式,注册 app.py,在配置中启用。
# src/mcp_template/resources/my_resource.py
import mcp.types as types
async def my_resource_handler(uri: str) -> str:
"""Handle resource read."""
return "Resource data"
MY_RESOURCE_SCHEMA = types.Resource(
uri="myresource://example",
name="My Resource",
description="Resource description",
mimeType="application/json"
)
添加新提示
# src/mcp_template/prompts/my_prompt.py
import mcp.types as types
async def my_prompt_handler(arguments: dict) -> types.GetPromptResult:
"""Handle prompt request."""
return types.GetPromptResult(
description="Prompt description",
messages=[
types.PromptMessage(
role="user",
content=types.TextContent(
type="text",
text="Prompt text"
)
)
]
)
MY_PROMPT_SCHEMA = types.Prompt(
name="my_prompt",
description="Prompt description",
arguments=[
types.PromptArgument(
name="arg1",
description="Argument description",
required=True
)
]
)
注册表集成
该模板包括一个用于服务器发现和管理的可插拔注册表系统。
运作原理
- 注册:启动时,服务器向注册表注册
- 心跳:定期心跳保持记录
- 注销:优雅的关闭会注销服务器
自定义注册表后端
实施 RegistryClient 自定义后端接口:
from mcp_template.registry.base import RegistryClient
class MyRegistryClient(RegistryClient):
async def register(self, server_info: dict) -> dict:
# Your implementation
pass
async def deregister(self, server_id: str) -> bool:
# Your implementation
pass
# Implement other methods...
然后在您的应用程序中使用它:
from mcp_template.registry.manager import RegistryManager
registry_manager = RegistryManager(settings, client=MyRegistryClient())
发展
设置开发环境
# Install with development dependencies
pip install -e ".[dev]"
# Or using make
make install
运行测试
# Run all tests
pytest
# Run with coverage
pytest --cov
# Run only unit tests
pytest tests/unit
# Run only integration tests
pytest tests/integration -m integration
# Using make
make test
代码质量
# Format code
make format
# Lint code
make lint
# Type check
make typecheck
# Run all checks
make check
预提交钩子
# Install pre-commit hooks
pre-commit install
# Run manually
pre-commit run --all-files
部署
码头工人
创建一个 Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY src/ src/
COPY config/ config/
RUN pip install -e .
CMD ["mcp-template", "run"]
构建并运行:
docker build -t mcp-template .
docker run -e REGISTRY_API_KEY=your-key mcp-template
环境特定配置
为每个环境创建不同的配置文件:
config/
├── config.yaml # Default
├── config.dev.yaml # Development
├── config.staging.yaml # Staging
└── config.prod.yaml # Production
使用特定配置运行:
mcp-template run --config config/config.prod.yaml
监测和可观察性
结构化日志记录
所有日志都是结构化的(默认为JSON格式),便于解析:
{
"timestamp": "2024-01-01T12:00:00.000Z",
"level": "info",
"event": "Server started",
"server": "my-server",
"version": "0.1.0"
}
健康检查
# CLI health check
mcp-template health
# Programmatic health check
from mcp_template.app import create_app
app = create_app()
health = await app.server.health_check()
故障排除
常见问题
未找到配置文件
# Initialize configuration
mcp-template init
# Or specify path
mcp-template run --config path/to/config.yaml
注册表连接失败
# Check registry health
mcp-template health
# Disable registry temporarily
# In config.yaml:
registry:
enabled: false
导入错误
# Reinstall in editable mode
pip install -e .
贡献
- 分叉存储库
- 创建要素分支
- 进行更改
- 添加测试
- 运行代码质量检查:
make check - 提交拉取请求
许可证
MIT许可证-有关详细信息,请参阅许可证文件
资源
支持
对于问题、疑问或贡献,请在GitHub上打开问题。