MCP服务器Docker执行与客户端设置

提供基于Docker的MCP服务器部署方案,包含OAuth2认证、安全架构和客户端配置指南。

  • by ysys143
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 ysys143/mcp-docker

使用说明

MCP服务器Docker执行和客户端设置指南

项目结构

mcp-docker/
├── oauth2-demo/                    # 🔐 OAuth2 + Security Demo Server
│   ├── core/                       #   Core OAuth2 modules
│   │   ├── mcp_oauth2_server.py   #     Integrated OAuth2 FastAPI server
│   │   ├── oauth2_web_server.py   #     Separated OAuth2 web server
│   │   ├── oauth2_mcp_tools.py    #     OAuth2 MCP tools
│   │   └── oauth2_common.py       #     JWT token & auth common logic
│   ├── security/                   #   Security feature modules
│   │   ├── security_common.py     #     PII detection, encryption, audit logging
│   │   ├── secure_mcp_tools.py    #     Security-enabled MCP tools
│   │   └── pii_patterns.json      #     PII pattern definitions
│   ├── tests/                      #   Comprehensive test suite
│   │   ├── test_oauth2_demo.py    #     OAuth2 flow tests
│   │   ├── test_mcp_tools_direct.py #   Direct MCP tool tests
│   │   ├── test_mcp_integration.py #    MCP integration tests
│   │   ├── test_security_integration.py # Security integration tests
│   │   ├── keys/                  #     Test encryption keys
│   │   └── logs/                  #     Test audit logs
│   ├── config/                     #   Configuration files
│   │   └── Dockerfile             #     Dockerfile for OAuth2 server
│   ├── docs/                       #   OAuth2 detailed documentation
│   │   ├── README.md              #     Complete OAuth2 guide
│   │   └── README_SEPARATED.md    #     Separated structure explanation
│   ├── keys/                       #   JWT encryption key storage
│   ├── logs/                       #   Security audit logs
│   │   └── security_audit.log     #     Real-time security event logs
│   ├── README.md                   #   OAuth2 demo main documentation
│   └── __init__.py                 #   Python package initialization
├── docker/                         # Docker related files
│   └── dockerfile                  #   Dockerfile for main Python MCP server
├── scripts/                        # Execution scripts
│   └── run_mcp_server_with_logging.sh # MCP server logging script
├── examples/                       # Example files
│   └── custom_mcp_server.py        #   Basic MCP server example
├── .cursor/                        # Cursor IDE configuration
│   └── mcp.json                    #   MCP client configuration
├── .venv/                          # Python virtual environment (uv)
├── docker-compose.yml              # 🐳 Docker Compose integrated configuration
│                                   #   - mcp-python-server-docker (port 8080)
│                                   #   - mcp-oauth2-web-server (port 8081)
│                                   #   - mcp-node-server-docker
├── requirements.txt                # Python dependency packages
├── QUICK_START.md                  # Quick start guide
├── README_KOR.md                   # 📖 Korean main documentation
└── README.md                       # 📖 English main documentation (this file)

Korean Version(韩语版) Docker博客:如何构建和交付用于生产的MCP服务器

🏗️ 架构概述

总体系统架构

1️⃣ 主MCP服务器堆栈

  • Python MCP服务器:在端口8080上运行的主要MCP工具
  • Node.js MCP服务器:基于Node.js的工具,如Context7、顺序思维
  • Docker隔离:每台服务器都在独立的容器中安全运行

2️⃣ OAuth2+安全堆栈

  • OAuth2授权服务器:JWT代币发行(客户端_凭证流)
  • OAuth2资源服务器:受保护的MCP端点配置
  • PII检测和屏蔽:自动识别和保护个人身份信息
  • 数据加密:基于Fernet算法的敏感数据保护
  • 安全审计日志记录:实时跟踪所有安全事件

3️⃣ 综合测试系统

  • OAuth2流量测试:令牌发放、身份验证、受保护的资源访问
  • MCP工具测试:直接通话和集成场景测试
  • 安全集成测试:PII检测、加密、审计日志验证
  • 自动化CI/CD:持续验证所有功能

Docker网络配置

🔐 OAuth2和安全身份验证工作流

OAuth2客户端凭据流

此项目使用以下方式实现服务器到服务器身份验证 OAuth2客户端凭据授予.

