MCP骨架-MCP服务器模板(Python)
🎯 这是一个用于构建MCP服务器的SKELETON/TEMPLATE,而不是一个生产应用程序!
MCP骨架是 通用模板 用于使用FastMCP构建模型上下文协议(MCP)服务器。该架构提供了MCP服务器层和业务逻辑之间的完全分离,使其成为任何领域的真正“即插即用”框架。
提供模块化架构,用于构建具有双传输模式(stdio+HTTP/SSE)和完整Kubernetes/AKS部署支持的生产就绪MCP服务器。
✨ 主要特点
- 清洁结构 –具有明确关注点分离的平面文件组织
- 双重运输 –支持stdio(IDE集成)和HTTP/SSE(部署)
- 结构化响应 –所有工具的一致JSON响应
- 类型安全 –用于请求/响应验证的Pydantic模型
- 示例工具 –计算器和天气服务作为参考实现
- 生产就绪 –包括Docker设置和配置管理
______________________________________________________________________
🏗️ 项目结构
mcp-skeleton/
├── mcp_server.py # Main MCP server with tool registrations
│
├── tools/ # Business Logic Layer ⚠️ REPLACE WITH YOUR OWN
│ ├── __init__.py # Package exports (required)
│ ├── calculator_tools.py # 📚 EXAMPLE Tool 1: Math operations (replace)
│ ├── weather_tools.py # 📚 EXAMPLE Tool 2: Weather data (replace)
│ ├── http_tools.py # 📚 EXAMPLE Tool 3: API integration (replace)
│ ├── text_tools.py # 📚 EXAMPLE Tool 4: Text processing (replace)
│ └── your_tool.py # ✨ YOUR Tool 5+: Custom business logic
│
├── utilities/ # Shared Utilities (Keep as-is or extend)
│ ├── __init__.py # Package exports (required)
│ ├── config.py # Configuration management
│ └── base_tools.py # Base classes for consistent responses
│
├── tests/ # Test Cases ⚠️ REPLACE WITH YOUR OWN
│ ├── __init__.py # Test package initialization
│ ├── conftest.py # Pytest fixtures and configuration
│ ├── test_calculator_tools.py # 📚 EXAMPLE: Calculator tests (replace)
│ ├── test_weather_tools.py # 📚 EXAMPLE: Weather tests (replace)
│ ├── test_text_tools.py # 📚 EXAMPLE: Text analysis tests (replace)
│ └── test_your_tools.py # ✨ YOUR tests for your tools
│
├── pyproject.toml # Poetry dependencies
├── poetry.lock # Locked dependencies (commit this!)
├── Dockerfile # Production container image
├── entrypoint.sh # Container entrypoint
├── .env.example # Environment configuration template
├── ARCHITECTURE.md # System architecture documentation
└── README.md # User guide and quick reference备注: -__init__.pyPython需要文件才能将目录识别为包 - 📚 示例文件是演示-替换为您自己的实现 - ✨ 你的文件代表了你应该为你的域创建什么 - 使用运行测试poetry run pytest
🚀 此模板提供什么
✅ 生产就绪基础设施 (保持原样)
- 采用FastMCP框架的MCP服务器
- 双传输:stdio(本地)+HTTP/SSE(容器)
- Docker容器化与安全最佳实践
- Kubernetes/AKS部署配置
- Pydantic的类型安全配置
- 全面的日志记录和健康检查
📚 示例工具 (替换为您的业务逻辑)
- 计算器、天气、HTTP、文本工具 仅演示
- 显示实现自己的工具的模式
- 服务器和业务逻辑之间的明确分离
⚠️ 开始之前
此模板包括您应该替换的4个示例工具:
| 示例工具 | 目的 | 替换为 |
|---|---|---|
| 🧮 计算器 | 数学运算演示 | 您的域逻辑 |
| 🌤️ 天气 | API集成模式 | 您的API调用 |
| 🌐 HTTP | HTTP客户端示例 | 您的集成 |
| 📝 文本 | 文本处理演示 | 您的数据处理 |
保留: 服务器基础设施、Docker、Kubernetes配置、实用程序\ 替换: 一切都在 tools/ 包含业务逻辑的目录
📋 模板功能
🏗️ 生产基础设施(保留这些)
- 模块化架构:干净的三层分隔(服务器→ 工具→ 公用事业)
- 双重运输模式:
- 标准:用于MCP客户端的本地开发(Cursor、VS Code、Claude Desktop) - HTTP/SSE:用于生产部署(Docker、Kubernetes、AKS、云)
- 企业级Docker:多阶段构建、非root用户、健康检查、安全最佳实践
- Kubernetes/AKS就绪:部署清单、横向扩展、可观察性、生产模式
- 类型安全:用于配置验证的Pydantic模型
- 诗歌依赖管理:带锁文件的现代Python打包
- 综合录井:具有可配置级别的结构化日志记录
📚 示例实现(替换这些)
- 4演示工具:计算器、天气(模拟)、HTTP客户端、文本分析
- 清晰的图案:显示如何构造异步函数、错误处理、响应
- 文档:解释架构的广泛评论
- 易于拆卸:只需删除示例工具并添加您自己的工具
🚀 快速开始
地方发展与诗歌
- 安装诗歌 (如果尚未安装):
curl -sSL https://install.python-poetry.org | python3 -- 安装依赖项:
poetry install- 运行服务器:
stdio模式 (光标、VS代码):
poetry run python mcp_server.py
# or use the entry point
poetry run mcp-skeletonHTTP/SSE模式 (适用于容器/网络):
poetry run python mcp_server.py --http服务器可用 http://localhost:8000/sse
Docker部署
- 塑造形象:
docker build -t mcp-skeleton:latest .- 运行容器:
docker run -d \
-p 8000:8000 \
-e LOG_LEVEL=INFO \
--name mcp-skeleton \
mcp-skeleton:latest- 测试端点:
curl http://localhost:8000/sseKubernetes/AKS部署
看 建筑.md 完整的Kubernetes部署示例包括:
- 部署清单
- 服务配置
- 入口设置
- 配置映射和秘密
- 资源限制和扩展
🛠️ 示例工具(⚠️ 用您的业务逻辑替换)
🎯 这些只是演示工具 -它们向您展示了模式,但不适用于生产使用。\ 删除它们或用特定于域的业务逻辑替换它们。
| 演示工具 | 显示内容 | 替换为您的。.. |
|---|---|---|
| 🧮 计算器 | 带验证的基本异步函数 | 数据库查询、计算、业务规则 |
| 🌤️ 天气 (mock) | 外部API模式(mock实现) | 真实的API集成,第三方服务 |
| 🌐 超文本传输协议 | 使用httpx | neneneba API聚合的HTTP客户端、webhook处理程序、集成 |
| 📝 文本 | 字符串处理和分析 | NLP、数据转换、ETL逻辑 |
你应该建造什么
将示例工具替换为 您的实际用例:
| 用例 | 您的工具 | 示例 |
|---|---|---|
| 数据库接口 | query_tools.py, analytics_tools.py | PostgreSQL查询、聚合 |
| ML/AI平台 | inference_tools.py, training_tools.py | 模型预测、嵌入 |
| 业务逻辑 | validation_tools.py, rules_tools.py | 定价引擎、审批工作流 |
| 数据处理 | etl_tools.py, transform_tools.py | 数据管道、格式转换器 |
| API网关 | integration_tools.py, orchestration_tools.py | 服务网格,API组合 |
工具响应格式
所有工具都返回结构化字典。根据您的用例设计您的响应:
# ❌ Example Tool Response (Calculator - Demo, replace this)
{
"operation": "add",
"operand_a": 5,
"operand_b": 3,
"result": 8
}
# ✅ Your Custom Tool Response (Database Query)
{
"query": "SELECT * FROM users WHERE active = true",
"results": [...],
"count": 42,
"execution_time_ms": 23
}
# ✅ Your Custom Tool Response (ML Inference)
{
"model": "sentiment-analyzer-v2",
"input_text": "This product is amazing!",
"prediction": "positive",
"confidence": 0.94,
"inference_time_ms": 156
}
# ✅ Your Custom Tool Response (Business Logic)
{
"rule": "pricing_engine",
"base_price": 100.0,
"discount_applied": 15.0,
"final_price": 85.0,
"currency": "USD"
}➕ 如何使用此模板
快速入门:用你的逻辑替换示例工具
架构原理:业务逻辑存在 tools/,服务器基础架构保持不变 mcp_server.py.\ 这种分离使模板保持通用,代码保持模块化。
选项1:干净的石板(建议用于新项目)
- 删除所有示例工具:
rm tools/calculator_tools.py tools/weather_tools.py tools/http_tools.py tools/text_tools.py- 创建您的第一个工具:
touch tools/your_domain_tools.py- 实施您的业务逻辑 (见下面的步骤1)
选项2:增量替换(保留示例作为参考)
在构建自己的工具时保留示例工具,然后稍后将其删除。
______________________________________________________________________
步骤1:创建工具实现(您的业务逻辑)
# tools/your_domain_tools.py (e.g., database_tools.py, ml_tools.py, etc.)
from typing import Dict, Any
async def your_business_function(input_param: str) -> Dict[str, Any]:
"""
Your actual business logic implementation.
Real-world examples:
- Database query: await db.execute(query)
- ML inference: model.predict(input_param)
- API call: await httpx.get(external_api)
- Business rule: calculate_pricing(input_param)
- Data processing: transform_data(input_param)
"""
# ✅ Replace this with YOUR ACTUAL implementation
# Example: Database query
# results = await db.query("SELECT * FROM table WHERE id = ?", input_param)
# Example: ML inference
# prediction = await ml_model.predict(input_param)
# Example placeholder (replace this):
processed_result = f"Processed: {input_param}"
return {
"input": input_param,
"result": processed_result,
"status": "success",
"metadata": {
"processed_at": "2024-01-01T00:00:00Z",
"version": "1.0"
}
}步骤2:导出 tools/__init__.py
# tools/__init__.py
# ❌ Remove or comment out example tools:
# from .calculator_tools import calculate_operation
# from .weather_tools import get_weather_data
# from .http_tools import fetch_api_data
# from .text_tools import text_analyzer
# ✅ Import YOUR tools:
from .your_domain_tools import your_business_function
# from .database_tools import query_database, insert_record
# from .ml_tools import run_inference, get_embeddings
# from .api_tools import fetch_external_data
__all__ = [
# Your tool functions
'your_business_function',
# 'query_database',
# 'insert_record',
# 'run_inference',
# 'get_embeddings',
# 'fetch_external_data',
]步骤3:注册 mcp_server.py (服务器层-仅限精简包装!)
# mcp_server.py
# ❌ Remove example tool imports:
# from tools.weather_tools import get_weather_data
# from tools.calculator_tools import calculate_operation
# ✅ Import YOUR tools:
from tools.your_domain_tools import your_business_function
# ❌ Delete or comment out example tool registrations:
# @mcp.tool()
# async def get_weather(city: str) -> dict: ...
# ✅ Register YOUR tool (server just routes, no business logic here!):
@mcp.tool()
async def your_tool_name(input_param: str) -> dict:
"""
Your tool description that MCP clients will see.
⚠️ IMPORTANT: This function should ONLY delegate to your business logic.
Do NOT put business logic here - keep it in tools/your_domain_tools.py
Args:
input_param: Description of your parameter
Returns:
Result from your business logic function
"""
# Server layer just delegates - all logic in tools/ directory
return await your_business_function(input_param)✅ 就是这样! 您的业务逻辑现在可以通过MCP协议访问。
关键架构点:
- ✅ 服务器层(
mcp_server.py):通用、可重复使用、仅限精简布线 - ✅ 业务逻辑(
tools/):您的领域特定代码,模块化和可测试 - ✅ 完全分离:易于独立维护、扩展和测试
🔧 配置
配置通过环境变量和 utilities/config.py:
# .env file (copy from .env.example)
SERVER_NAME=MCP Skeleton Server
SERVER_VERSION=0.1.0
LOG_LEVEL=INFO
MCP_SERVER_HOST=0.0.0.0
MCP_SERVER_PORT=8000要添加自定义配置,请执行以下操作:
- 更新
utilities/config.py:
class Settings(BaseSettings):
# Existing settings
server_name: str = "MCP Skeleton Server"
# Your new settings
my_api_key: Optional[str] = None
my_custom_setting: str = "default_value"- 增添
.env.example:
MY_API_KEY=your_api_key_here
MY_CUSTOM_SETTING=some_value- 在代码中使用:
from utilities.config import settings
api_key = settings.my_api_key📦 依赖项
通过诗歌管理 pyproject.toml:
核心依赖关系:
fastmcp ^0.2.0-FastMCP框架pydantic ^2.11.7-数据验证pydantic-settings ^2.9.1-设置管理httpx >=0.27-HTTP客户端python-dotenv ^1.0.0-环境变量uvicorn >=0.31.1-ASGI服务器
开发依赖关系:
pytest ^7.0.0-测试框架pytest-asyncio ^0.21.0-异步测试black ^24.0.0-代码格式ruff ^0.1.0-Lintingmypy ^1.0.0-类型检查
要更新依赖关系,请执行以下操作:
poetry update
poetry lock🧪 发展
代码质量
# Format code
poetry run black .
# Lint code
poetry run ruff check .
# Type checking
poetry run mypy mcp_server.py tools utilities
# Run all checks
poetry run black . && poetry run ruff check . && poetry run mypy mcp_server.py tools utilities测试
示例测试见 tests/ 显示测试异步函数模式的目录。
# Run all tests
poetry run pytest
# Run with verbose output
poetry run pytest -v
# Run with coverage
poetry run pytest --cov=tools --cov=utilities
# Run specific test file
poetry run pytest tests/test_calculator_tools.py
# Run tests matching a pattern
poetry run pytest -k "calculator"将示例测试替换为您自己的测试:
test_calculator_tools.py→ 业务逻辑测试test_weather_tools.py→ API集成测试test_text_tools.py→ 数据处理测试- 添加
conftest.py满足您特定需求的固定装置
🐳 Docker生产
构建论点
# Custom Poetry version
docker build --build-arg POETRY_VERSION=1.8.0 -t mcp-skeleton:latest .环境变量
docker run -d \
-p 8000:8000 \
-e SERVER_NAME="My MCP Server" \
-e LOG_LEVEL=DEBUG \
-e MCP_SERVER_PORT=8000 \
--name mcp-skeleton \
mcp-skeleton:latest安全特性
- ✅ 非root用户(
mcpuser,UID 10001) - ✅ 最小基础图像(
python:3.12-slim) - ✅ 多阶段诗意构建
- ✅ 健康检查端点
- ✅ 正确的文件权限
- ✅ 没有硬编码的秘密
☸️ Kubernetes/AKS
快速部署
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: mcp-skeleton
spec:
replicas: 2
selector:
matchLabels:
app: mcp-skeleton
template:
metadata:
labels:
app: mcp-skeleton
spec:
containers:
- name: mcp-skeleton
image: your-registry/mcp-skeleton:latest
ports:
- containerPort: 8000
env:
- name: LOG_LEVEL
value: "INFO"
resources:
requests:
memory: "128Mi"
cpu: "100m"
limits:
memory: "512Mi"
cpu: "500m"
livenessProbe:
httpGet:
path: /sse
port: 8000
initialDelaySeconds: 10
readinessProbe:
httpGet:
path: /sse
port: 8000
---
apiVersion: v1
kind: Service
metadata:
name: mcp-skeleton
spec:
selector:
app: mcp-skeleton
ports:
- port: 80
targetPort: 8000部署:
kubectl apply -f deployment.yaml
kubectl get pods -l app=mcp-skeleton看 建筑.md 用于完整的Kubernetes配置,包括Ingress、ConfigMaps、Secrets和扩展策略。
📊 监测和可观察性
日志
# Docker logs
docker logs -f mcp-skeleton
# Kubernetes logs
kubectl logs -f deployment/mcp-skeleton
kubectl logs -f pod/mcp-skeleton-xxx
# Stream logs from all replicas
kubectl logs -f -l app=mcp-skeleton健康检查
# Direct health check
curl http://localhost:8000/sse
# Check container health
docker inspect --format='{{.State.Health.Status}}' mcp-skeleton
# Kubernetes health
kubectl describe pod mcp-skeleton-xxx指标
集 LOG_LEVEL=DEBUG 详细日志记录:
export LOG_LEVEL=DEBUG
poetry run python mcp_server.py --http🚀 生产检查表
在部署到生产环境之前:
- \[\]生成
poetry.lock:poetry lock - \[\]更新版本
pyproject.toml - \[\]设置适当
LOG_LEVEL(信息或警告) - \[\]配置K8s中的资源限制
- \[\]设置监控和警报
- \[\]配置日志聚合
- \[\]向机密添加自定义API密钥
- \[\]测试健康检查端点
- \[\]配置水平吊舱自动缩放
- \[\]使用TLS设置入口
- \[\]运行安全扫描:
docker scan mcp-skeleton:latest - \[\]预期流量的负载测试
- \[\]记录自定义配置
📚 文档
- 建筑.md -完整的系统架构、图表、部署策略、安全性和可扩展性
- .env.示例 -具有所有可用选项的配置模板
- pyproject.toml -项目元数据和依赖关系
🤝 贡献
- 复刻仓库
- 创建要素分支:
git checkout -b feature/my-feature - 进行更改
- 运行质量检查:
poetry run black . && poetry run ruff check . - 承诺:
git commit -m 'Add my feature' - 推:
git push origin feature/my-feature - 打开拉取请求
📝 许可证
这个项目是开源的,可以在MIT许可证下使用。
🔗 资源
💡 快速命令
# Development
poetry install # Install dependencies
poetry run python mcp_server.py # Run stdio mode
poetry run python mcp_server.py --http # Run HTTP mode
poetry run mcp-skeleton # Run via entry point
# Docker
docker build -t mcp-skeleton . # Build image
docker run -p 8000:8000 mcp-skeleton # Run container
docker logs -f mcp-skeleton # View logs
# Kubernetes
kubectl apply -f deployment.yaml # Deploy
kubectl get pods # Check status
kubectl logs -f deployment/mcp-skeleton # Stream logs
kubectl scale deployment mcp-skeleton --replicas=3 # Scale
# Quality
poetry run black . # Format
poetry run ruff check . # Lint
poetry run mypy mcp_server.py # Type check______________________________________________________________________
🎯 入门检查表
在将此模板用于项目之前:
- \[\]更新
pyproject.toml您的姓名和电子邮件 - \[\]更新
SERVER_NAME在.env或utilities/config.py - \[\]删除或替换中的示例工具
tools/ - \[\]更新中的工具导入
tools/__init__.py - \[\]更新中的工具注册
mcp_server.py - \[\]更新中的MCP服务器说明
mcp_server.py - \[\]将您的自定义配置添加到
utilities/config.py - \[\]在中为您的工具编写测试
tests/ - \[\]运行测试以验证:
poetry run pytest - \[\]用您的项目详细信息更新此README.md
- \[\]本地测试
poetry run python mcp_server.py - \[\]构建并测试Docker镜像
- \[\]部署到目标环境
______________________________________________________________________
模板版本: 0.1.0\ 状态:生产就绪模板\ 部署:本地、Docker、Kubernetes、AKS兼容\ 许可证:麻省理工学院(或你的执照)
⚠️ 记住这是一个模板。更新中的项目元数据 pyproject.toml 与您的信息!
