Hackaton MCP服务器
 
描述
用于使用Python和FastMCP开发模型上下文协议(MCP)服务器的生产就绪模板。该服务器为创建符合MCP的服务器提供了基础,并提供了工具、结构化日志记录、配置管理和容器化部署的全面示例。
该模板包括三个示例MCP工具:乘法计算器、代码审查提示生成器和红帽徽标资源处理程序。它展示了MCP服务器开发的最佳实践,包括正确的错误处理、健康检查、多种传输协议(HTTP、SSE、流式HTTP)、SSL支持和全面的开发工具。
建筑
系统架构
graph TB
subgraph "External Clients"
A[Claude Code/LLM Client]
B[Custom MCP Client]
C[Development Tools]
end
subgraph "Network Layer"
D[Load Balancer/Proxy]
E[SSL Termination]
end
subgraph "Template MCP Server"
subgraph "Application Layer"
F[FastAPI Application
api.py]
G[Health Check Endpoint
/health]
H[MCP Protocol Handler
/mcp]
end
subgraph "MCP Core"
I[TemplateMCPServer
mcp.py]
J[FastMCP Instance
Protocol Implementation]
K[Tool Registry
Dynamic Registration]
end
subgraph "Tool Layer"
L[Mathematical Tools
multiply_numbers]
M[Resource Tools
redhat_logo]
N[Prompt Tools
code_review_prompt]
O[Custom Tools
Extensible]
end
subgraph "Infrastructure Layer"
P[Configuration Management
settings.py]
Q[Structured Logging
pylogger.py]
R[Error Handling
Exception Management]
S[Asset Management
Static Resources]
end
subgraph "Transport Layer"
T[HTTP Transport]
U[SSE Transport]
V[Streamable HTTP Transport]
end
end
subgraph "External Dependencies"
W[Environment Variables
.env]
X[SSL Certificates
TLS/HTTPS]
Y[Static Assets
Images/Files]
Z[Container Runtime
Docker/Podman]
end
A --> D
B --> D
C --> D
D --> E
E --> F
F --> G
F --> H
H --> I
I --> J
J --> K
K --> L
K --> M
K --> N
K --> O
I --> P
I --> Q
I --> R
M --> S
F --> T
F --> U
F --> V
P --> W
E --> X
S --> Y
Z --> F
classDef client fill:#e3f2fd
classDef network fill:#f3e5f5
classDef application fill:#e8f5e8
classDef core fill:#fff3e0
classDef tools fill:#fce4ec
classDef infrastructure fill:#f1f8e9
classDef transport fill:#fef7e0
classDef external fill:#f5f5f5
class A,B,C client
class D,E network
class F,G,H application
class I,J,K core
class L,M,N,O tools
class P,Q,R,S infrastructure
class T,U,V transport
class W,X,Y,Z external控制流程
flowchart TD
A[MCP Client Request] --> B{Transport Protocol?}
B -->|HTTP/Streamable-HTTP| C[FastAPI App
api.py]
B -->|SSE| D[SSE App
create_sse_app]
C --> E[Health Check?]
D --> E
E -->|/health| F[Health Endpoint
Return Status]
E -->|/mcp| G[MCP Request Handler
FastMCP Instance]
G --> H{MCP Method Type?}
H -->|tools/list| I[List Available Tools
Return tool definitions]
H -->|tools/call| J[Tool Execution Router
mcp.py]
J --> K{Which Tool?}
K -->|multiply_numbers| L[Multiply Tool
multiply_tool.py]
K -->|read_redhat_logo_content| M[Logo Resource Tool
redhat_logo.py]
K -->|get_code_review_prompt| N[Code Review Prompt
code_review_prompt_tool.py]
L --> O[Validate Input
Check numeric types]
M --> P[Read Asset File
Base64 encode PNG]
N --> Q[Generate Prompt
Format code review template]
O --> R[Perform Calculation
a * b]
P --> S[Return Image Data
MIME type + base64]
Q --> T[Return Prompt Array
Structured messages]
R --> U[Log Result
Structured logging]
S --> U
T --> U
U --> V[Return Success Response
JSON format]
V --> W[Send to MCP Client
Complete request cycle]
F --> W
I --> W
X[Configuration Loading
settings.py] --> Y[Environment Variables
.env file]
Y --> Z[Pydantic Validation
Type checking & defaults]
Z --> AA[Server Startup
main.py]
AA --> C
AA --> D
BB[Error Handling] --> CC[Structured Logging
pylogger.py]
CC --> DD[JSON Output
Timestamp + Context]
O --> BB
P --> BB
Q --> BB
classDef request fill:#e3f2fd
classDef routing fill:#f3e5f5
classDef tools fill:#e8f5e8
classDef config fill:#fff3e0
classDef logging fill:#fce4ec
class A,B,E,H,K request
class C,D,G,J routing
class L,M,N,O,P,Q,R,S,T tools
class X,Y,Z,AA config
class BB,CC,DD logging编码结构
template-mcp-server/
├── template_mcp_server/ # Main package directory
│ ├── __init__.py
│ ├── src/ # Core source code
│ │ ├── __init__.py
│ │ ├── main.py # Application entry point & startup logic
│ │ ├── api.py # FastAPI application & transport setup
│ │ ├── mcp.py # MCP server implementation & tool registration
│ │ ├── settings.py # Pydantic-based configuration management
│ │ └── tools/ # MCP tool implementations
│ │ ├── __init__.py
│ │ ├── multiply_tool.py # Mathematical operations tool
│ │ ├── code_review_prompt_tool.py # Code review prompt generator
│ │ ├── redhat_logo.py # Base64 image resource handler
│ │ └── assets/ # Static resource files
│ │ └── redhat.png # Example image asset
│ └── utils/ # Shared utilities
│ ├── __init__.py
│ └── pylogger.py # Structured logging with structlog
├── tests/ # Comprehensive test suite (81+ tests)
│ ├── __init__.py # Test package initialization
│ ├── conftest.py # Pytest fixtures and configuration
│ ├── test_multiply_tool.py # Unit tests for multiply tool (12 tests)
│ ├── test_redhat_logo.py # Unit tests for logo tool (10 tests)
│ ├── test_code_review_prompt.py # Unit tests for prompt tool (14 tests)
│ ├── test_settings.py # Unit tests for configuration (20 tests)
│ ├── test_mcp_server.py # Unit tests for MCP server (15 tests)
│ └── test_integration.py # Integration tests (10 tests)
├── pyproject.toml # Project metadata & dependencies
├── Containerfile # Red Hat UBI-based container build
├── compose.yaml # Docker Compose orchestration
├── .env.example # Environment configuration template
├── .gitignore # Version control exclusions
├── .pre-commit-config.yaml # Code quality automation
└── README.md # Project documentation关键组件
main.py:具有配置验证、错误处理和uvicorn服务器启动的应用程序入口点api.py:FastAPI应用程序设置,包括传输协议选择(HTTP/SSE/流式HTTP)和健康端点mcp.py:使用FastMCP装饰器注册工具的核心MCP服务器类settings.py:使用Pydantic BaseSettings进行基于环境的配置,并进行验证tools/:演示算术、提示和资源访问模式的MCP工具实现utils/pylogger.py:使用具有综合处理器的structlog进行结构化JSON日志记录
当前MCP工具
multiply_numbers:演示具有错误处理功能的基本算术运算read_redhat_logo_content:显示base64编码的资源访问模式get_code_review_prompt:说明代码分析的提示生成
如何在本地运行代码
先决条件
- Python 3.12或更高版本
- 紫外线 (快速Python包安装程序和解析器)
设置
- 安装uv(如果尚未安装):
# On macOS/Linux:
curl -LsSf https://astral.sh/uv/install.sh | sh
# On MacOS using brew
brew install uv
# On Windows:
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
# Or with pip:
pip install uv- 导航到项目目录:
cd hackaton-mcp-server- 使用uv创建和激活虚拟环境:
uv venv
# Activate the virtual environment:
# On macOS/Linux:
source .venv/bin/activate
# On Windows:
.venv\Scripts\activate- 安装软件包和依赖项:
# Install in editable mode with all dependencies
uv pip install -e .- 配置环境变量:
cp .env.example .env
# Edit .env file with your configuration- 运行服务器:
# Using the installed console script
template-mcp-server
# Or directly with Python module
python -m template_mcp_server.src.main
# Or using uv to run directly
uv run python -m template_mcp_server.src.main配置选项
服务器配置通过环境变量进行管理:
| 变量 | 默认值 | 描述 |
|---|---|---|
MCP_HOST | 0.0.0.0 | 服务器绑定地址 |
MCP_PORT | 3000 | 服务器端口(1024-65535) |
MCP_TRANSPORT_PROTOCOL | streamable-http | 传输协议(http, sse, streamable-http) |
MCP_SSL_KEYFILE | None | SSL私钥文件路径 |
MCP_SSL_CERTFILE | None | SSL证书文件路径 |
PYTHON_LOG_LEVEL | INFO | 日志记录级别(DEBUG, INFO, WARNING, ERROR, CRITICAL) |
使用Podman
- 使用Podman Compose构建和运行:
podman-compose up --build- 或者手动构建:
podman build -t template-mcp-server .
podman run -p 3000:3000 --env-file .env template-mcp-server部署到OpenShift
请参阅 OpenShift部署指南 获取完整说明。
快速启动:
# Deploy to OpenShift namespace
make deploy openshift NAMESPACE=your-project-name
# Remove deployment
make undeploy openshift部署到托管平台(MPP)
使用租户配置部署到Red Hat托管平台:
# Deploy to MPP with tenant
make deploy mpp TENANT=ask-data
# Remove MPP deployment
make undeploy mpp TENANT=ask-data验证安装
- 健康检查:
curl http://localhost:3000/health- 测试MCP工具:
# Test multiply tool via MCP endpoint
curl -X POST "http://localhost:3000/mcp" \
-H "Content-Type: application/json" \
-d '{"method": "tools/call", "params": {"name": "multiply_numbers", "arguments": {"a": 5, "b": 3}}}'如何在本地测试代码
开发环境设置
- 安装开发依赖项:
uv pip install -e ".[dev]"- 安装预提交挂钩:
pre-commit install运行测试
该项目包括一个全面的测试套件,包含81多个测试,涵盖单元测试、集成测试和各种边缘案例。
- 运行所有测试:
pytest- 运行具有覆盖率报告的测试:
pytest --cov=template_mcp_server --cov-report=html --cov-report=term- 按类别运行测试:
# Unit tests only
pytest -m unit
# Integration tests only
pytest -m integration
# Slow running tests
pytest -m slow
# Tests requiring network access
pytest -m network- 运行特定的测试模块:
# Test individual components
pytest tests/test_multiply_tool.py -v
pytest tests/test_redhat_logo.py -v
pytest tests/test_code_review_prompt.py -v
pytest tests/test_settings.py -v
pytest tests/test_mcp_server.py -v
# Run integration tests
pytest tests/test_integration.py -v- 使用不同的输出格式运行测试:
# Verbose output with detailed test names
pytest -v
# Short traceback format
pytest --tb=short
# Quiet output (minimal)
pytest -q代码质量检查
- 使用Ruff进行装订和格式化:
# Check for issues
ruff check .
# Auto-fix issues
ruff check . --fix
# Format code
ruff format .- 使用MyPy进行类型检查:
mypy template_mcp_server/- 文档字符串验证:
pydocstyle template_mcp_server/ --convention=google- 运行所有预提交检查:
pre-commit run --all-files测试套件概述
该项目包括一个具有以下结构的综合测试套件:
| 测试类别 | 计数 | 描述 |
|---|---|---|
| 单元测试 | 71 | 使用模拟进行单个组件测试 |
| 集成测试 | 10 | 端到端工作流测试 |
| 总测试 | 81+ | 完整的测试覆盖率 |
测试文件:
test_multiply_tool.py-12项测试,涵盖算术运算、边缘情况、错误处理test_redhat_logo.py-10个测试,涵盖异步文件操作、base64编码、错误场景test_code_review_prompt.py-14项测试,涵盖提示生成、多种语言、格式化test_settings.py-20项测试,涵盖配置、环境变量、验证test_mcp_server.py-15个测试,涵盖服务器初始化、工具注册、错误处理test_integration.py-10项测试,涵盖完整的工作流程和系统集成
测试特点:
- ✅ 全面的错误处理验证
- ✅ 异步功能测试支持
- ✅ 模拟外部依赖关系
- ✅ 使用固定装置进行环境隔离
- ✅ 大数据性能测试
- ✅ 并发使用模拟
- ✅ 配置验证测试
手动测试
- 容器测试:
docker-compose up -d
curl -f http://localhost:3000/health
docker-compose down- SSL测试(如果已配置):
curl -k https://localhost:3000/health代码质量检查
在提交之前,请在本地运行这些检查:
# Install development dependencies
uv pip install -e ".[dev]"
# Run all pre-commit checks
pre-commit run --all-files
# Run tests with coverage
pytest --cov=template_mcp_server --cov-fail-under=80
# Run security checks
bandit -r template_mcp_server/
safety check
# Build and test container
docker build -t hackaton-mcp-server .
docker run --rm hackaton-mcp-server python -c "import template_mcp_server; print('OK')"如何做出贡献
开发工作流程
- 设置开发环境:
cd hackaton-mcp-server
uv venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
uv pip install -e ".[dev]"
pre-commit install- 按照我们的标准进行更改
- 运行全面测试:
# Code quality
ruff check . --fix
ruff format .
mypy template_mcp_server/
# Tests
pytest --cov=template_mcp_server
# Pre-commit validation
pre-commit run --all-files- 提交更改:
git add .
git commit -m "feat: descriptive commit message"编码标准
- Python风格:遵循PEP 8(由Ruff执行)
- 类型注解:所有公共职能和方法都需要
- 文档:所有公共API的谷歌风格文档字符串
- 测试:使用pytest编写新功能的测试
- 提交:使用常规提交格式(
feat:,fix:,docs:等等) - 错误处理:使用结构化日志记录和适当的异常处理
添加新的MCP工具
- 创建工具模块:
# template_mcp_server/src/tools/your_tool.py
async def your_tool_function(param: str) -> dict:
"""Your tool description.
Args:
param: Parameter description.
Returns:
dict: Result dictionary.
"""
# Implementation here
return {"result": "success"}- 在MCP服务器中注册:
# In template_mcp_server/src/mcp.py
from template_mcp_server.src.tools.your_tool import your_tool_function
def _register_mcp_tools(self) -> None:
self.mcp.tool()(your_tool_function) # Add this line- 添加测试:
# tests/test_your_tool.py
import pytest
from template_mcp_server.src.tools.your_tool import your_tool_function
@pytest.mark.asyncio
async def test_your_tool():
result = await your_tool_function("test_param")
assert result["result"] == "success"- 更新文档
添加新资源
- 将资产放置在:
template_mcp_server/src/tools/assets/ - 在以下位置创建资源处理程序:
template_mcp_server/src/tools/ - 注册地址:
template_mcp_server/src/mcp.py - 添加测试和文档
代码审查指南
- 自动检查必须通过(测试、抽检、类型检查)
- 文档应针对用户面临的变化进行更新
- 重大变更需要讨论和版本控制考虑
获取帮助
- 文档:检查现有文档和代码示例
- 测试:为虫子提供最少的繁殖条件
