Skip to content

About

E2B sandbox provider for Strands Agents

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

13 Commits

Folders and files

Repository files navigation

strands-e2b

Run a Strands Agents agent's shell, Python, and file tools in an E2B sandbox instead of on your machine.

E2BSandbox plugs into Strands' native sandbox API (Agent(sandbox=...)). You create the E2B sandbox and pass it in; the agent's shell, Python, and file tools then run inside it, and you kill it when you're done.

Install

Requires Python 3.11 or later.

pip install strands-e2b

Set E2B_API_KEY (get one) and the credentials for your Strands model provider.

Use with an agent

The example uses Claude Haiku through Strands' Anthropic provider (pip install "strands-agents[anthropic]", plus ANTHROPIC_API_KEY). Any Strands model works.

import asyncio

from e2b import AsyncSandbox
from strands import Agent
from strands.models.anthropic import AnthropicModel

from strands_e2b import E2BSandbox


async def main() -> None:
    # You own the sandbox: create it, and kill it when the agent is done.
    sandbox = await AsyncSandbox.create(timeout=600)
    try:
        agent = Agent(
            model=AnthropicModel(model_id="claude-haiku-5-5", max_tokens=4096),
            sandbox=E2BSandbox(sandbox, working_dir="/home/user"),
        )
        await agent.invoke_async(
            "Write a CSV with the squares of 1..10 to squares.csv, "
            "then use Python to print the sum of the squares column."
        )
        print(await agent.sandbox.read_text("squares.csv"))
    finally:
        await sandbox.kill()


asyncio.run(main())

The agent writes squares.csv inside the sandbox and answers 385. A runnable version is in examples/agent.py (python examples/agent.py). Synchronous calls (agent("...")) work too.

Tools

E2BSandbox registers these Strands tools, bound to the sandbox:

Tool Does
sandbox_shell Runs a shell command
sandbox_python_repl Runs Python code in a fresh python3 process
sandbox_read Reads a file (text, images, documents)
sandbox_write Creates or overwrites a file
sandbox_edit Replaces an exact string in a file

Agent(sandbox=...) always registers all five; a tool you pass yourself with the same name takes precedence. To give the agent fewer tools, don't pass sandbox=. Instead pass tools bound to the sandbox, for example Agent(tools=[make_read(sandbox=E2BSandbox(sandbox))]) with make_read from strands.vended_tools. In that setup agent.sandbox and any other Strands tools you add run on your machine.

You can also drive the sandbox from your own code, for example to seed input files or read results:

s = E2BSandbox(sandbox, working_dir="/home/user")
await s.write_text("input.txt", "hello")
result = await s.execute("wc -c input.txt")
print(result.exit_code, result.stdout)

Options

Option Default Description
sandbox required A running e2b.AsyncSandbox
working_dir E2B default (/home/user) Absolute directory for commands and relative file paths. The directory must exist.
user E2B default E2B user for commands and file operations. File operations go through the E2B filesystem API, which is not limited by this user's permissions.

Behavior and lifecycle

  • You own the sandbox. E2BSandbox never creates, pauses, extends, or kills it. Strands does not close it either. Kill it yourself, and keep the E2B sandbox timeout longer than the agent run.
  • Files persist, processes don't. Files stay in the sandbox for its lifetime and are shared by all tools. Each command and each Python call starts a fresh process, so shell variables, cd, and Python variables don't carry over. Save intermediate results to files.
  • Commands run with bash -l -c in working_dir (or the per-call cwd) and stream stdout and stderr. A non-zero exit code is returned as a result, not raised. env values are passed to the command as is. Your local environment, including E2B_API_KEY, is never forwarded.
  • Timeouts. A tool's timeout is a wall-clock limit. When it expires, the command is killed and Strands' SandboxTimeoutError is raised with the output so far.
  • Killing a command sends SIGKILL to its whole process group: the shell, pipelines, child processes such as python3, and & jobs. This happens on timeout, cancellation, closing the output stream early, and a dropped connection. A process that starts its own session (setsid, daemons) is not reached. Without setsid in the template, only the shell is killed.
  • Uncertain outcomes. If the connection drops while a command is starting, or the kill request fails (it is logged as a warning), the command may still be running. It is never retried automatically.
  • File operations use the E2B filesystem API, so binary files and large files work without shell encoding. Parent directories are created on write. Missing paths raise FileNotFoundError, reading a directory raises IsADirectoryError, and listing a file raises NotADirectoryError. Other E2B errors keep their E2B exception type.
  • Output is not truncated by the adapter. Commands keep their full output in memory, as Strands expects. Redirect very large output to a file.
  • Isolation comes from the sandbox. working_dir is not a boundary. In the default E2B template the user account has passwordless sudo, so anything the agent runs can reach the whole sandbox, but not your machine. Network access follows the sandbox's settings (AsyncSandbox.create(allow_internet_access=...)).
  • Strands harness. create_harness(sandbox=E2BSandbox(...)) works too: the harness replaces the sandbox_* tools with its own shell, read, write, and edit, which run in the sandbox. Its session and memory files stay on your machine.
  • Tools run concurrently by default in Strands. Concurrent edits of the same file are not coordinated.

Development

uv venv && uv pip install -e '.[dev]'
pytest                       # mocked tests, no credentials needed
E2B_API_KEY=... pytest -m live   # creates real E2B sandboxes
ruff check . && ruff format --check . && mypy src

License

MIT

About

E2B sandbox provider for Strands Agents

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages