安全MCP服务器

一个以安全为先的Python实现的Model Context Protocol (MCP)服务器,提供安全的文件访问、操作和代码审查功能。

  • by Danor93
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 danor93/secure-mcp-server

使用说明

安全MCP服务器演示

Python中具有安全优先设计的全面模型上下文协议(MCP)服务器实现。

特性

MCP原语实现

  1. 资源:通过验证保护文件访问

    • 路径遍历保护
    • 文件大小限制(最大1MB)
    • 扩展白名单(.txt、.md、.json、.py、.js、.html、.css)
    • 安全目录限制
  2. 工具:安全的文件操作

    • safe_file_writer:写入带有净化功能的文件
    • secure_echo:带有防注射功能的回显文本
    • list_safe_files:列出安全目录中的文件
  3. 提示:以安全为重点的模板

    • secure_code_review:以安全为重点的代码分析
    • safe_documentation:生成安全文档

安全功能

  • 输入消毒:防止脚本注入和危险模式
  • 路径验证:防止目录遍历攻击
  • 文件限制:尺寸限制和扩展控制
  • 预防注射:检测并阻止常见的攻击模式
  • 错误处理:安全错误消息,无信息泄露

快速开始

选项1:Windows批处理脚本

  • 双击 scripts/run_mcp_server.bat -直接启动服务器
  • 双击 scripts/activate_env.bat -使用环境打开命令提示符

选项2:手动设置

  1. 创建虚拟环境:

    py -m venv mcp-server-env
    mcp-server-env\Scripts\activate
    
  2. 再进行:

    pip install -r requirements.txt
    
  3. 运行服务器:

    python start_server.py
    

选项3:直接Python路径

C:\path\to\project\mcp-server-env\Scripts\python.exe start_server.py

Claude桌面集成

  1. 从复制配置 config/claude_desktop_config.json
  2. 添加到您的Claude Desktop配置文件中:
    • 视窗: %APPDATA%\Claude\claude_desktop_config.json
    • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
    • Linux: ~/.config/Claude/claude_desktop_config.json
  3. 重新启动克劳德桌面

测试

  • 功能: python examples/test_server.py
  • 安全: python examples/demo_security.py
  • 文档:参见 docs/ 目录

安全考虑

预防攻击媒介:

  • 目录遍历: ../../../etc/passwd 尝试被阻止
  • 脚本注入: <script> 标签和JavaScript URL已清理
  • 命令注入:检测到并阻止了Shell命令模式
  • 文件过滤:仅限于安全目录访问
  • 快速注射:提示中的危险模式已过滤

实施的最佳实践:

  • 在每个入口点进行输入验证
  • 基于白名单的文件访问
  • 尺寸和类型限制
  • 综合录井
  • 优雅的错误处理
  • 信息披露最少

项目结构

mcp-server-python/
├── src/mcp_server/          # Main server code
│   ├── server.py           # MCP server implementation
│   ├── safe_files/         # Secure file storage
│   └── __init__.py
├── config/                 # Configuration files
│   └── claude_desktop_config.json
├── scripts/                # Helper scripts
│   ├── activate_env.bat    # Activate virtual environment
│   └── run_mcp_server.bat  # Start server directly
├── examples/               # Test and demo files
│   ├── test_server.py      # Functionality tests
│   └── demo_security.py    # Security demonstrations
├── docs/                   # Documentation
│   ├── SETUP.md           # Detailed setup guide
│   └── POWERSHELL_SETUP.md # PowerShell-specific setup
├── requirements.txt        # Python dependencies
├── start_server.py        # Server entry point
└── .gitignore            # Git ignore rules

此实现演示了如何构建安全的MCP服务器,以抵御常见的攻击媒介,同时为Claude Desktop用户提供有用的功能。