1️⃣ 身份验证流程步骤

2️⃣ 详细实施

代币发行流程
# Step 1: Client authentication and token request
curl -X POST http://localhost:8081/oauth2/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials&client_id=mcp-client&client_secret=secret&scope=mcp.access"

# Response: JWT Token
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 1800,
  "scope": "mcp.access"
}
JWT令牌结构
{
  "header": {
    "alg": "HS256",
    "typ": "JWT"
  },
  "payload": {
    "sub": "mcp-client",           // Client ID
    "aud": "mcp-client",           // Target service
    "scope": "mcp.access",         // Permission scope
    "exp": 1704533400,             // Expiration time
    "iat": 1704531600,             // Issued at
    "jti": "unique-token-id"       // Unique token ID
  },
  "signature": "HMACSHA256(...)"   // Signature
}

🛡️ 多层安全架构

安全处理流程

安全层结构

1️⃣ PII(个人身份信息)检测系统

# PII Pattern Definitions (pii_patterns.json)
{
  "email": "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b",
  "phone": "\\b01[0-9]-?[0-9]{4}-?[0-9]{4}\\b",
  "korean_name": "\\b[가-힣]{2,4}\\b(?=님|씨|\\s|$)",
  "ssn": "\\b\\d{6}-?[1-4]\\d{6}\\b"
}

# Real-time PII detection and processing
def scan_and_process_pii(text: str, policy: str = "encrypt"):
    detected_pii = pii_detector.scan_text(text)
    
    if detected_pii:
        if policy == "encrypt":
            return encryption_service.encrypt(text)
        elif policy == "mask":
            return pii_detector.mask_pii(text)
        elif policy == "reject":
            raise SecurityException("Request rejected due to PII content")
    
    return text

2️⃣ 数据加密系统

# Using Fernet symmetric encryption
from cryptography.fernet import Fernet

class EncryptionService:
    def __init__(self):
        self.fernet = Fernet(self._load_or_generate_key())
    
    def encrypt(self, data: str) -> str:
        """Encrypt sensitive data"""
        encrypted = self.fernet.encrypt(data.encode())
        return base64.b64encode(encrypted).decode()
    
    def decrypt(self, encrypted_data: str) -> str:
        """Decrypt encrypted data"""
        decoded = base64.b64decode(encrypted_data.encode())
        decrypted = self.fernet.decrypt(decoded)
        return decrypted.decode()

3️⃣ 安全审计日志记录

# Real-time recording of all security events
def log_security_event(event_type: str, tool_name: str, 
                      user_id: str, client_id: str, 
                      contains_pii: bool, action_taken: str):
    log_entry = {
        "timestamp": datetime.utcnow().isoformat(),
        "event_type": event_type,
        "tool_name": tool_name,
        "user_id": user_id,
        "client_id": client_id,
        "contains_pii": contains_pii,
        "action_taken": action_taken,
        "parameter_count": len(params)
    }
    
    # Record in JSON format to security audit log
    security_logger.info(json.dumps(log_entry, ensure_ascii=False))

🔄 真实身份验证流程示例

MCP工具调用流程

数据处理流程

从游标调用MCP工具时

# 1. Cursor calls MCP tool in Docker container
docker exec -i mcp-python-server-docker uv run /workspace/oauth2-demo/core/oauth2_mcp_tools.py

# 2. MCP tool requests token from OAuth2 server
POST http://localhost:8081/oauth2/token
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&client_id=mcp-client&client_secret=secret&scope=mcp.access

# 3. OAuth2 server issues JWT token
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 1800
}

# 4. MCP tool accesses protected resources with token
GET http://localhost:8081/hello
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

# 5. Server validates token and responds
{
  "message": "Hello from MCP OAuth2 Demo!",
  "authenticated_client": "mcp-client",
  "timestamp": "2025-01-06T12:34:56"
}

🔒 安全策略选项

策略 描述 用例
encrypt 检测到PII时自动加密数据 敏感数据存储/传输
mask 屏蔽PII(****)并继续 记录、调试、预览
reject 检测到PII时立即拒绝请求 高安全性环境,合规性

Docker博客:如何构建和交付用于生产的MCP服务器

