MCP服务器安全执行工具

e2b-mcp是一个在E2B沙箱中安全运行MCP服务器的工具,提供隔离执行环境、自动资源管理和工具发现功能,适用于AI代理平台、SaaS应用和开发者工具等多种场景。

  • by cased
  • Python
  • 本地部署
  • 13 星标
  • 更新于
在 GitHub 查看 cased/e2b-mcp

使用说明

e2b mcp

跑 MCP(模型上下文协议) 服务器安全 苯甲酸雌二醇 沙箱。

e2b mcp提供了一种在隔离的云环境中执行mcp服务器的简单方法,可以安全执行不受信任的工具和代码。它们不是直接在主机系统上运行MCP服务器,而是在具有自动资源管理和清理功能的安全E2B沙盒中运行。

用例

我们建立了e2b mcp 用…完全覆盖的 可以代表用户运行MCP服务器,以及 与我们的DevOps代理集成。但是e2b-mcp有很多用例:

AI代理平台

  • 安全工具执行:让AI代理使用文件操作、git命令和web API,而不会影响您的基础设施
  • 用户特定沙盒:在隔离环境中使用每个用户的凭据和权限运行MCP服务器
  • 动态工具发现:按需发现并为代理提供新功能

SaaS应用程序

  • 多租户工具执行:在专用沙盒中安全执行用户请求的操作(文件处理、数据分析)
  • 用于MCP的API网关:将MCP工具作为具有内置安全性和隔离性的REST端点公开
  • 无服务器MCP:根据需求扩展MCP服务器实例,无需基础设施管理

开发工具和IDE

  • 代码执行环境:为在线IDE和编码平台提供安全的代码执行
  • 插件沙盒:在不影响主机环境的情况下安全运行不受信任的MCP插件
  • CI/CD集成:在具有受控访问的隔离环境中执行构建/测试工具

企业解决方案

  • 合规与安全:通过隔离所有工具执行来满足安全要求
  • 客户入职培训:让客户在部署之前安全地尝试工具和集成
  • 人工智能管理服务:在不暴露后端系统的情况下向客户提供人工智能功能

特性

  • 安全执行:在隔离的E2B沙箱中运行MCP服务器
  • CLI和API:命令行界面和Python API
  • 工具发现:自动从MCP服务器发现工具
  • 异步/同步支持:异步和同步执行模式
  • 自动清理:自动沙盒和资源管理
  • 包管理:自动安装MCP服务器依赖项
  • 多语言:通过CLI从任何语言使用或构建特定语言的包装器

安装

uv pip install e2b-mcp

先决条件

  1. E2B API密钥:从获取您的免费API密钥 e2b.dev
  2. 环境变量:设置 E2B_API_KEY 在您的环境中
export E2B_API_KEY="your_api_key_here"

快速开始

CLI使用情况

# Add a GitHub MCP server
e2b-mcp server add github \
  --command "npx -y @modelcontextprotocol/server-github" \
  --env GITHUB_PERSONAL_ACCESS_TOKEN=your_token

# Discover available tools
e2b-mcp tools list github

# Execute a tool
e2b-mcp tools execute github search_repositories \
  --params '{"query": "python", "per_page": 5}'

# Quick one-shot execution (no config save)
e2b-mcp quick "npx -y @modelcontextprotocol/server-filesystem /tmp" \
  list_directory --param path=/tmp

Python API

import asyncio
from e2b_mcp import E2BMCPRunner, ServerConfig

async def main():
    # Create runner
    runner = E2BMCPRunner()

    # Add MCP server
    runner.add_server(ServerConfig(
        name="filesystem",
        command="npx -y @modelcontextprotocol/server-filesystem /tmp",
        description="File system operations"
    ))

    # Discover tools
    tools = await runner.discover_tools("filesystem")
    print(f"Found {len(tools)} tools")

    # Execute a tool
    result = await runner.execute_tool(
        "filesystem",
        "write_file",
        {"path": "/tmp/example.txt", "content": "Hello World!"}
    )
    print(result)

# Run async code
asyncio.run(main())

📖 CLI文档

服务器管理

# Add a new MCP server configuration
e2b-mcp server add <name> --command "<command>" [options]

# List all configured servers
e2b-mcp server list [--json]

# Remove a server configuration  
e2b-mcp server remove <name> [--yes]

添加服务器选项:

  • --command:运行MCP服务器的命令(必需)
  • --env KEY=VALUE:环境变量(可以多次使用)
  • --package:要安装的Python包
  • --description:服务器描述
  • --timeout:超时时间(分钟)(默认值:10)

工具操作

# List tools from a configured server
e2b-mcp tools list <server_name> [--json]

# Execute a tool
e2b-mcp tools execute <server_name> <tool_name> [options]

执行工具选项:

  • --params:工具参数为JSON字符串
  • --param key=value:单个参数(可多次使用)
  • --json:输出原始JSON响应

