使用说明
MCP服务器模板(Python)
用于在Python中构建模型上下文协议(MCP)服务器的现成模板。此模板可帮助您快速创建可以注册和公开AI模型使用的工具和提示的服务器。
📚 目录
🚀 快速开始
先决条件
- Python 3.10或更新版本
通过3个简单步骤进行设置
1.️⃣ 安装软件包
# Clone the repository
git clone https://github.com/MrQbit/mcp-server-template.git my-mcp-server
cd my-mcp-server
# Install in development mode
pip install -e ".[dev]"
2.️⃣ 运行您的服务器
# Run with Python
python -m src.main
# Or use the convenient CLI
mcp-server-template
3.️⃣ 您的服务器现已上线!
访问您的MCP服务器:
- 🌐 HTTP:http://localhost:8080
- 💻 或者使用stdio传输:
mcp-server-template --transport stdio
您将看到日志输出,确认服务器正在成功运行。
🎮 命令行选项
使用以下命令行选项自定义服务器行为:
# Change port (default: 8080)
mcp-server-template --port 9000
# Enable debug mode for more detailed logs
mcp-server-template --debug
# Use stdio transport instead of HTTP
mcp-server-template --transport stdio
# Set logging level (options: debug, info, warning, error)
mcp-server-template --log-level debug
🛠️ 创建自己的工具和提示
添加工具
工具是AI模型可以调用的函数。要添加新工具,请执行以下操作:
- 编辑
src/main.py - 使用添加新功能
@mcp.tool()装饰师:
@mcp.tool()
def your_tool_name(param1: str, param2: int) -> Dict[str, Any]:
"""
Your tool description - this will be shown to the AI.
Args:
param1: Description of first parameter
param2: Description of second parameter
Returns:
Dictionary with your results
"""
# Your tool logic here
return {"result": "your result"}
添加提示
提示是AI模型可以访问的模板:
@mcp.prompt()
def your_prompt_name(param: str) -> str:
"""Your prompt description."""
return f"""
Your formatted prompt with {param} inserted.
Use this for structured prompt templates.
"""
📁 项目结构
src/ # Source code directory
├── main.py # Server entry point with tools & prompts
├── config.py # Configuration settings
├── utils/ # Utility functions
├── tools/ # Tools implementation
└── resources/ # Resource definitions
test/ # Tests directory
pyproject.toml # Package configuration
Dockerfile # Docker support
🚢 部署选项
Docker部署
# Build the Docker image
docker build -t my-mcp-server .
# Run the container
docker run -p 8080:8080 my-mcp-server
云部署
此模板旨在与各种云平台很好地配合使用:
- 在AWS、GCP或Azure上部署为容器
- 在支持容器化应用程序的无服务器平台上运行
- 使用Kubernetes进行编排
🧪 开发指南
# Install development dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Format code
black src test
isort src test
# Run linting
flake8 src test
❓ 需要帮助?
- 📚 MCP文件: 模型上下文协议.io
- 🐛 提交问题: GitHub问题
数据库支持
此模板包括对连接到外部PostgreSQL数据库的支持。要使用数据库功能,请执行以下操作:
-
复制
.env.example向.env并配置您的数据库连接:cp .env.example .env -
更新
.env包含数据库凭据的文件:DB_HOST=your_database_host DB_PORT=5432 DB_NAME=your_database_name DB_USER=your_username DB_PASSWORD=your_password -
在工具中使用数据库上下文:
@mcp.tool() async def query_database(query: str, context: Dict[str, Any]) -> Dict[str, Any]: """Execute a read-only SQL query.""" session = context["database"]["db_session"] result = await session.execute(query) rows = result.fetchall() return {"results": [dict(row) for row in rows]}
数据库上下文提供程序通过适当的连接池和清理自动管理连接和会话。
API工具支持
此模板包括对根据API规范自动生成工具的支持。您可以通过指定OpenAPI、Swagger或GraphQL API端点来添加工具。
配置
-
复制
.env.example向.env并配置您的API端点:cp .env.example .env -
更新
.env使用API配置文件:API_SPECS='[ { "name": "weather", "url": "https://api.openweathermap.org/openapi.json", "type": "openapi", "auth": { "type": "api_key", "key": "your_api_key" }, "rate_limits": { "requests_per_minute": 60 } } ]'
支持的API类型
- OpenAPI/Swagger:根据OpenAPI 3.0或Swagger 2.0规范自动生成工具
- 图查询语言:从GraphQL模式生成工具(即将推出)
特性
- 根据API规范自动生成工具
- 支持多种身份验证方法:
- API密钥
- 承载令牌
- OAuth2(即将推出)
- 速率限制支持
- 类型安全参数和响应处理
- 自动生成文档
示例用法
生成的工具可以像任何其他MCP工具一样使用:
@mcp.tool()
async def get_weather(
city: str,
context: Dict[str, Any]
) -> Dict[str, Any]:
"""Get weather information for a city."""
weather_api = context["api_clients"]["weather"]
response = await weather_api.get_weather(city=city)
return {"temperature": response.temperature}
安全考虑
- API密钥和令牌通过环境变量进行安全管理
- 速率限制可防止滥用外部API
- 输入验证确保安全的API调用
- 身份验证是自动处理的
由以下材料制成❤️ 面向AI开发者社区
