E2B Sandbox for AI Code Execution

VerifiedCaution

Execute AI-generated code in secure isolated cloud sandboxes. Supports Python/JS/TS/R/Java/Bash, coding agents, Git, MCP Gateway, file operations, and sandbox lifecycle management.

Sby Skills Guide Bot
DevelopmentIntermediate
7/24/2026
Claude CodeCursorWindsurfCodex
#e2b#sandbox#code-execution#ai-agents#cloud-vms

Recommended for

Automated summary

A guide for using E2B cloud sandboxes (SDK v2) to execute AI-generated code inside secure, isolated VMs.

Strengths

  • Concrete code patterns for both the Python and JavaScript SDKs (create, run, kill)
  • Multi-language coverage (Python, JS, TS, R, Java, Bash) with isolated code contexts for parallel execution
  • Covers advanced features: pause/resume persistence, custom templates, S3/GCS/R2 bucket mounting, SSH/PTY, and the MCP Gateway
  • Explicitly flags the SDK v2 breaking change (Sandbox.create() instead of Sandbox())

Limitations

  • Requires an E2B_API_KEY and depends on an external cloud service
  • The SKILL.md mostly acts as a router to separate reference files that are not included here
  • Scoped to E2B only; no self-hosted option or alternative sandbox providers
When to use it

Use it when you need to run untrusted or LLM-generated code safely, or build an agent that executes code in isolated cloud VMs.

When not to use it

Avoid it when execution must stay on local or on-premise infrastructure, or when no external cloud API dependency is acceptable.

Security analysis

Caution
Quality score76/100

The skill is documentation for the legitimate E2B sandbox SDK: no curl|sh, no destructive rm, no obfuscation, no exfiltration to unexpected endpoints. However it does orchestrate powerful capabilities (arbitrary code execution, network, git with tokens, coding agents with permission bypass), so it warrants caution rather than a clean 'safe' rating, with the noted secret-handling and permission-skipping flags for reviewers.

Findings
  • •Runs AI-generated code with filesystem and network access inside E2B cloud sandboxes; safety depends entirely on the remote sandbox isolation and correct SDK usage
  • •Passes secrets (GITHUB_TOKEN, ANTHROPIC_API_KEY, E2B_API_KEY) into sandbox environments and git operations, increasing exposure surface if code or templates are untrusted
  • •Example invokes Claude Code with '--dangerously-skip-permissions', which disables the agent's own confirmation gates (mitigated somewhat by being inside a disposable sandbox)
  • •Requires an external cloud service and API key, adding third-party data-processing dependency
  • •Ends mid-code-example (truncated Pattern 8), so full behavior of the MCP gateway portion cannot be fully verified
How this analysis is made

Examples

Run Python analysis in a sandbox
Use the e2b skill to create a sandbox, upload my sales.csv, run a pandas groupby on it, and print the result table.
Pause and resume a coding agent
Start a Claude Code agent inside an E2B sandbox, let it scaffold a repo, then pause the sandbox and show me how to resume it later.
Parallel isolated contexts
Using the e2b skill, create two code contexts in one sandbox and run a pandas script in each without their imports interfering.

name: e2b description: Execute AI-generated code in secure isolated E2B cloud sandboxes (SDK v2). Use for running Python/JavaScript/TypeScript/R/Java/Bash code, managing sandbox lifecycle (create, pause, resume, kill, list, connect), running coding agents (Claude Code, Codex, AMP, OpenCode) in sandboxes, git operations inside sandboxes, code contexts for parallel isolated execution, monitoring metrics (CPU, memory, disk), MCP gateway integration (200+ tools), uploading/downloading files, storage bucket mounting (S3, GCS, R2), streaming command output, SSH/PTY access, custom templates with Build System 2.0, and integrating LLMs with code execution capabilities.

E2B Sandbox Skill

Secure isolated cloud VMs for executing AI-generated code. Sandboxes start in ~150ms with full code execution, filesystem, git, and network access.

SDK v2 Breaking Change: Python uses Sandbox.create() — not Sandbox(). Secured access is enabled by default.

Quick Reference

