MCP安全网关

企业级MCP通信安全代理,提供认证、授权、请求验证、速率限制和全面审计日志功能。

  • by dopperdev
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 dopperdev/mvp-mcp

使用说明

MCP安全网关

企业级安全代理,用于模型上下文协议(MCP)通信。为MCP服务器提供认证、授权、请求验证、速率限制和全面的审计日志记录功能。

🚀 功能

核心安全功能

  • 🔐 认证与授权

    • 基于JWT的认证
    • 基于用户的身份访问控制列表(ACLs)
    • 细粒度权限(针对每个MCP服务器的读/写/执行权限)
    • 服务账户支持
  • 🛡️ 请求验证与清理

    • SQL注入检测与阻断
    • 防止路径遍历攻击
    • 命令注入检测
    • Base64编码的漏洞利用检测
    • JNDI注入检测(Log4Shell风格)
    • XXE(XML外部实体)防护
  • ⚡ 流量限制

    • 每个用户和MCP服务器的可配置限制
    • 使用Redis的令牌桶算法
    • 优雅降级并提供适当的错误信息
  • 📊 审计日志记录

    • 每个请求都记录了完整的上下文信息
    • PII(个人可识别信息)检测与自动屏蔽
    • 结构化JSON日志记录
    • 可配置的保留策略
    • 异步日志记录以提升性能
  • 📈 实时监控

    • 带有指标可视化的实时仪表板
    • 安全警报和通知
    • 请求跟踪和性能指标
    • 顶级用户和服务器分析
  • 🔍 Prometheus 指标

    • 请求计数器和直方图
    • 请求拦截追踪
    • 自定义指标端点

🏗️ 建筑学

┌─────────────┐
│   Client    │ (Claude Desktop, API clients, etc.)
└──────┬──────┘
       │ JWT Token
       ▼
┌─────────────────────────────────────────┐
│     MCP Security Gateway (Port 8000)     │
│  ┌────────────────────────────────────┐ │
│  │   1. JWT Authentication            │ │
│  │   2. Permission Check              │ │
│  │   3. Rate Limiting                 │ │
│  │   4. Security Validation           │ │
│  │      • SQL Injection               │ │
│  │      • Path Traversal              │ │
│  │      • Command Injection           │ │
│  │   5. Audit Logging                 │ │
│  └────────────────────────────────────┘ │
└──────┬──────────────────────────────────┘
       │
       ▼
┌─────────────┐     ┌─────────────┐
│ MCP Server  │     │ MCP Server  │
│ (Database)  │     │ (Filesystem)│
└─────────────┘     └─────────────┘

📋 先决条件

  • Docker 及 Docker Compose(推荐)
  • Python 3.11+(用于本地开发)
  • PostgreSQL 16+(包含在Docker Compose中)
  • Redis 7+(包含在Docker Compose中)

🚀 快速入门

使用 Docker Compose(推荐)

  1. 克隆仓库
git clone <repository-url>
cd mcp-security-gateway
  1. 创建环境文件
cp .env.example .env
# Edit .env and set JWT_SECRET and other variables
  1. 启动网关
docker-compose up -d
  1. 确认它正在运行
curl http://localhost:8000/health
  1. 获取身份验证令牌
curl -X POST http://localhost:8000/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"admin"}'
  1. 访问仪表板 在浏览器中打开 http://localhost:8000/dashboard

⚠️ 重要立即在生产环境中更改默认管理员密码!

🔧 配置

环境变量

创建一个 .env 基于文件的 .env.example:

# Database
DATABASE_URL=postgresql://mcp_user:mcp_password@postgres:5432/mcp_gateway

# Redis
REDIS_URL=redis://redis:6379/0

# Security
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
JWT_ALGORITHM=HS256
JWT_EXPIRATION_HOURS=24

# Gateway
GATEWAY_HOST=0.0.0.0
GATEWAY_PORT=8000
LOG_LEVEL=INFO

# Rate Limiting
RATE_LIMIT_REQUESTS=100
RATE_LIMIT_PERIOD=3600

# Audit
AUDIT_LOG_RETENTION_DAYS=30
PII_DETECTION_ENABLED=true

YAML 配置

编辑 config/default.yaml 对于高级配置:

# MCP Servers
servers:
  - name: "company-database"
    upstream_url: "http://localhost:9001"
    enabled: true
    allowed_tools: ["query", "schema"]
    blocked_patterns:
      - "DROP"
      - "DELETE FROM"

# User Policies
policies:
  - user: "data-scientist@company.com"
    servers: ["company-database"]
    permissions: ["read"]
    rate_limit: 100

📚 API 文档

认证

登录

POST /auth/login
Content-Type: application/json

{
  "username": "admin",
  "password": "admin"
}

# Response
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "expires_in": 86400
}

获取当前用户

GET /auth/me
Authorization: Bearer <token>

# Response
{
  "id": 1,
  "username": "admin",
  "email": "admin@example.com",
  "is_active": true,
  "is_admin": true
}

MCP 代理

转发MCP请求

POST /mcp/{server_name}
Authorization: Bearer <token>
Content-Type: application/json

{
  "jsonrpc": "2.0",
  "method": "tools/list",
  "params": {},
  "id": "1"
}

# Response
{
  "jsonrpc": "2.0",
  "result": { ... },
  "id": "1"
}

管理端点

列出MCP服务器

GET /admin/servers
Authorization: Bearer <admin-token>

获取审计日志

GET /admin/audit-logs?limit=100&blocked_only=false
Authorization: Bearer <admin-token>

获取安全警报

GET /admin/security-alerts?limit=50
Authorization: Bearer <admin-token>

获取仪表板指标

GET /admin/metrics
Authorization: Bearer <token>

OpenAPI 文档

交互式API文档可在以下地址获取:

  • Swagger UI:http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc(中文翻译为:ReDoc 文档界面:http://localhost:8000/redoc)

🧪 测试

运行所有测试

# Using Docker
docker-compose exec gateway pytest

# Local development
pytest

仅运行安全测试

pytest src/tests/test_security.py -v

带覆盖运行

pytest --cov=src --cov-report=html

预期测试结果

  • ✅ 50+项安全验证测试
  • ✅ SQL注入检测(10个测试用例)
  • ✅ 路径遍历检测(10个测试用例)
  • ✅ 命令注入检测(5个测试用例)
  • ✅ Base64漏洞检测
  • ✅ JNDI注入检测
  • ✅ 个人身份信息(PII)检测与遮蔽
  • ✅ 性能测试(验证时间 < 10毫秒)

🔒 安全最佳实践

1. 更改默认凭据

# In production, NEVER use default admin/admin
# Set strong passwords in environment variables
DEFAULT_ADMIN_PASSWORD=<strong-random-password>

2. 使用强JWT密钥

# Generate a strong secret
python -c "import secrets; print(secrets.token_urlsafe(32))"

# Set in .env
JWT_SECRET=<generated-secret>

3. 配置TLS/SSL

在生产环境中,使用带有TLS的反向代理(如nginx、Caddy):

server {
    listen 443 ssl;
    server_name gateway.example.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

4. 限制网络访问

使用防火墙规则限制访问:

# Only allow specific IPs
iptables -A INPUT -p tcp --dport 8000 -s 10.0.0.0/8 -j ACCEPT
iptables -A INPUT -p tcp --dport 8000 -j DROP

5. 启用审计日志监控

为可疑活动设置警报:

  • 同一用户多次请求被阻止
  • 高严重性安全警报
  • 非典型的访问模式

📊 监控与可观测性

Prometheus 指标

可用指标位于 /metrics 终端点;终点

# Request counters
mcp_gateway_requests_total{method="query", server="db", status="success"} 1234

# Request duration
mcp_gateway_request_duration_seconds{method="query", server="db"} 0.015

# Blocked requests
mcp_gateway_blocked_requests_total{reason="SQL Injection"} 42

仪表盘

访问实时仪表盘,请前往 http://localhost:8000/dashboard

特点:

  • 总请求数和被阻止的请求数
  • 活跃用户数量
  • 平均响应时间
  • 每分钟请求数
  • 顶级用户和服务器
  • 最近的安全警报

🚢 部署

Docker 生产环境部署

# Build production image
docker build -t mcp-gateway:latest .

# Run with production settings
docker run -d \
  --name mcp-gateway \
  -p 8000:8000 \
  --env-file .env.production \
  mcp-gateway:latest

Kubernetes 部署

# Apply Kubernetes manifests
kubectl apply -f k8s/namespace.yaml
kubectl apply -f k8s/configmap.yaml
kubectl apply -f k8s/secret.yaml
kubectl apply -f k8s/deployment.yaml
kubectl apply -f k8s/service.yaml

🐛 故障排除

网关无法启动

# Check logs
docker-compose logs gateway

# Check database connection
docker-compose exec postgres pg_isready

# Check Redis connection
docker-compose exec redis redis-cli ping

身份验证失败

# Verify JWT secret is set
echo $JWT_SECRET

# Check user exists
docker-compose exec postgres psql -U mcp_user -d mcp_gateway \
  -c "SELECT username, is_active FROM users;"

请求被意外阻止

# Check audit logs
curl -H "Authorization: Bearer $TOKEN" \
  http://localhost:8000/admin/audit-logs?blocked_only=true

# Check blocked patterns
docker-compose exec postgres psql -U mcp_user -d mcp_gateway \
  -c "SELECT * FROM blocked_patterns WHERE is_active = true;"

🤝 贡献(或:参与贡献)

欢迎贡献!请参阅 CONTRIBUTING.md 了解指南。

📄 许可证

此项目采用MIT许可证授权,请参阅LICENSE文件了解详情。

🙏 致谢

📞 支持

  • 问题:GitHub Issues(GitHub上的问题)
  • 文档: 文档/
  • 安全邮箱:security@example.com

🗺️ 路线图

v0.2.0(计划中)

  • [ ] 基于人工智能的异常检测
  • [ ] 多租户支持
  • [ ] 加密审计日志
  • [ ] 合规报告生成(SOC2,HIPAA)
  • [ ] MCP响应验证
  • [ ] 用于安全事件的Webhook警报

v1.0.0(未来版本)

  • [ ] 高级威胁情报集成
  • [ ] 用于模式检测的机器学习
  • GraphQL API支持
  • [ ] 高级缓存策略
  • [ ] 支持多区域部署

为MCP社区倾心打造