快速执行

# Execute without saving server config
e2b-mcp quick "<command>" <tool_name> [options]

快速执行选项:

  • --params:工具参数为JSON字符串
  • --param key=value:单个参数
  • --env KEY=VALUE:环境变量
  • --json:输出原始JSON响应

配置

# Show current configuration
e2b-mcp config [--show]

# Edit configuration file
e2b-mcp config --edit

# Reset all configuration
e2b-mcp config --reset

CLI示例

# GitHub integration
export GITHUB_TOKEN="your_token"
e2b-mcp server add github \
  --command "npx -y @modelcontextprotocol/server-github" \
  --env GITHUB_PERSONAL_ACCESS_TOKEN=$GITHUB_TOKEN

e2b-mcp tools execute github search_repositories \
  --params '{"query": "e2b", "per_page": 3}'

# Filesystem operations
e2b-mcp server add fs \
  --command "npx -y @modelcontextprotocol/server-filesystem /tmp"

e2b-mcp tools execute fs write_file \
  --param path=/tmp/test.txt \
  --param content="Hello CLI!"

e2b-mcp tools execute fs read_file \
  --param path=/tmp/test.txt

# Using quick execute for one-offs
e2b-mcp quick "npx -y @modelcontextprotocol/server-filesystem /tmp" \
  list_directory --param path=/tmp --json

配置存储在 ~/.e2b-mcp/servers.json 并且可以在不同的环境中共享。

配置

服务器配置

from e2b_mcp import ServerConfig

# Method 1: Using ServerConfig class
config = ServerConfig(
    name="my_server",
    command="python -m my_mcp_server --stdio",
    package="my-mcp-server-package",  # Optional
    description="My custom MCP server",
    timeout_minutes=10,
    env={"DEBUG": "1"}  # Optional environment variables
)
runner.add_server(config)

# Method 2: Using dictionary
runner.add_server_from_dict("my_server", {
    "command": "python -m my_mcp_server --stdio",
    "package": "my-mcp-server-package",
    "description": "My custom MCP server",
    "timeout_minutes": 10,
    "env": {"DEBUG": "1"}
})

配置参数

  • 名字:MCP服务器的唯一标识符
  • 命令:启动MCP服务器的命令
  • 包裹:要安装的Python包(可选)
  • 描述:人类可读的描述
  • 超时_分钟:沙盒超时(默认值:10分钟)
  • 环境:环境变量(可选)

api参考

E2BMCPRunner

用于管理E2B沙盒中MCP服务器的主类。

方法

__init__(api_key: Optional[str] = None)

使用E2B API密钥初始化运行程序。

add_server(config: ServerConfig) -> None

添加MCP服务器配置。

add_server_from_dict(name: str, config_data: Dict[str, Any]) -> None

从字典中添加MCP服务器配置。

list_servers() -> List[str]

列出所有已配置的服务器名称。

async discover_tools(server_name: str) -> List[Tool]

从MCP服务器发现工具。

async execute_tool(server_name: str, tool_name: str, params: Dict[str, Any]) -> Dict[str, Any]

在MCP服务器上执行工具。

execute_tool_sync(server_name: str, tool_name: str, params: Dict[str, Any]) -> Dict[str, Any]

同步包装器 execute_tool.

async create_session(server_name: str) -> AsyncContextManager[Session]

创建托管MCP会话(高级用法)。

例子

基本工具执行

import asyncio
from e2b_mcp import E2BMCPRunner

async def main():
    runner = E2BMCPRunner()

    # Add a simple test server
    runner.add_server_from_dict("test", {
        "command": "python /tmp/test_mcp_server.py",
        "description": "Test server with basic tools"
    })

    # Execute tools
    time_result = await runner.execute_tool("test", "get_time", {"format": "iso"})
    echo_result = await runner.execute_tool("test", "echo", {"text": "Hello!"})

    print(f"Time: {time_result}")
    print(f"Echo: {echo_result}")

asyncio.run(main())

同步使用

from e2b_mcp import E2BMCPRunner

runner = E2BMCPRunner()
runner.add_server_from_dict("test", {
    "command": "python /tmp/test_mcp_server.py"
})

# Synchronous execution
result = runner.execute_tool_sync("test", "get_time", {"format": "readable"})
print(result)

会话管理(高级)

async def advanced_usage():
    runner = E2BMCPRunner()
    runner.add_server_from_dict("filesystem", {
        "command": "python -m mcp_server_filesystem --stdio",
        "package": "mcp-server-filesystem"
    })

    # Manage session lifecycle manually
    async with runner.create_session("filesystem") as session:
        print(f"Session ID: {session.session_id}")
        print(f"Sandbox ID: {session.sandbox_id}")

        # Session automatically cleaned up when exiting context

支持的MCP服务器

e2b-mcp可与支持标准mcp协议的任何mcp服务器配合使用。一些流行的服务器包括:

  • mcp服务器文件系统:文件系统操作
  • mcp服务器git:Git存储库管理
  • mcp服务器sqlite:SQLite数据库操作
  • mcp服务器勇敢搜索:Web搜索功能
  • mcp服务器松弛:Slack集成

安全

e2b-mcp提供了多个安全层:

  1. 沙箱隔离:所有MCP服务器都在隔离的E2B沙箱中运行
  2. 网络隔离:沙盒具有受控的网络访问
  3. 资源限制:自动CPU、内存和时间限制
  4. 自动清理:沙盒在使用后会自动销毁
  5. 无主机访问权限:MCP服务器无法访问您的本地文件系统

错误处理

from e2b_mcp import E2BMCPRunner, MCPError

try:
    runner = E2BMCPRunner()
    result = await runner.execute_tool("nonexistent", "tool", {})
except MCPError as e:
    print(f"MCP operation failed: {e}")
except ValueError as e:
    print(f"Configuration error: {e}")

发展

地方发展

# Clone the repository
git clone https://github.com/cased/e2b-mcp.git
cd e2b-mcp

# Install in development mode
pip install -e ".[dev]"

# Format and lint code using the provided script
./scripts/format

# Or run individual tools manually
black .
ruff check .

开发脚本

该项目在 scripts/ 目录:

设置脚本格式(./scripts/format)

自动格式化和lint代码库:

  • 跑 black 用于代码格式化
  • 跑 ruff check --fix --unsafe-fixes 用于起毛和自动修复
  • 跑 ruff format 用于进口分拣
  • 跑 mypy 用于类型检查
./scripts/format

发布脚本(./scripts/release)

通过全面的飞行前检查处理完整的专业放行流程:

  • 版本验证:确保提供的版本匹配 pyproject.toml
  • 飞行前检查:验证git状态、分支和所需工具
  • 环境验证:检查PyPI凭据和依赖关系
  • 构建和发布:自动构建包并发布到PyPI
  • Git标记:创建git标签并将其推送到GitHub
  • GitHub发布:可选择创建带有自动生成注释的GitHub版本

发布的先决条件:

# 1. Set PyPI credentials (required)
export TWINE_USERNAME=__token__
export TWINE_PASSWORD='your-pypi-api-token'

# 2. Install required tools
pip install build twine

# 3. Optional: Install GitHub CLI for release creation
brew install gh  # or equivalent for your system

发布流程:

# 1. Update version in pyproject.toml manually
# version = "0.2.0"

# 2. Commit the version change
git add pyproject.toml
git commit -m "Bump version to 0.2.0"

# 3. Run release script with the same version
./scripts/release 0.2.0

发布脚本的作用:

  • ✅ 验证版本匹配 pyproject.toml
  • ✅ 检查干净的git状态和正确的分支
  • ✅ 验证PyPI凭据和所需工具
  • ✅ 使用以下内容构建包 python -m build
  • ✅ 发布到PyPI twine upload
  • ✅ 创建并推送git标签(v0.2.0)
  • ✅ 可选择创建带有自动生成注释的GitHub版本
  • ✅ 处理干净构建的虚拟环境停用/重新激活

安全功能:

  • 破坏性操作前有多个确认提示
  • 开始前验证所有先决条件
  • 干净的错误处理和有用的消息
  • 安全的虚拟环境处理

测试

该包包括单元测试和集成测试:

单元测试

运行不需要E2B API访问的快速单元测试:

# Run only unit tests (fast)
pytest tests/test_basic.py

# Run with verbose output
pytest tests/test_basic.py -v

集成测试

运行全面的集成测试,创建真正的E2B沙盒:

# Set E2B API key (required for integration tests)
export E2B_API_KEY="your_api_key"

# Run integration tests
pytest tests/test_integration.py -v

# Run all tests including integration
pytest -v

测试命令

# Run only unit tests (no E2B API key needed)
pytest -m "not integration"

# Run only integration tests (E2B API key required)
pytest -m integration

# Run all tests
pytest

# Run with coverage
pytest --cov=e2b_mcp

# Run specific test
pytest tests/test_integration.py::TestE2BMCPIntegration::test_tool_discovery -v

集成测试类别

  • 基本功能:会话创建、工具发现、工具执行
  • 软件包安装:测试具有pip依赖关系的MCP服务器
  • 环境变量:测试自定义环境配置
  • 错误处理:测试故障场景和清理
  • 演出:并行会议和快速创建/销毁
  • 压力测试:多个同时操作

备注:集成测试创建真正的E2B沙盒,可能需要几分钟才能完成。它们需要有效的E2B API密钥。

运行示例

# Set E2B API key
export E2B_API_KEY="your_api_key"

# Run basic example
python examples/basic_usage.py

贡献

欢迎投稿!请随时提交拉取请求。

许可证

MIT许可证-请参阅 许可证 文件以获取详细信息。

相关项目