| Feature | Reference | |---------|-----------| | Getting started | quickstart.md | | Lifecycle & security | sandbox-lifecycle.md | | Code execution & contexts | code-interpreting.md | | File operations | filesystem.md | | Git operations | git-integration.md | | Coding agents | agents.md | | Monitoring & events | monitoring-and-events.md | | Persistence (pause/resume) | persistence.md | | MCP Gateway (200+ tools) | mcp-gateway.md | | Custom templates | custom-templates.md | | Advanced (SSH, PTY, buckets, proxy) | advanced-sandbox.md |

Installation

Two packages available — use e2b for base sandbox features, e2b-code-interpreter when you need run_code() (Jupyter-style execution):

# Python — base sandbox (filesystem, commands, git, processes)
pip install e2b

# Python — code interpreter (adds run_code with charts, multi-language)
pip install e2b-code-interpreter

# JavaScript/TypeScript — base sandbox
npm i e2b

# JavaScript/TypeScript — code interpreter
npm i @e2b/code-interpreter

Required environment variable:

E2B_API_KEY=e2b_***  # Get from https://e2b.dev/dashboard?tab=keys

Core Patterns

Pattern 1: One-shot Code Execution

from e2b_code_interpreter import Sandbox

sandbox = Sandbox.create()
execution = sandbox.run_code('print("Hello from E2B!")')
print(execution.text)
sandbox.kill()
import { Sandbox } from '@e2b/code-interpreter'

const sandbox = await Sandbox.create()
const execution = await sandbox.runCode('console.log("Hello!")')
console.log(execution.text)
await sandbox.kill()

Pattern 2: Multi-language Execution

sandbox.run_code('import pandas as pd; df.describe()')       # Python (default)
sandbox.run_code('await fetch(url)', language='js')           # JavaScript
sandbox.run_code('const x: number = 42', language='ts')       # TypeScript
sandbox.run_code('summary(mtcars)', language='r')             # R
sandbox.run_code('System.out.println("hi")', language='java') # Java
sandbox.run_code('ls -la /home/user', language='bash')        # Bash

Pattern 3: File Upload + Analysis

sandbox.files.write('/home/user/data.csv', csv_content)

execution = sandbox.run_code('''
import pandas as pd
df = pd.read_csv('/home/user/data.csv')
df.describe()
''')

result = sandbox.files.read('/home/user/output.png')

Pattern 4: Code Contexts (Isolated Parallel Execution)

ctx_a = sandbox.create_code_context(cwd='/home/user/project-a')
ctx_b = sandbox.create_code_context(cwd='/home/user/project-b')

result_a = sandbox.run_code('import pandas; print("A")', context=ctx_a)
result_b = sandbox.run_code('import numpy; print("B")', context=ctx_b)

Pattern 5: Git Operations

from e2b import Sandbox

sandbox = Sandbox.create()
sandbox.git.clone('https://github.com/user/repo.git', '/home/user/repo',
                  username='user', password=os.environ['GITHUB_TOKEN'])
sandbox.git.checkout_branch('/home/user/repo', 'feature-branch')
sandbox.git.add('/home/user/repo')
sandbox.git.commit('/home/user/repo', 'fix: update config')
sandbox.git.push('/home/user/repo', username='user', password=os.environ['GITHUB_TOKEN'])

Pattern 6: Running Coding Agents

from e2b import Sandbox

sandbox = Sandbox.create(
    template='claude',
    envs={'ANTHROPIC_API_KEY': os.environ['ANTHROPIC_API_KEY']},
    timeout=300
)
result = sandbox.commands.run(
    'claude -p "Write a hello world server" --dangerously-skip-permissions',
    timeout=120
)
print(result.stdout)

See agents.md for Codex, AMP, OpenCode, and more patterns.

Pattern 7: LLM Tool Integration

from anthropic import Anthropic
from e2b_code_interpreter import Sandbox

tools = [{
    "name": "execute_python",
    "description": "Execute python code in sandbox",
    "input_schema": {
        "type": "object",
        "properties": {
            "code": {"type": "string", "description": "Python code to execute"}
        },
        "required": ["code"]
    }
}]

client = Anthropic()
message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Calculate 2+2"}],
    tools=tools
)

if message.stop_reason == "tool_use":
    tool_use = next(b for b in message.content if b.type == "tool_use")
    sandbox = Sandbox.create()
    result = sandbox.run_code(tool_use.input['code'])
    print(result.text)
    sandbox.kill()

Pattern 8: MCP Gateway

from e2b import Sandbox

