企业MCP服务器
一个生产就绪的模型上下文协议(MCP)服务器,具有多个免费的API集成,用于天气、IP地理位置、字典查找和货币汇率。
📋 目录
特性
🌟 企业级架构
- 多阶段Docker构建:使用UV包管理器进行优化,以实现快速构建
- Nginx反向代理:支持SSL/TLS的生产就绪
- YAML配置:具有Pydantic验证的类型安全配置
- 结构化日志记录:JSON和文本日志记录,带文件轮换
- 错误处理:具有自定义异常和重试逻辑的全面错误处理
- 类型安全:整个代码库中的完整类型提示
- 可扩展:易于使用基类添加新工具
🛠️ 免费API工具(无需API密钥)
- 天气信息 (
get_weather)
- 任何地点的当前天气状况 - 温度、湿度、风速、压力等。 - 由wttr.in提供技术支持
- IP地理定位 (
get_ip_info)
- 任何IP地址的地理位置数据 - 城市、国家、时区、坐标 - ISP和网络信息 - 由ipapi.co提供技术支持
- 字典查找 (
lookup_word)
- 单词定义、发音和示例 - 词类、同义词和反义词 - 由免费词典API提供支持
- 汇率 (
get_exchange_rate)
- 160+种货币的实时汇率 - 货币兑换 - 由exchangerate-api.com提供技术支持
项目结构
first_try_mcp/
├── src/
│ ├── servers/
│ │ └── http_server.py # Main MCP server
│ ├── clients/
│ │ └── http_client.py # Test client
│ ├── config/
│ │ └── settings.py # YAML configuration loader
│ ├── tools/
│ │ ├── base.py # Base tool classes
│ │ ├── weather.py # Weather tool
│ │ ├── ip_info.py # IP geolocation tool
│ │ ├── dictionary.py # Dictionary tool
│ │ └── exchange_rate.py # Exchange rate tool
│ └── utils/
│ ├── logger.py # Logging utilities
│ ├── http_client.py # HTTP client with retry
│ └── exceptions.py # Custom exceptions
├── tests/
│ └── test_tools.py # Unit tests
├── docs/
│ ├── API.md # API documentation
│ ├── GETTING_STARTED.md # Getting started guide
│ ├── DOCKER.md # Docker deployment guide
│ └── REFACTORING_SUMMARY.md # Refactoring notes
├── nginx/
│ ├── nginx.conf # Main Nginx config
│ ├── conf.d/ # Server configurations
│ └── README.md # Nginx setup guide
├── Dockerfile # Multi-stage Dockerfile
├── Dockerfile.prod # Production Dockerfile
├── docker-compose.yml # Development compose
├── docker-compose.prod.yml # Production compose
├── config.yaml # Configuration file
├── pyproject.toml
├── Makefile
└── README.md快速开始
先决条件
- Python 3.13+
- UV包管理器(推荐)或pip
- Docker和Docker Compose(用于容器化部署)
本地开发
# 1. Clone the repository
git clone
cd first_try_mcp
# 2. Install UV (if not installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
# 3. Create virtual environment and install dependencies
uv venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
uv pip install -e .
# 4. Copy and configure settings
cp config.yaml.example config.yaml
# Edit config.yaml as needed
# 5. Run the server
python -m src.servers.http_server
# 6. In another terminal, test the client
python -m src.clients.http_clientDocker部署
Docker开发
# Build and start services
make docker-build
make docker-up
# View logs
make docker-logs
# Stop services
make docker-down使用Docker进行生产
# Build and start production services
make docker-prod
# Stop production services
make docker-prod-down手动Docker命令
# Development
docker compose build
docker compose up -d
# Production
docker compose -f docker-compose.prod.yml up -d --buildAWS EC2部署
步骤1:启动EC2实例
- 登录AWS控制台
- 引导到https://console.aws.amazon.com - 使用您的凭据登录
- 启动EC2实例
- 转到EC2仪表板 - 点击“启动实例” - 名字: mcp-server-prod - 急性心肌梗死:Ubuntu服务器22.04 LTS(免费版) - 实例类型: t2.medium (建议的最小值)或 t2.large 为了获得更好的性能 - 密钥对:创建新的或选择现有的密钥对(保存 .pem 文件安全)
- 配置网络设置
- 创建或选择VPC - 启用“自动分配公共IP” - 安全组:使用规则创建新的安全组: - SSH(22)-仅限您的IP - HTTP(80)-0.0.0.0/0 - HTTPS(443)-0.0.0.0/0 - 自定义TCP(8000)-仅限您的IP(用于直接服务器访问)
- 配置存储
- 根卷:20 GB GP3(最低) - 建议:日志和数据为30GB
- 启动实例
- 点击“启动实例” - 等待实例状态为“正在运行”
步骤2:通过SSH连接到EC2
# Change permissions on your key pair file
chmod 400 your-key-pair.pem
# Connect to EC2 instance
ssh -i your-key-pair.pem ubuntu@步骤3:在EC2上安装依赖项
# Update system packages
sudo apt update && sudo apt upgrade -y
# Install Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo usermod -aG docker ubuntu
# Install Docker Compose
sudo apt install docker-compose -y
# Install Git
sudo apt install git -y
# Install UV (optional, for local development)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Logout and login again to apply docker group changes
exit重新连接到EC2:
ssh -i your-key-pair.pem ubuntu@步骤4:部署应用程序
# Clone your repository
git clone
cd first_try_mcp
# Copy and configure settings
cp config.yaml.example config.yaml
nano config.yaml # Edit configuration as needed
# For production, update server_host in config.yaml:
# server:
# host: "0.0.0.0"
# port: 8000
# Build and start services
docker compose -f docker-compose.prod.yml up -d --build
# Check if services are running
docker ps
# View logs
docker compose -f docker-compose.prod.yml logs -f步骤5:配置域和SSL(可选)
选项A:使用Let’s Encrypt进行SSL加密
# Install Certbot
sudo apt install certbot python3-certbot-nginx -y
# Stop Nginx container temporarily
docker compose -f docker-compose.prod.yml stop nginx
# Generate SSL certificate
sudo certbot certonly --standalone -d your-domain.com
# Copy certificates to project
sudo cp /etc/letsencrypt/live/your-domain.com/fullchain.pem nginx/ssl/
sudo cp /etc/letsencrypt/live/your-domain.com/privkey.pem nginx/ssl/
sudo chown ubuntu:ubuntu nginx/ssl/*.pem
# Update Nginx configuration
cd nginx/conf.d
cp mcp-server-ssl.conf.example mcp-server-ssl.conf
nano mcp-server-ssl.conf # Update server_name to your domain
# Restart services
docker compose -f docker-compose.prod.yml up -d选项B:使用AWS Route 53进行DNS
- 注册域名 在Route 53中或使用现有域
- 创建托管区域 对于您的域名
- 创建记录 指向EC2公共IP
- 等待DNS传播 (5-30分钟)
- 遵循选项A 设置SSL证书
步骤6:验证部署
# Test from EC2 instance
curl http://localhost/health
# Test from your local machine
curl http://
# Test MCP server (if port 8000 is open)
curl http://:8000/mcp步骤7:设置重启时的自动启动
# Create systemd service
sudo nano /etc/systemd/system/mcp-server.service添加以下内容:
[Unit]
Description=MCP Server Docker Compose
Requires=docker.service
After=docker.service
[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/home/ubuntu/first_try_mcp
ExecStart=/usr/bin/docker compose -f docker-compose.prod.yml up -d
ExecStop=/usr/bin/docker compose -f docker-compose.prod.yml down
User=ubuntu
[Install]
WantedBy=multi-user.target启用并启动服务:
# Reload systemd
sudo systemctl daemon-reload
# Enable service to start on boot
sudo systemctl enable mcp-server
# Start service
sudo systemctl start mcp-server
# Check status
sudo systemctl status mcp-server第8步:监控和维护
# View application logs
docker compose -f docker-compose.prod.yml logs -f mcp-server
# View Nginx logs
docker compose -f docker-compose.prod.yml logs -f nginx
# Monitor resource usage
docker stats
# Update application
cd /home/ubuntu/first_try_mcp
git pull
docker compose -f docker-compose.prod.yml up -d --build
# Clean up old images
docker system prune -aAWS部署的安全最佳实践
- SSH访问
- 只允许从您的IP地址进行SSH - 使用强密钥对 - 考虑使用AWS Systems Manager会话管理器而不是SSH
- 防火墙规则
- 最小化安全组中的开放端口 - 为不同的服务使用单独的安全组 - 启用AWS WAF进行DDoS保护
- SSL/TLS
- 在生产环境中始终使用HTTPS - 保持SSL证书更新 - 使用强密码套件(在Nginx中配置)
- 监控
- 启用CloudWatch监控 - 设置CPU/内存使用率高的警报 - 定期监控应用程序日志
- 备份
- 定期创建EC2 AMI快照 - 备份配置文件 - 将日志存储在S3或CloudWatch日志中
- 更新
- 保持系统包更新 - 定期更新Docker镜像 - 监控安全公告
EC2部署故障排除
无法通过SSH连接:
# Check security group allows your IP on port 22
# Verify key pair permissions: chmod 400 your-key.pem
# Check instance public IP hasn't changedDocker容器未启动:
# Check Docker service
sudo systemctl status docker
# View detailed logs
docker compose -f docker-compose.prod.yml logs
# Check disk space
df -h端口80/443不可访问:
# Check security group rules in AWS Console
# Verify Nginx is running
docker ps | grep nginx
# Check Nginx logs
docker logs mcp-nginx应用程序错误:
# Check server logs
docker logs mcp-server
# Verify config.yaml settings
cat config.yaml
# Restart services
docker compose -f docker-compose.prod.yml restart配置
配置
服务器使用基于YAML的配置和Pydantic验证。复制 config.yaml.example 到 config.yaml 并自定义:
server:
name: "Enterprise MCP Server"
host: "0.0.0.0"
port: 8000
transport: "http"
logging:
level: "INFO"
format: "json" # json or text
file: "logs/mcp_server.log"
api:
request_timeout: 30
max_retries: 3
retry_delay: 1.0
features:
enable_weather_tool: true
enable_ip_info_tool: true
enable_dictionary_tool: true
enable_exchange_rate_tool: true
development:
debug_mode: false
environment: "development"API工具
天气信息
# Using client
python -c "
from src.clients.http_client import MCPClient
import asyncio
async def get_weather():
client = MCPClient()
result = await client.call_tool('get_weather', {'location': 'Tokyo'})
print(result)
asyncio.run(get_weather())
"IP地理定位
# Current IP
curl -X POST http://localhost:8000/mcp \
-H "Content-Type: application/json" \
-d '{"tool": "get_ip_info", "arguments": {"ip_address": ""}}'
# Specific IP
curl -X POST http://localhost:8000/mcp \
-H "Content-Type: application/json" \
-d '{"tool": "get_ip_info", "arguments": {"ip_address": "8.8.8.8"}}'字典查找
result = await client.call_tool("lookup_word", {"word": "ephemeral"})货币兑换
# Convert 100 USD to JPY
result = await client.call_tool("get_exchange_rate", {
"base_currency": "USD",
"target_currency": "JPY",
"amount": 100
})发展
运行测试
# Install test dependencies
uv pip install pytest pytest-asyncio pytest-cov
# Run tests
make test
# With coverage
make test-coverage代码质量
# Format code
make format
# Lint code
make lint
# Type check
make type-check添加新工具
- 在中创建新文件
src/tools/(例如。,my_tool.py) - 从……继承……
BaseTool或APIBasedTool - 实施所需方法
- 注册
src/servers/http_server.py
例子:
from src.tools.base import APIBasedTool, ToolMetadata
from typing import Any, Dict
class MyTool(APIBasedTool):
def __init__(self):
super().__init__(base_url="https://api.example.com")
def _get_metadata(self) -> ToolMetadata:
return ToolMetadata(
name="my_tool",
description="Does something awesome",
version="1.0.0",
requires_api_key=False,
)
def validate_input(self, **kwargs: Any) -> None:
# Validate inputs
pass
async def execute(self, param: str, **kwargs: Any) -> Dict[str, Any]:
# Implement tool logic
url = self._build_url("/endpoint")
async with HTTPClient() as client:
data = await client.get(url)
return data文档
Makefile命令
# Server management
make run # Run the server
make run-server # Run the server (alias)
make run-client # Run the test client
# Docker commands
make docker-build # Build Docker images
make docker-up # Start containers
make docker-down # Stop containers
make docker-logs # View logs
make docker-restart # Restart containers
make docker-ps # List containers
make docker-clean # Clean up containers and volumes
make docker-prod # Start production containers
make docker-prod-down # Stop production containers
# Development
make test # Run tests
make test-coverage # Run tests with coverage
make format # Format code
make lint # Lint code
make clean # Clean cache files
make install # Install dependencies监控和日志
查看日志
# Application logs (local)
tail -f logs/mcp_server.log
# Docker logs
docker logs mcp-server -f
docker logs mcp-nginx -f
# All services
docker compose logs -f健康检查
# Check server health
curl http://localhost:8000/mcp
# Check via Nginx
curl http://localhost/性能调整
Docker资源
编辑 docker-compose.prod.yml:
services:
mcp-server:
deploy:
resources:
limits:
cpus: "2"
memory: 2G
reservations:
cpus: "1"
memory: 1GNginx优化
看 nginx/README.md 详细的优化指南包括:
- 工作进程和连接
- 缓存策略
- 压缩设置
- 速率限制
故障排除
导入警告:
# Ignore frozen runpy warnings, they don't affect functionality
python -W ignore::RuntimeWarning -m src.servers.http_server端口已在使用中:
# Check what's using the port
sudo lsof -i :8000
# Kill the process
sudo kill -9
Docker构建失败:
# Clean Docker cache
docker builder prune -a
# Rebuild without cache
docker compose build --no-cache免费API的速率限制:
- IP信息API(ipapi.co):每天最多1000个请求
- 使用特定IP而不是当前IP来减少请求
- 考虑升级到付费层以供生产使用
贡献
- 分叉存储库
- 创建要素分支(
git checkout -b feature/amazing-feature) - 进行更改
- 添加新功能的测试
- 运行测试和过梁
- 提交您的更改(
git commit -m 'Add amazing feature') - 推到分支(
git push origin feature/amazing-feature) - 打开拉取请求
许可证
MIT许可证-有关详细信息,请参阅许可证文件
支持
对于问题和疑问:
- GitHub问题:创建问题
- 文件:见
docs/目录 - 电子邮件:support@example.com