现有MCP(模型上下文协议)工作流的问题

  • 复杂管理:每个MCP客户端必须始终运行每个MCP服务器的副本,这消耗了过多的本地资源。客户端必须直接配置他们的服务器集,很难确定使用哪些MCP服务器,一些MCP服务器存在兼容性问题,无法在某些代理上工作。
  • 依赖地狱:MCP服务器只有在安装了所有运行时和依赖项的情况下才能工作。代理可以直接访问主机资源,这可能会带来安全风险。
  • 安全问题:API密钥必须在明文配置文件中手动配置,身份验证服务器管理繁琐。

通过将MCP服务器执行环境与Docker隔离,

  • 简化运行时:使用Docker可以通过单个运行时应用程序标准化MCP工具的安装,从而显著降低管理开销。
  • 隔离和安全Docker容器在沙盒代理方面非常有效,可以防止对主机资源的不必要访问。此外,可以安全地管理API密钥,而无需将其存储在明文配置文件中,并且可以考虑基于OAuth的服务器身份验证来增强安全性。
  • 容易获得:客户端可以通过单个端点访问MCP服务,为代理使用合适的工具完成任务提供了灵活性,即使用户没有明确安装它们。

设置方法

1.先决条件

2.Docker容器执行

使用Docker启动node20镜像。

docker run -d --name mcp-node-server-docker -it node:20-slim bash

备注:使用指定的容器名称 --name 选项(mcp-node-server-docker)在Docker主机中必须是唯一的。如果同名容器已在运行或停止,则无法启动新容器。在这种情况下,您必须停止并删除现有容器或使用其他名称。

3.MCP客户端配置(.cursor/MCP.json示例)

MCP客户端(例如Cursor)配置如何通过以下方式连接到Context7文档MCP服务器 mcp.json 文件。该文件通常位于客户端的配置目录中(例如。, ~/.cursor/mcp.json)并且是 没有复制到Docker容器中。

此设置使用 docker exec 直接调用容器内的MCP服务器脚本,因此没有单独的端口映射(-p 选项)是必需的。

验证容器内的命令执行(可选): 要检查MCP服务器是否已正确准备好在容器内执行,您可以访问容器,并尝试使用以下命令直接运行MCP服务器脚本:

docker exec -it mcp-node-server-docker bash
# (Inside the container) npx -y @upstash/context7-mcp@latest
# Or for a Python-based server:
# docker exec -it mcp-python-server-docker bash
# (Inside the container) uv run /app/custom_mcp_server.py

您可以配置 mcp.json 如下文件连接到Docker容器中运行的Context7 MCP服务器:

{
    "mcpServers": {
        "Context7 MCP (Docker exec)": {
            "command": "docker",
            "args": [
                "exec",
                "-i",
                "mcp-node-server-docker",
                "npx",
                "-y",
                "@upstash/context7-mcp@latest"
            ]
        },
        "sequential-thinking (Docker exec)": {
            "command": "docker",
            "args": [
                "exec",
                "-i",
                "mcp-node-server-docker",
                "npx",
                "-y",
                "@modelcontextprotocol/server-sequential-thinking"
            ]
        }
    }
}

4.停止和移除容器(可选)

要停止并删除容器,请使用以下命令:

docker stop mcp-node-server-docker
docker rm mcp-node-server-docker

遵循本指南,您可以在Docker环境中轻松部署和配置Context7文档MCP服务器,并将其与您的客户端一起使用。


5.定制构建案例

5.1.基于Node.js的MCP服务器自定义构建

Context7文档MCP服务器是基于Node.js的。您可以使用以下方法在Node.js环境中构建和运行服务器 Dockerfile.

FROM node:20-slim
WORKDIR /app
CMD ["tail", "-f", "/dev/null"]

在项目根目录中运行以下命令构建Docker镜像,其中 Dockerfile 位于。 用通用名称标记构建的图像,如 node-base-image.

docker build -t node-base-image .

使用构建的镜像运行Docker容器。

docker run -d --name mcp-node-server-docker -it node-base-image
  • -d:在分离模式下运行容器(在后台)。
  • --name mcp-node-server-docker:指定名称 mcp-node-server-docker 到集装箱。

    备注:使用指定的容器名称 --name 选项(mcp-node-server-docker)在Docker主机中必须是唯一的。如果同名容器已在运行或停止,则无法启动新容器。在这种情况下,您必须停止并删除现有容器或使用其他名称。

  • -it:为容器启用交互模式并分配TTY。在容器内执行命令时,这很有用。
  • node-base-image:要运行的Docker映像的名称。

