使用说明
MCP服务器模板
使用FastMCP 2.0构建MCP(模型上下文协议)服务器的生产就绪模板。
特性
- =� FastMCP 2.0 -MCP服务器的现代Python框架
- =' 示例工具 -计算器、文件操作、网页抓取器、数据处理器
- =� 资源 -配置、状态监控、日志访问
- = 认证 -承载令牌和OAuth支持
- =� 中间件 -日志记录、速率限制、CORS、请求跟踪
- =3 Docker就绪 -具有组合配置的多阶段构建
- 测试 -带pytest的全面测试套件
- =� 类型安全 -完整的类型提示和mypy支持
- <� 生产就绪 -基于环境的配置、健康检查、监控
快速开始
先决条件
- Python 3.12或更高版本
- UV包管理器(
pip install uv)
安装
- 克隆存储库:
git clone https://github.com/yourusername/mcp-server-template.git
cd mcp-server-template
- 使用UV安装依赖项:
uv sync
- 复制环境变量:
cp .env.example .env
# Edit .env with your configuration
- 运行服务器:
对于HTTP模式:
uv run python -m mcp_server_template.main
服务器将于启动 http://localhost:8000.
对于MCP检查器(stdio模式):
uv run mcp-server-stdio
与MCP检查器一起使用
MCP Inspector是MCP服务器的调试工具。以下是如何将其与此模板一起使用:
选项1:直接命令
# Install MCP Inspector
npx @modelcontextprotocol/inspector
# Run with your server
npx @modelcontextprotocol/inspector uv run mcp-server-stdio
选项2:使用配置文件
- 使用提供的
mcp_config.json:
npx @modelcontextprotocol/inspector mcp_config.json
- 或者在MCP客户端中创建自己的配置:
{
"mcpServers": {
"mcp-server-template": {
"command": "uv",
"args": ["run", "mcp-server-stdio"],
"cwd": "/path/to/mcp-server-template"
}
}
}
Inspector中的可用工具:
- 计算:执行数学运算
- read_file:读取文件内容
- write_file:将内容写入文件
- list_directory:浏览目录内容
- scrape_url:从网页中提取内容
- 进程数据:转换和分析数据
Inspector中的可用资源:
- config://settings:查看服务器配置
- status://server:检查服务器运行状况和指标
- logs://recent:访问最近的日志条目
Inspector中的可用提示:
- 编码助理:编程帮助提示
- 数据分析师:数据分析提示
项目结构
mcp-server-template/
�� src/
�� mcp_server_template/
�� __init__.py
�� main.py # Server entry point
�� config.py # Configuration management
�� tools/ # MCP tools
�� calculator.py
�� file_operations.py
�� web_scraper.py
�� data_processor.py
�� resources/ # MCP resources
�� config_resource.py
�� status_resource.py
�� logs_resource.py
�� middleware/ # Middleware components
�� auth.py
�� logging.py
�� rate_limiting.py
�� tests/ # Test suite
�� examples/ # Usage examples
�� docs/ # Documentation
�� fastmcp.json # FastMCP configuration
�� pyproject.toml # Project dependencies
�� Dockerfile # Container configuration
�� docker-compose.yml # Docker compose setup
�� CLAUDE.md # AI assistant instructions
�� .cursorrules # Cursor IDE rules
可用工具
计算器
进行数学计算:
{
"tool": "calculate",
"params": {
"operation": "add",
"a": 5,
"b": 3
}
}
文件操作
读取、写入和列出文件:
{
"tool": "read_file",
"params": {
"path": "/path/to/file.txt"
}
}
Web剪贴器
从URL中提取内容:
{
"tool": "scrape_url",
"params": {
"url": "https://example.com",
"selector": ".content"
}
}
数据处理器
转换和分析数据:
{
"tool": "process_data",
"params": {
"data": [1, 2, 3, 4, 5],
"operation": "statistics"
}
}
可用资源
config://settings-当前服务器配置status://server-服务器运行状况和指标logs://recent-最近的日志条目
配置
环境变量
创建一个 .env 文件包含:
# Environment
ENVIRONMENT=development # development, staging, production
# Authentication
MCP_AUTH_TOKEN=your-secret-token
# OAuth (optional)
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
# Database (optional)
DATABASE_URL=postgresql://user:password@localhost/dbname
# External APIs (optional)
OPENAI_API_KEY=your-openai-key
ANTHROPIC_API_KEY=your-anthropic-key
FastMCP配置
编辑 fastmcp.json 配置:
- 服务器设置
- 验证方法
- 中间件选项
- 资源缓存
- 部署环境
发展
运行测试
# Run all tests
uv run pytest
# Run with coverage
uv run pytest --cov=mcp_server_template --cov-report=html
# Run specific test file
uv run pytest tests/unit/test_calculator.py
代码质量
# Format code
uv run black src tests
# Lint code
uv run ruff check src tests
# Type checking
uv run mypy src
添加新工具
- 在中创建新文件
src/mcp_server_template/tools/ - 使用async方法实现工具类
- 注册
main.py使用@app.tool() - 在中添加测试
tests/unit/tools/
例子:
# src/mcp_server_template/tools/my_tool.py
class MyTool:
async def process(self, input: str) -> dict:
return {"result": f"Processed: {input}"}
# main.py
@app.tool()
async def my_tool(input: str) -> dict:
return await my_tool_instance.process(input)
Docker部署
构建并运行
# Build image
docker build -t mcp-server .
# Run container
docker run -p 8000:8000 --env-file .env mcp-server
# Or use docker-compose
docker-compose up -d
Docker编写配置文件
# Run with PostgreSQL database
docker-compose --profile with-database up
# Run with Redis cache
docker-compose --profile with-cache up
# Run with Nginx proxy
docker-compose --profile with-proxy up
生产部署
环境配置
集 ENVIRONMENT=production 以启用:
- 多人加工
- 基于文件的日志记录
- 优化的性能设置
- 安全强化
健康检查
服务器提供 /health 监控端点:
curl http://localhost:8000/health
监控
通过状态资源访问服务器指标:
{
"resource": "status://server"
}
扩展
调整生产中的工人数量:
# pyproject.toml or environment
SERVER_WORKERS=4 # Number of worker processes
安全
认证
启用承载令牌身份验证:
MCP_AUTH_TOKEN=your-secure-token
请求必须包括:
Authorization: Bearer your-secure-token
速率限制
在中配置 fastmcp.json:
{
"middleware": {
"rate_limiting": {
"enabled": true,
"requests_per_minute": 60
}
}
}
Best Practices
- Always use environment variables for secrets
- Enable authentication in production
- Implement rate limiting
- Use HTTPS with proper certificates
- Regularly update dependencies
- Monitor logs and metrics
- Implement proper error handling
AI Assistant Integration
Claude.ai
The project includes CLAUDE.md with specific instructions for Claude to:
- Challenge assumptions
- Provide counterpoints
- Test reasoning
- Offer alternatives
- Prioritize correctness
Cursor IDE
The .cursorrules file configures Cursor to:
- Use UV for package management
- Follow project conventions
- Maintain code quality
- Challenge implementation decisions
Troubleshooting
Common Issues
-
Import errors
uv sync # Reinstall dependencies -
Port already in use
# Change port in .env or command line uv run uvicorn mcp_server_template.main:app --port 8001 -
Authentication failures
- Check
MCP_AUTH_TOKENis set correctly - Verify Authorization header format
- Check
-
Rate limiting
- Adjust
requests_per_minutein configuration - Check
X-RateLimit-*response headers
- Adjust
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
License
MIT License - see LICENSE file for details
Resources
Support
For issues, questions, or suggestions:
- Open an issue on GitHub
- Check existing documentation
- Review the CLAUDE.md file for development guidance
Built with d using FastMCP 2.0