sandbox = Sandbox.create(
    mcp={
        'github': {'githubPersonalAccessToken': os.environ['GITHUB_TOKEN']},
        'slack': {'botToken': os.environ['SLACK_BOT_TOKEN']}
    }
)
mcp_url = sandbox.get_mcp_url()
mcp_token = sandbox.get_mcp_token()

See mcp-gateway.md for 200+ available integrations.

Pattern 9: Persistence (Pause/Resume)

sandbox = Sandbox.create(auto_pause=True, timeout=600)
sandbox.run_code(code)
sandbox.pause()
saved_id = sandbox.sandbox_id

# Later: Resume
sandbox = Sandbox.connect(saved_id)

Pattern 10: Custom Template (Build System 2.0)

import { Template, waitForPort } from 'e2b'

const template = Template()
  .fromPythonImage('3.12')
  .pipInstall(['pandas', 'numpy', 'matplotlib'])
  .copy('./app', '/home/user/app')
  .setStartCmd('python /home/user/app/server.py', waitForPort(3000))

await Template.build(template, { name: 'my-data-template' })

API Quick Reference

Sandbox Lifecycle

# Create (SDK v2 — always use .create())
sandbox = Sandbox.create()                          # Default 5 min timeout
sandbox = Sandbox.create(timeout=300)               # Custom timeout (seconds)
sandbox = Sandbox.create(envs={'KEY': 'val'})       # With env vars
sandbox = Sandbox.create(metadata={'user': '123'})  # With metadata
sandbox = Sandbox.create(template='my-template')    # Custom template
sandbox = Sandbox.create(secure=False)              # Disable secured access

# Info & timeout
info = sandbox.get_info()
sandbox.set_timeout(60)

# Kill
sandbox.kill()
Sandbox.kill(sandbox_id)

Sandbox Discovery

paginator = Sandbox.list()                                          # List all
sandboxes = paginator.next_items()
paginator = Sandbox.list(query={'state': ['running', 'paused']})    # Filter by state
paginator = Sandbox.list(query={'metadata': {'userId': '123'}})     # Filter by metadata
sandbox = Sandbox.connect(sandbox_id)                               # Connect to existing

Code Execution

execution = sandbox.run_code(code, language='python', envs={'VAR': 'val'})
execution.text          # Combined output
execution.logs.stdout   # Standard output
execution.logs.stderr   # Standard error
execution.results       # Rich results (charts, tables)
execution.error         # Runtime errors

Commands

result = sandbox.commands.run('ls -la')
result = sandbox.commands.run('cmd', envs={'VAR': 'val'})
result = sandbox.commands.run('cmd', background=True)
result = sandbox.commands.run('cmd', on_stdout=callback, on_stderr=callback)

Files

sandbox.files.write('/home/user/file.txt', content)     # Write single file
sandbox.files.write_files([('/path/a', data_a), ...])    # Write multiple files
content = sandbox.files.read('/home/user/file.txt')      # Read file
info = sandbox.files.get_info('/home/user/file.txt')     # File metadata
files = sandbox.files.list('/home/user')                 # List directory
watcher = sandbox.files.watch_dir('/path')               # Watch changes

Git

sandbox.git.clone(url, path, username=..., password=...)
sandbox.git.branches(path)
sandbox.git.create_branch(path, 'branch-name')
sandbox.git.checkout_branch(path, 'branch-name')
sandbox.git.add(path)
sandbox.git.commit(path, 'message')
sandbox.git.push(path, username=..., password=...)
sandbox.git.pull(path)

Code Contexts

ctx = sandbox.create_code_context(cwd='/path', language='python')
result = sandbox.run_code('print("isolated")', context=ctx)
contexts = sandbox.list_code_contexts()
sandbox.remove_code_context(ctx.id)

Monitoring

metrics = sandbox.get_metrics()
# Returns list of SandboxMetric: cpu_used_pct, cpu_count, mem_used, mem_total, disk_used, disk_total

Python vs JavaScript API

| Operation | Python | JavaScript | |-----------|--------|------------| | Create | Sandbox.create() | await Sandbox.create() | | Timeout | set_timeout(60) | setTimeout(60000) (ms) | | Run code | run_code(code) | await runCode(code) | | Kill | kill() | await kill() | | Pause | pause() | await pause() | | Git clone | git.clone(url, path) | await git.clone(url, path) | | Code context | create_code_context() | await createCodeContext() |

Packages: e2b vs e2b-code-interpreter