5.2.pythonuv)基于MCP服务器的自定义构建(示例)

如果您正在使用基于Python的MCP服务器,并使用 uv,您可以配置类似的 Dockerfile 如下所述。本例假设a requirements.txt 文件存在于您的项目根目录中。

FROM python:3.10-slim-buster
WORKDIR /app

# Install necessary system packages and clean up cache
RUN apt-get update && apt-get install -y --no-install-recommends curl tar \
    && rm -rf /var/lib/apt/lists/*

# Install uv (recommended)
# Download the latest uv binary and install it to /usr/local/bin.
RUN curl -sSfL https://astral.sh/uv/install.sh | sh \
    && mv /root/.local/bin/uv /usr/local/bin/uv

# Install dependencies
COPY requirements.txt .
RUN uv pip install -r requirements.txt --system

# Copy and build MCP server script (if necessary)
# Example: Assuming you have a file named custom_mcp_server.py
COPY custom_mcp_server.py .
# custom_mcp_server.py should be an MCP server that handles JSON-RPC requests/responses via standard input (stdin) and standard output (stdout).

CMD ["tail", "-f", "/dev/null"]

在项目根目录中运行以下命令构建Docker镜像,其中 Dockerfile 位于。 用通用名称标记构建的图像,如 python-mcp-base-image.

docker build -t python-mcp-base-image .

使用构建的镜像运行Docker容器。

docker run -d --name mcp-python-server-docker -it python-mcp-base-image
  • -d:在分离模式下运行容器(在后台)。
  • --name mcp-python-server-docker:指定名称 mcp-python-server-docker 到集装箱。
  • -it:为容器启用交互模式并分配TTY。
  • python-mcp-base-image:要运行的Docker映像的名称。

以下是一个示例 mcp.json 在容器中运行基于Python的MCP服务器的客户端配置:

{
    "mcpServers": {
        "Python Weather MCP (Docker exec)": {
            "command": "docker",
            "args": [
                "exec",
                "-i",
                "mcp-python-server-docker",
                "uv",
                "run",
                "/app/custom_mcp_server.py"
            ]
        }
    }
}

添加此配置后,您应该重新启动MCP客户端(例如Cursor)以应用更改。

要停止并删除容器,请使用以下命令:

docker stop mcp-python-server-docker
docker rm mcp-python-server-docker

6.OAuth2+安全演示用法

6.1.使用Docker Compose运行全栈

# Run full stack (Python + Node.js + OAuth2 server)
docker-compose up -d

# Run specific services only
docker-compose up -d mcp-server oauth2-web-server

# Check service status
docker-compose ps

6.2.OAuth2服务器测试

# Check OAuth2 server status
curl http://localhost:8081/.well-known/openid-configuration

# Get token
curl -X POST http://localhost:8081/oauth2/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials&client_id=mcp-client&client_secret=secret&scope=mcp.access"

# Access protected endpoint
curl -H "Authorization: Bearer <token>" http://localhost:8081/hello

6.3.安全功能测试

# Activate virtual environment
source .venv/bin/activate

# Automated OAuth2 flow testing
python oauth2-demo/tests/test_oauth2_demo.py

# Direct MCP tool testing
python oauth2-demo/tests/test_mcp_tools_direct.py

# Security integration testing
python oauth2-demo/tests/test_mcp_integration.py

6.4.MCP客户端配置(光标)

将以下配置添加到 .cursor/mcp.json 文件:

{
    "mcpServers": {
        "Python MCP Server (Docker exec)": {
            "command": "docker",
            "args": [
                "exec",
                "-i",
                "mcp-python-server-docker",
                "uv",
                "run",
                "/workspace/custom_mcp_server.py"
            ]
        },
        "OAuth2 MCP Tools": {
            "command": "docker",
            "args": [
                "exec",
                "-i",
                "mcp-python-server-docker",
                "uv",
                "run",
                "/workspace/oauth2-demo/core/oauth2_mcp_tools.py"
            ]
        },
        "Security MCP Tools": {
            "command": "docker",
            "args": [
                "exec",
                "-i",
                "mcp-python-server-docker",
                "uv",
                "run",
                "/workspace/oauth2-demo/security/secure_mcp_tools.py"
            ]
        },
        "Context7 MCP (Docker exec)": {
            "command": "docker",
            "args": [
                "exec",
                "-i",
                "mcp-node-server-docker",
                "npx",
                "-y",
                "@upstash/context7-mcp@latest"
            ]
        }
    }
}

6.5.可用的MCP工具

OAuth2工具

  • get_oauth2_server_status:检查OAuth2服务器状态
  • create_oauth2_test_token:生成测试JWT令牌
  • get_oauth2_flow_guide:提供OAuth2流程指南
  • validate_oauth2_setup:验证完整的OAuth2设置

安全工具

  • test_pii_detection:测试PII检测和屏蔽
  • test_encryption:测试数据加密/解密
  • get_security_audit_log:查看安全审核日志
  • simulate_data_breach_detection:模拟数据泄露检测
  • generate_security_report:生成全面的安全报告

7.故障排除和调试

7.1.MCP服务器的一般问题

如果MCP服务器没有按预期工作,您可以检查Docker容器的日志来诊断问题。

  • 检查容器日志:

    docker logs <container_name>
    # Example:
    docker logs mcp-node-server-docker
    docker logs mcp-python-server-docker
    docker logs mcp-oauth2-web-server
    

    此命令显示自启动以来容器输出到标准输出(stdout)和标准错误(stderr)的所有日志。

  • Docker编写完整日志:

    # Full service logs
    docker-compose logs
    
    # Specific service logs
    docker-compose logs oauth2-web-server
    
    # Real-time log monitoring
    docker-compose logs -f
    

7.2.OAuth2相关故障排除

  • OAuth2服务器连接失败:

    # Check server status
    curl http://localhost:8081/.well-known/openid-configuration
    
    # Check container status
    docker ps | grep oauth2
    
    # Check OAuth2 server logs
    docker logs mcp-oauth2-web-server
    
  • 401未经授权的错误:

    • 令牌丢失或无效
    • 检查令牌过期
    • 验证范围是否正确(mcp.access)包容性
  • 400错误请求错误:

    • 验证内容类型是否为 application/x-www-form-urlencoded
    • 检查所需参数(grant_type, client_id, client_secret)包容性

7.3.安全功能调试

  • 检查安全审核日志:

    # Real-time security log monitoring
    tail -f oauth2-demo/logs/security_audit.log
    
    # Check logs for specific time period
    grep "2025-01-06T12" oauth2-demo/logs/security_audit.log
    
    # Check PII detection events only
    grep "contains_pii.*true" oauth2-demo/logs/security_audit.log
    
  • PII检测问题:

    # Check PII pattern file
    cat oauth2-demo/security/pii_patterns.json
    
    # Test PII detection
    python -c "
    from oauth2_demo.security.security_common import get_pii_detector
    detector = get_pii_detector()
    print(detector.scan_text('Test email: test@example.com'))
    "
    
  • 加密密钥问题:

    # Check encryption key directory
    ls -la oauth2-demo/keys/
    ls -la oauth2-demo/tests/keys/
    
    # Check key permissions
    chmod 600 oauth2-demo/keys/encryption.key
    

7.4.MCP工具连接问题

  • MCP工具无响应:

    # Test MCP tool directly
    docker exec -i mcp-python-server-docker uv run /workspace/oauth2-demo/core/oauth2_mcp_tools.py
    
    # Restart MCP server in Cursor
    # Ctrl+Shift+P → "MCP: Restart Server"
    
  • 虚拟环境问题:

    # Check virtual environment
    source .venv/bin/activate
    which python
    
    # Reinstall dependencies
    uv pip install -r requirements.txt
    

7.5.通过集成测试进行全系统状态检查

# Complete system status check script
./scripts/health_check.sh

# Or manual sequential testing
source .venv/bin/activate
python oauth2-demo/tests/test_oauth2_demo.py
python oauth2-demo/tests/test_mcp_tools_direct.py
python oauth2-demo/tests/test_mcp_integration.py

这种多层安全架构提供了一个完整的安全解决方案 OAuth2身份验证 + PII保护 + 数据加密 + 审计跟踪.