AI集成安全协议

MCP Security提供企业级安全措施,用于构建安全的基于HTTP的AI集成,包括OAuth 2.1认证、TLS加密、输入验证和速率限制等功能。

  • by laksiri-fernando
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 laksiri-kingslake/mcp_security

使用说明

MCP安全:从易受攻击到强化

该项目包含使用具有全面安全措施的模型上下文协议(MCP)构建安全的基于HTTP的AI集成的工作示例。

概述

了解如何使用企业级安全保护您的MCP集成:

  • 使用PKCE身份验证实现OAuth 2.1
  • 配置TLS加密和安全标头
  • 添加全面的输入验证和净化
  • 实施速率限制和DDoS保护
  • 监控安全事件并处理事件
  • 将客户端安全地连接到受保护的MCP服务器

快速开始

用于开发(无TLS):

task setup && task generate-keys
task run-oauth    # Terminal 1
task run-server   # Terminal 2

用于生产(使用TLS):

task setup && task generate-keys && task generate-certs
task docker-up

先决条件

开发设置

  • Python 3.12.9(通过pyenv管理)
  • 依赖管理诗
  • Go Task实现构建自动化
  • 本地安装的OpenAI或Anthropic(Claude)或Ollama的API密钥
  • 用于速率限制的Redis服务器(可选)

Docker/生产设置

  • Docker和Docker Compose
  • 用于生产部署的有效SSL证书
  • 本地安装的OpenAI或Anthropic(Claude)或Ollama的API密钥

设置

开发设置(本地Python)

  1. 克隆此存储库

  2. 复制 .env.example 到 .env 并配置您的环境:

    cp .env.example .env
    
  3. 编辑 .env 要配置安全和LLM提供程序,请执行以下操作:

    • 设置OAuth配置
    • 添加API密钥
    • 如果使用分布式速率限制,请配置Redis URL
    • 设置TLS证书路径
  4. 运行安装任务:

    task setup           # Install Python dependencies
    task generate-keys   # Generate RSA keys for JWT
    task generate-certs  # Generate self-signed certificates
    

Docker设置(生产)

  1. 克隆此存储库

  2. 复制 .env.example.tls 到 .env 并为Docker进行配置:

    cp .env.example.tls .env
    
  3. 编辑 .env 要配置生产环境,请执行以下操作:

    • 设置API密钥(OPENAI_API_KEY、ANTHROPIC_API_KEY)
    • 配置JWT机密和OAuth凭据
    • 设置Redis密码和其他生产设置
  4. 运行Docker安装程序:

    task generate-keys   # Generate RSA keys for JWT
    task generate-certs  # Generate self-signed certificates
    task docker-build    # Build Docker images
    task docker-up       # Start all services with TLS
    

支持的LLM提供商

开放人工智能

  • 模型:gpt-4.1-2025-04-14
  • 客户端: src/secure_clients/openai_client.py
  • 任务: task run-openai-client
  • 需要:OpenAI API密钥(OPENAI_API_KEY in.env)
  • 特性:函数调用与工具结果显示

人类学(克劳德)

  • 模型:claude-sonnet-4-20250514
  • 客户端: src/secure_clients/anthropic_client.py
  • 任务: task run-anthropic-client
  • 需要:无烟煤API键(ANTHROPIC_API_KEY in.env)
  • 特性:工具执行与克劳德的分析和评论

Ollama(当地)

  • 模型:杰玛3:27
  • 需要:Olama已安装,gemma3:27b型号已拔出
  • 安装: brew install ollama (macOS)或查看 奥拉玛
  • 拉模式: ollama pull gemma3:27b
  • 备注:服务器支持Ollama,但尚未实现安全的客户端

LangChain(多提供商)

  • 客户端: src/secure_clients/langchain_client.py
  • 任务: task run-langchain-client
  • 需要:OpenAI API密钥(使用GPT-4作为底层LLM)
  • 特性:具有安全MCP工具集成和OAuth身份验证的ReAct代理

DSPy(多提供商)

  • 客户端: src/secure_clients/dspy_client.py
  • 任务: task run-dspy-client
  • 需要:OpenAI或Anthropic API密钥(可通过LLM_PROVIDER配置)
  • 特性:具有OAuth 2.1和TLS安全性的DSPy ReAct代理

LiteLLM(多提供商)

  • 客户端: src/secure_clients/litellm_client.py
  • 任务: task run-litellm-client
  • 需要:OpenAI或Anthropic API密钥(可通过LLM_PROVIDER配置)
  • 特性:LiteLLM与OAuth 2.1身份验证和JWT签名验证的集成

项目结构

.
├── src/
│   ├── __init__.py
│   ├── config.py                    # Security and LLM configuration
│   ├── main.py                      # Secure MCP server implementation
│   ├── secure_server.py             # Production-ready secure server
│   ├── oauth_server.py              # OAuth 2.1 authorization server
│   ├── secure_clients/
│   │   ├── __init__.py
│   │   ├── openai_client.py         # ✅ Secure OpenAI GPT-4 client
│   │   ├── anthropic_client.py      # ✅ Secure Anthropic Claude client
│   │   ├── langchain_client.py      # ✅ Secure LangChain integration
│   │   ├── dspy_client.py           # ✅ Secure DSPy integration
│   │   ├── claude_desktop.py        # ⏳ Secure Claude Desktop integration
│   │   └── litellm_client.py        # ✅ Secure LiteLLM integration
│   └── security/
│       ├── __init__.py
│       ├── auth.py                  # Authentication middleware
│       ├── validation.py           # Input validation
│       ├── rate_limiting.py        # Rate limiting implementation
│       └── monitoring.py           # Security monitoring
├── tests/
│   ├── test_security.py            # Security tests
│   └── test_clients.py             # Client integration tests
├── certificates/
│   ├── server.crt                  # TLS certificate
│   └── server.key                  # TLS private key
├── .env.example                    # Environment template
├── Taskfile.yml                    # Task automation
└── pyproject.toml                  # Poetry configuration

关键安全概念演示

  1. OAuth 2.1与PKCE:使用验证密钥进行代码交换的现代身份验证
  2. TLS加密:通过适当的证书管理进行端到端加密
  3. 输入验证:全面消毒和预防注射
  4. 速率限制:请求和AI令牌的多层速率限制
  5. 安全监控:实时威胁检测和事件响应
  6. 安全客户端集成:保护来自所有主要AI平台的连接

运行应用程序

快速比较

特性 开发模式 Docker模式(生产)
OAuth URL http://localhost:8080 https://localhost:8443
MCP网址 http://localhost:8000 https://localhost:8001
TLS/HTTPS ❌ 否 ✅ 是(通过nginx)
Redis 本地安装 Docker容器
复杂性 简单性 生产就绪
用例 开发/测试 生产/演示

选项1:开发模式(无Docker/nginx)

此模式直接使用Python运行服务,使用HTTP而不使用TLS。

环境变量(.env)

# Key differences for development mode:
OAUTH_TOKEN_URL=http://localhost:8080/token
MCP_SERVER_URL=http://localhost:8000/mcp
OAUTH_SERVER_HOST=localhost
OAUTH_ISSUER_URL=http://localhost:8080
MCP_SERVER_HOST=localhost
REDIS_URL=redis://localhost:6379

与任务一起运行

# Terminal 1: Start OAuth server
task run-oauth           # Runs on http://localhost:8080

# Terminal 2: Start MCP server
task run-server          # Runs on stdio (FastMCP 2.8+)

# Terminal 3: Run AI clients
task run-openai-client     # OpenAI GPT-4 client
task run-anthropic-client  # Anthropic Claude client
task run-langchain-client  # LangChain ReAct agent client
task run-dspy-client       # DSPy ReAct agent client
task run-litellm-client    # LiteLLM multi-provider client

无任务运行

# Terminal 1: OAuth server
poetry run python src/oauth_server.py

# Terminal 2: MCP server
poetry run python src/main.py

# Terminal 3: AI clients
poetry run python src/secure_clients/openai_client.py     # OpenAI
poetry run python src/secure_clients/anthropic_client.py  # Anthropic
poetry run python src/secure_clients/langchain_client.py  # LangChain
poetry run python src/secure_clients/dspy_client.py       # DSPy
poetry run python src/secure_clients/litellm_client.py    # LiteLLM

测试

# Test OAuth server
curl http://localhost:8080/

# Test with AI clients
task run-openai-client     # Test OpenAI integration
task run-anthropic-client  # Test Anthropic integration
task run-langchain-client  # Test LangChain integration
task run-dspy-client       # Test DSPy integration
task run-litellm-client    # Test LiteLLM integration

# Run all tests
task test

选项2:生产模式(使用Docker/nginx进行TLS)

此模式在Docker容器中运行所有服务,nginx提供TLS终止。

环境变量(.env)

# Key differences for Docker mode:
OAUTH_TOKEN_URL=https://localhost:8443/token
MCP_SERVER_URL=https://localhost:8001/mcp
OAUTH_SERVER_HOST=0.0.0.0
OAUTH_ISSUER_URL=https://localhost:8443
MCP_SERVER_HOST=0.0.0.0
REDIS_URL=redis://redis:6379
TLS_CA_CERT_PATH=  # Empty to skip cert verification for self-signed

与任务一起运行

# Start all services (nginx, OAuth, MCP, Redis)
task docker-up

# View logs
task docker-logs

# Run AI clients against Docker services
task run-openai-client     # OpenAI client with HTTPS
task run-anthropic-client  # Anthropic client with HTTPS
task run-langchain-client  # LangChain client with HTTPS
task run-dspy-client       # DSPy client with HTTPS
task run-litellm-client    # LiteLLM client with HTTPS

# Stop all services
task docker-down

无任务运行

# Build and start services
docker-compose build
docker-compose up -d

# View logs
docker-compose logs -f

# Run AI clients with Docker URLs
OAUTH_TOKEN_URL=https://localhost:8443/token \
MCP_SERVER_URL=https://localhost:8001/mcp \
TLS_CA_CERT_PATH= \
poetry run python src/secure_clients/openai_client.py

# Or Anthropic client
OAUTH_TOKEN_URL=https://localhost:8443/token \
MCP_SERVER_URL=https://localhost:8001/mcp \
TLS_CA_CERT_PATH= \
poetry run python src/secure_clients/anthropic_client.py

# Stop services
docker-compose down

测试

# Test OAuth server (via nginx HTTPS)
curl -k https://localhost:8443/

# Test direct container access (from host)
curl http://localhost:8080/  # Direct to OAuth container

# Debug containers
task docker-shell-oauth
task docker-shell-mcp

服务URL

  • OAuth服务器: https://localhost:8443(通过nginx进行TLS)
  • MCP服务器: https://localhost:8001(通过nginx进行TLS)
  • 直接OAuth: http://localhost:8080(集装箱码头,不对外使用)
  • 直接MCP: http://localhost:8000(集装箱码头,不对外使用)

可用任务

核心任务

  • task setup -设置Python环境并安装依赖项
  • task generate-keys -为OAuth JWT签名生成RSA密钥对
  • task generate-certs -生成自签名证书
  • task test -运行所有pytest测试
  • task format -黑色和Ruff格式代码
  • task clean -清理生成的文件

开发模式任务

  • task run-server -运行MCP服务器(stdio传输)
  • task run-oauth -在端口8080上运行OAuth服务器
  • task run-openai-client -运行OpenAI客户端(用于本地服务)
  • task run-anthropic-client -运行Anthropic Claude客户端(用于本地服务)
  • task run-langchain-client -运行LangChain ReAct代理客户端(用于本地服务)
  • task run-dspy-client -运行DSPy ReAct代理客户端(用于本地服务)
  • task run-litellm-client -运行LiteLLM多提供商客户端(用于本地服务)

Docker模式任务

  • task docker-build -构建Docker镜像
  • task docker-up -使用TLS启动所有服务
  • task docker-down -停止所有服务
  • task docker-logs -查看服务日志
  • task docker-restart -重新启动服务
  • task docker-clean -清理容器和体积
  • task docker-shell-oauth -调试OAuth容器
  • task docker-shell-mcp -调试MCP容器

安全检查列表

在部署到生产环境之前,请确保:

身份验证和授权

  • ✅ OAuth 2.1已实现PKCE
  • ✅ JWT令牌使用RS256和JWKS端点
  • ✅ 所有客户端中的JWT签名验证
  • ✅ 令牌过期时间设置为15-60分钟
  • ✅ 正确定义和执行范围

运输安全

  • ✅ 最低TLS 1.2,首选TLS 1.3(通过nginx)
  • ✅ 在所有客户端中启用SSL证书验证
  • ✅ mkcert证书,用于使用适当的CA包进行开发
  • ✅ HSTS标头,最小年龄为1年,最大年龄为1岁
  • ✅ 证书链验证工作

输入验证

  • ✅ 所有输入均已Pydantic模型验证
  • ✅ 用正则表达式阻止危险模式
  • ✅ SQL查询只使用参数化
  • ✅ 命令执行仅使用分配列表

速率限制和DDoS保护

  • ✅ 已实施请求速率限制
  • ✅ 基于令牌的AI操作限制
  • ✅ Redis分布式速率限制
  • ✅ 使用重试后正确的429响应

示例输出

这些例子表明:

  1. 使用OAuth 2.1设置生产就绪的安全MCP服务器
  2. 实施全面的输入验证和注射预防
  3. 为请求和AI令牌使用配置速率限制
  4. 将各种AI客户端安全地连接到受保护的服务器
  5. 监控安全事件并应对威胁

故障排除

发展模式问题

  • OAuth令牌错误:检查您的OAuth服务器配置和客户端凭据
  • 导入错误:运行 task setup 安装依赖项
  • 关键错误:运行 task generate-keys 创建RSA密钥对
  • 证书错误:运行 task generate-certs 创建自签名证书

Docker模式问题

  • TLS证书错误:确保证书有效且配置正确
  • 容器启动失败:使用以下命令检查Docker日志 task docker-logs
  • 端口冲突:确保端口80、443、8001、8080、8443可用
  • Redis连接错误:检查Redis容器状态和配置
  • 客户端连接失败:验证OAuth令牌和TLS设置

常见解决方案

  • 权限不足:确保证书文件具有正确的权限(600)
  • 利率限制问题:检查Redis连接和速率限制配置
  • API关键错误:验证.env文件中的OpenAI/Anthopic API密钥
  • 网络问题:检查Docker网络配置和容器连接

在模式之间切换

在开发模式和Docker模式之间切换时:

  1. 更新.env文件:更改比较表中显示的URL
  2. 停止所有服务:确保没有端口冲突
  3. 对于Docker→ 发展:停止Docker(task docker-down)在开始本地服务之前
  4. 为了发展→ 码头工人:启动Docker前停止本地服务(Ctrl+C)

了解更多