Skip to main content

E2B MCP Server (Python)

A production-grade Model Context Protocol server for executing code in secure, isolated E2B sandboxes.

Python 3.10+ License E2B

✨ Features

  • 🚀 Production-Ready: Comprehensive error handling, logging, and resource management
  • 🔒 Secure Isolation: Each sandbox runs in a separate, secure E2B environment
  • 🎯 Type-Safe: Full type annotations and Pydantic validation
  • 📊 Observable: Detailed logging and sandbox statistics
  • 🧹 Auto Cleanup: Automatic resource cleanup and graceful shutdown
  • 📦 Modular Design: Clean, maintainable code structure
  • ⚡ Easy to Use: Simple API with comprehensive documentation

🛠️ Available Tools

The server provides 10 powerful tools for sandbox interaction:

Tool Description
create_sandbox Create a new E2B sandbox with configurable timeout
run_code Execute Python code using Jupyter notebook syntax
run_command Run shell commands in the sandbox
read_file Read file contents from the sandbox
write_file Write content to files in the sandbox
list_files List files in a sandbox directory
get_sandbox_url Get URL for accessing sandbox on specific port
get_file_download_url Get download URL for a file in the sandbox
list_sandbox_ids List all active sandbox IDs and statistics
kill_sandbox Terminate and cleanup a sandbox

📋 Requirements

🚀 Quick Start

Installation

# Install with uv (recommended)
uv install

# Or with pip
pip install -e .

Configuration

  1. Get your E2B API key from e2b.dev
  2. Set up environment variables:
# Copy example config
cp .env.example .env

# Edit .env and add your API key
E2B_API_KEY=your_api_key_here

Running the Server

Standalone

# Run directly
python -m e2b_mcp_server

# Or programmatically
python -c "from e2b_mcp_server import main; import asyncio; asyncio.run(main())"

With Claude Desktop

Add to your Claude Desktop config:

MacOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "e2b-mcp-server": {
      "command": "uvx",
      "args": ["e2b-mcp-server"],
      "env": {
        "E2B_API_KEY": "your_api_key_here"
      }
    }
  }
}

⚙️ Configuration

Environment variables (see .env.example):

Variable Default Description
E2B_API_KEY (required) Your E2B API key
LOG_LEVEL INFO Logging level (DEBUG, INFO, WARNING, ERROR)
MAX_ACTIVE_SANDBOXES 10 Maximum concurrent sandboxes

Advanced Configuration

The server uses these constants (can be modified in constants.py):

  • DEFAULT_SANDBOX_TIMEOUT_MS: 300000 (5 minutes)
  • MAX_SANDBOX_TIMEOUT_MS: 3600000 (1 hour)

🏗️ Architecture

Module Structure

e2b_mcp_server/
├── constants.py      # Configuration constants
├── exceptions.py     # Custom exception classes
├── schemas.py        # Pydantic validation schemas
├── utils.py          # Utility functions
├── manager.py        # Sandbox lifecycle management
├── handlers.py       # Tool handler implementations
├── server.py         # MCP server setup and routing
└── __init__.py       # Package exports

Design Principles

  • Separation of Concerns: Each module has a single, clear responsibility
  • Type Safety: Full type hints and Pydantic validation
  • Error Handling: Comprehensive exception hierarchy
  • Resource Management: Automatic cleanup and lifecycle tracking
  • Testability: Modular design enables easy unit testing

Key Components

SandboxManager (manager.py)

Manages E2B sandbox lifecycle:

  • Creates and tracks sandboxes
  • Enforces resource limits
  • Handles cleanup on shutdown

Tool Handlers (handlers.py)

Implements business logic for each tool:

  • Validates inputs using schemas
  • Interacts with sandboxes
  • Returns standardized responses

Schemas (schemas.py)

Pydantic models for validation:

  • Type checking
  • Field validation
  • Auto-generated JSON schemas

🐛 Debugging

Use the MCP Inspector for debugging:

npx @modelcontextprotocol/inspector \
  uv \
  --directory . \
  run \
  e2b-mcp-server

The Inspector provides a web interface for:

  • Testing tool calls
  • Viewing request/response logs
  • Debugging connection issues

Enable Debug Logging

export LOG_LEVEL=DEBUG
python -m e2b_mcp_server

🧪 Development

Setup Development Environment

# Clone the repository
git clone https://github.com/yukkit/e2b-mcp-server
cd mcp-server/packages/python

# Install dependencies
uv install

# Copy environment config
cp .env.example .env
# Edit .env with your E2B_API_KEY

Project Structure

packages/python/
├── e2b_mcp_server/       # Main package
│   ├── __init__.py
│   ├── server.py         # MCP server
│   ├── manager.py        # Sandbox management
│   ├── handlers.py       # Tool handlers
│   ├── schemas.py        # Validation schemas
│   ├── constants.py      # Configuration
│   ├── exceptions.py     # Custom exceptions
│   └── utils.py          # Utilities
├── tests/                # Test suite (coming soon)
├── examples/             # Usage examples
├── .env.example          # Environment template
├── pyproject.toml        # Package configuration
└── README.md             # This file

Code Style

The codebase follows:

  • PEP 8 style guidelines
  • Type hints for all functions
  • Comprehensive docstrings
  • Modular, testable design

Running Tests

# Coming soon
pytest tests/

� Building and Packaging

Quick Build

# Method 1: Using Poetry (recommended)
poetry install
poetry build

# Method 2: Using build.sh script
./build.sh

# Generated files in dist/:
# - e2b_mcp_server-0.1.1-py3-none-any.whl
# - e2b_mcp_server-0.1.1.tar.gz

Local Installation Testing

# Install from built wheel
pip install dist/*.whl

# Test the installation
python -m e2b_mcp_server --help

Publishing to PyPI

# Configure PyPI token
poetry config pypi-token.pypi YOUR_TOKEN

# Publish
poetry publish

# Or build and publish together
poetry publish --build

For detailed packaging instructions, see PACKAGING.md.

�📊 Resource Management

The server includes production-grade resource management:

Sandbox Limits

  • Maximum concurrent sandboxes: Configurable (default: 10)
  • Automatic limit enforcement
  • Clear error messages when limits reached

Automatic Cleanup

  • Graceful shutdown handling
  • All sandboxes cleaned up on exit
  • Temporary sandboxes auto-cleaned after use

Monitoring

# Get current statistics
from e2b_mcp_server.manager import sandbox_manager

stats = sandbox_manager.get_stats()
# Returns: {
#   "active_sandboxes": 3,
#   "max_sandboxes": 10,
#   "sandbox_ids": ["sbx_123", "sbx_456", "sbx_789"]
# }

🔒 Security

  • Isolated Execution: Each sandbox runs in isolated E2B environment
  • Resource Limits: Configurable timeout and sandbox limits
  • API Key Protection: Credentials loaded from environment
  • Input Validation: All inputs validated with Pydantic

📄 API Reference

Tool Schemas

All tools use Pydantic schemas for validation. See schemas.py for details.

create_sandbox

{
  "secure": true,        # Optional, default: true
  "timeoutMs": 300000    # Optional, milliseconds
}

run_code

{
  "code": "print('hello')",      # Required
  "sandboxId": "sbx_..."          # Optional
}

run_command

{
  "command": "ls -la",            # Required
  "sandboxId": "sbx_...",         # Required
  "background": false             # Optional
}

get_file_download_url

{
  "filePath": "/path/to/file",      # Required
  "sandboxId": "sbx_...",           # Required
  "useSignatureExpiration": 300_000 # Optional, milliseconds, default: 300000 (5 minutes)
}

See inline documentation in schemas.py for complete API details.

🤝 Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests (when available)
  5. Submit a pull request

📝 License

Apache 2.0 - See LICENSE file for details.

💬 Support

🙏 Acknowledgments

Built with:

  • E2B - Secure code execution sandboxes
  • MCP - Model Context Protocol
  • Pydantic - Data validation
  • Python - Programming language

Made with ❤️ by the E2B team

Metadata

Release files for yukkit-e2b-mcp-server 0.6.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for yukkit-e2b-mcp-server 0.6.0
File Size Uploaded Provenance
yukkit_e2b_mcp_server-0.6.0.tar.gz 13.7 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for yukkit-e2b-mcp-server 0.6.0
File Interpreter ABI Platform
yukkit_e2b_mcp_server-0.6.0-py3-none-any.whl Python 3 none any Details

Total release size: 27.2 kB

Release files / yukkit_e2b_mcp_server-0.6.0.tar.gz

Download URL yukkit_e2b_mcp_server-0.6.0.tar.gz
Size 13.7 kB
Tags Source
SHA-256 checksum
How to use checksums
94af0704ffa9e7ee0039d81694f9e2285e526f01cf0214aa7b17ca3269cb52e3
BLAKE2b-256 checksum
How to use checksums
7339dbca4666b1094899a922331463cf162497bd4e5efd5ae719c4f00b1140eb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.5.1 CPython/3.12.12 Linux/6.8.0-1044-azure

Release files / yukkit_e2b_mcp_server-0.6.0-py3-none-any.whl

Download URL yukkit_e2b_mcp_server-0.6.0-py3-none-any.whl
Size 13.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4e082f60b3d790050470e01321ce3b13f2eb1c73679efcd811c86c4ec706b333
BLAKE2b-256 checksum
How to use checksums
e8e30ddc1bd511c121c55f6b65b2ecbf119ec2dc6c0d8b783fb117bb82e3ab02
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.5.1 CPython/3.12.12 Linux/6.8.0-1044-azure

Security for yukkit-e2b-mcp-server 0.6.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page