Overview
Secure sandboxed code execution for AI agents with Python, Node.js, and more.
Setup
Run with npx:
npx -y @modelcontextprotocol/server-e2bConfiguration
E2B_API_KEY environment variableDocumentation
E2B MCP
Overview
E2B MCP is a Model Context Protocol server that provides secure, sandboxed code execution for AI agents. E2B (Environment to Build) offers isolated execution environments for Python, Node.js, and other languages, enabling AI agents to run code safely without risking host system security.
Unlike local code execution, E2B runs code in cloud-based sandboxed containers with network isolation, resource limits, and automatic cleanup. This makes it ideal for executing untrusted code, running data analysis, generating visualizations, and more.
Features
- Sandboxed Execution: Isolated containers for secure code running
- Multi-Language Support: Python, Node.js, and more
- Package Installation: Install packages at runtime
- File System: Read/write files in sandbox
- Network Access: Optional internet access for API calls
- Resource Limits: CPU, memory, and time limits
- Automatic Cleanup: Sandboxes auto-destroy after use
- Real-Time Output: Stream stdout/stderr
Installation
npx -y @modelcontextprotocol/server-e2b
Configuration
Add to your claude_desktop_config.json:
{
"mcpServers": {
"e2b": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-e2b"],
"env": {
"E2B_API_KEY": "YOUR_E2B_API_KEY"
}
}
}
}
Getting an E2B API Key
- Go to E2B Dashboard
- Sign up or log in
- Create an API key
- Add the key to your MCP configuration
Available Tools
| Tool | Description |
|---|---|
execute_python | Run Python code in sandbox |
execute_node | Run Node.js code in sandbox |
upload_file | Upload a file to sandbox |
download_file | Download a file from sandbox |
list_files | List files in sandbox directory |
install_package | Install a Python/Node package |
Usage Examples
Run Python Code
result = execute_python(code="""
import pandas as pd
import matplotlib.pyplot as plt
# Create sample data
data = {
'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
'Sales': [12000, 15000, 18000, 22000, 25000]
}
df = pd.DataFrame(data)
print(df.to_string())
# Create visualization
plt.figure(figsize=(10, 6))
plt.plot(df['Month'], df['Sales'], marker='o', linewidth=2)
plt.title('Monthly Sales Trend')
plt.xlabel('Month')
plt.ylabel('Sales ($)')
plt.grid(True, alpha=0.3)
plt.savefig('sales_chart.png')
print('Chart saved to sales_chart.png')
""")
print(result.stdout)
print(result.stderr)
Install and Use Packages
# Install a package
install_package(package="requests", language="python")
# Use the installed package
result = execute_python(code="""
import requests
response = requests.get('https://api.github.com')
print(f"GitHub API status: {response.status_code}")
print(f"Rate limit remaining: {response.headers.get('X-RateLimit-Remaining')}")
""")
Data Analysis Workflow
# Upload a CSV file
upload_file(local_path="sales_data.csv", sandbox_path="/home/user/sales_data.csv")
# Analyze the data
result = execute_python(code="""
import pandas as pd
df = pd.read_csv('/home/user/sales_data.csv')
print(f"Shape: {df.shape}")
print(f"Columns: {df.columns.tolist()}")
print(f"\\nSummary statistics:")
print(df.describe())
# Find top products
top_products = df.nlargest(5, 'revenue')[['product', 'revenue']]
print(f"\\nTop 5 products by revenue:")
print(top_products.to_string())
""")
print(result.stdout)
# Download results
download_file(sandbox_path="analysis_results.csv", local_path="results.csv")
Run Node.js Code
result = execute_node(code="""
const fs = require('fs');
// Process JSON data
const data = {
users: [
{ id: 1, name: 'Alice', score: 85 },
{ id: 2, name: 'Bob', score: 92 },
{ id: 3, name: 'Charlie', score: 78 }
]
};
// Calculate average score
const avgScore = data.users.reduce((sum, u) => sum + u.score, 0) / data.users.length;
console.log(`Average score: ${avgScore.toFixed(2)}`);
// Find top performer
const topPerformer = data.users.reduce((max, u) => u.score > max.score ? u : max);
console.log(`Top performer: ${topPerformer.name} (${topPerformer.score})`);
// Write to file
fs.writeFileSync('results.json', JSON.stringify({ avgScore, topPerformer }, null, 2));
console.log('Results written to results.json');
""");
print(result.stdout)
Pros
- ✅ Secure Sandbox: Isolated execution protects host system
- ✅ Multi-Language: Python, Node.js, and more
- ✅ Package Support: Install packages at runtime
- ✅ File System: Read/write files in sandbox
- ✅ Network Access: Optional internet for API calls
- ✅ Automatic Cleanup: Sandboxes auto-destroy
- ✅ Real-Time Output: Stream execution output
Cons
- ❌ API Key Required: Need E2B account and API key
- ❌ Cost: Free tier has limits, paid plans for heavy use
- ❌ Latency: Cloud execution adds latency vs local
- ❌ Network Limits: Some network access may be restricted
When to Use
Use E2B MCP when:
- You need to execute untrusted or user-provided code
- You want to run data analysis safely
- You need to generate visualizations programmatically
- You want to test code in an isolated environment
- You need multi-language code execution
Avoid E2B MCP when:
- You can execute code locally safely
- You need real-time performance (latency matters)
- You're on a tight budget (free tier limits)
- You need access to local hardware/resources