| Feature | e2b | e2b-code-interpreter | |---------|-------|------------------------| | Sandbox lifecycle | Yes | Yes (inherits) | | Commands (commands.run) | Yes | Yes | | Filesystem | Yes | Yes | | Git integration | Yes | Yes | | run_code() (Jupyter) | No | Yes | | Charts/visualizations | No | Yes | | Code contexts | No | Yes | | Coding agent templates | Yes | No (use e2b) |

Use e2b for: running agents, shell commands, git workflows, file operations. Use e2b-code-interpreter for: data analysis, code execution, charts, multi-language code.

Default Environment Variables

Available in every sandbox:

  • E2B_SANDBOX=true
  • E2B_SANDBOX_ID - Current sandbox ID
  • E2B_TEAM_ID - Team ID
  • E2B_TEMPLATE_ID - Template used

Best Practices

  1. Always clean up: Use try/finally with kill() or context managers
  2. Use absolute paths: /home/user/file.txt not file.txt
  3. Handle errors: Check execution.error after run_code()
  4. Tag with metadata: Use metadata for tracking user sessions
  5. Monitor resources: Check get_metrics() for CPU/memory usage
  6. Set appropriate timeouts: Short tasks 60-120s, analysis 300-600s
  7. Use code contexts: Isolate parallel code execution within one sandbox
  8. Use git API: Prefer sandbox.git.* over shell git commands

Troubleshooting

| Issue | Solution | |-------|----------| | Sandbox() fails in Python | Use Sandbox.create() (SDK v2 breaking change) | | Timeout too quick | Sandbox.create(timeout=300) or set_timeout(300) | | Code fails | Check execution.error for details | | File not found | Use absolute paths, verify with files.list() | | Auth error on secured sandbox | Old template — rebuild with envd >= v0.2.0, or use secure=False | | Rate limited | Check plan limits in sandbox-lifecycle.md | | High resource usage | Check get_metrics(), kill unused sandboxes |

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/e2b-sandbox-for-ai-code-execution-mryiqfhl/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/e2b-sandbox-for-ai-code-execution-mryiqfhl' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/e2b-sandbox-for-ai-code-execution-mryiqfhl/download' --output '.skill-downloads/e2b-sandbox-for-ai-code-execution-mryiqfhl/SKILL.md.part' && mv '.skill-downloads/e2b-sandbox-for-ai-code-execution-mryiqfhl/SKILL.md.part' '.skill-downloads/e2b-sandbox-for-ai-code-execution-mryiqfhl/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

Original excerpt: Quick Reference
FeatureReference
Getting startedquickstart.md
Lifecycle & securitysandbox-lifecycle.md
Code execution & contextscode-interpreting.md
File operationsfilesystem.md
Git operationsgit-integration.md
Coding agentsagents.md
Monitoring & eventsmonitoring-and-events.md
Persistence (pause/resume)persistence.md
MCP Gateway (200+ tools)mcp-gateway.md
Custom templatescustom-templates.md
Advanced (SSH, PTY, buckets, proxy)advanced-sandbox.md

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/e2b-sandbox-for-ai-code-execution-mryiqfhl/SKILL.md' && test -s '.skill-downloads/e2b-sandbox-for-ai-code-execution-mryiqfhl/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/e2b' && cp -R '.skill-downloads/e2b-sandbox-for-ai-code-execution-mryiqfhl' '.claude/skills/e2b'

Cursor
test -f '.skill-downloads/e2b-sandbox-for-ai-code-execution-mryiqfhl/SKILL.md' && test -s '.skill-downloads/e2b-sandbox-for-ai-code-execution-mryiqfhl/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/e2b' && cp -R '.skill-downloads/e2b-sandbox-for-ai-code-execution-mryiqfhl' '.cursor/skills/e2b'

Codex
test -f '.skill-downloads/e2b-sandbox-for-ai-code-execution-mryiqfhl/SKILL.md' && test -s '.skill-downloads/e2b-sandbox-for-ai-code-execution-mryiqfhl/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/e2b' && cp -R '.skill-downloads/e2b-sandbox-for-ai-code-execution-mryiqfhl' '.agents/skills/e2b'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/e2b-sandbox-for-ai-code-execution-mryiqfhl'

openskills read 'e2b-sandbox-for-ai-code-execution-mryiqfhl'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/e2b-sandbox-for-ai-code-execution-mryiqfhl/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills