How Agents Use E2B Code Interpreter to Isolate Untrusted Code Execution
When building agents, one of the most tempting capabilities is letting the model write code and run it itself: cleaning data, testing formulas, plotting to verify results. That is also where the trouble lies. Once "generation" and "execution" sit on the same chain, you are effectively dropping code that is untrusted by default into your own runtime environment.
One instinct is to put the entire agent in a sandbox. Isolation is more thorough, but the cost often isn't worth it. Agent projects are usually large: dependencies, model clients, orchestration frameworks, and business code all go into the image, so cold starts and loading slow down noticeably. If the working directory also mounts object storage for reads and writes, every file access adds another layer of network latency. What really needs isolation is often just that small piece of code "the model generated and is about to run", not the whole agent process.
So the more common split is: the agent keeps running on your service side, and only the untrusted execution is handed off to a Code Interpreter sandbox. Starting from the agent's execution surface, this post explains why running code directly on the host is unsafe, how to build this isolation layer with E2B's Code Interpreter (e2b-code-interpreter / @e2b/code-interpreter), and what it can and cannot protect against.
The Core Problem: Why Can't Agents Run Code Directly on the Host?
An agent differs from a "chat-only model" by one step: it often wires generated output into tools, such as computing a table, drawing a chart, calling a library, or assembling a script, and runs it as soon as it's written. Convenient, but where execution authority lands becomes a hard question.
Code here should be treated as untrusted by default. It doesn't necessarily come from an attacker, but the model may hallucinate dangerous commands, user input may get spliced into the prompt, and the toolchain may be indirectly poisoned. If the interpreter has the same privileges as the host (same machine, same user, same file system and network), a single os.system, a careless disk write, or an outbound connection affects not just variables in the session but your secrets, repositories, and internal network.
So for agents, the right question isn't "does this code look like it'll run?" but rather: execution must happen in an environment with a clear boundary, that is disposable and isolated from the host. Without that isolation, a "Code Interpreter" just expands the attack surface from conversation to arbitrary code execution. Data analysis agents, apps with function calling, and AI assistants in IDEs are all making "generate + execute" the default path, so isolation is a prerequisite for the capability, not an afterthought patch.
E2B: A Disposable Execution Environment for Agents
E2B does something very focused: it provides securely isolated sandboxes in the cloud, specifically for running AI-generated code. You create and control sandboxes through the SDK; code runs inside the sandbox, and the host process only sends code and collects results. For an agent, this moves the "execution surface" from the local machine to a remote environment you can throw away after use. The agent itself stays on the service side, and the sandbox only takes on that piece of dangerous code, which is exactly the split described at the start.
Compare the boundaries with common approaches:
| Approach | Where isolation roughly sits | Practical cost |
|---|---|---|
Local subprocess / in-process interpreter |
Almost none; same privileges as the agent service | Fastest to implement, highest risk |
| Local Docker / self-managed containers | Process and file system can be isolated, but still uses your machine and network | You manage images, resources, cleanup, and the escape surface yourself |
| E2B cloud sandbox | Execution happens in an isolated remote environment, separate from the host machine | Start/stop via API; keys and quotas managed on the service side |
Local containers can of course provide isolation too, but agents tend to be "short-lived, highly concurrent, quick to destroy" workloads. Outsourcing sandbox operations to dedicated infrastructure is usually simpler than running yet another container orchestration setup next to your business process. E2B positions itself as open-source infrastructure on this path, not as yet another local interpreter embedded in the app.
In an agent pipeline, it usually sits here:
Model decision → tool call (code as an argument) → E2B sandbox execution → stdout / return value sent back → model continues reasoning
The agent framework (LangChain, custom function calling, etc.) is only responsible for "when to call the tool and what code to pass"; the truly dangerous step, interpreting and executing, happens inside the sandbox. The next section shows how the Code Interpreter SDK plugs this step into a tool function.
Letting Agents Run Code with e2b-code-interpreter
e2b-dev/code-interpreter provides an SDK for "interpreting and executing code in a sandbox": the Python package e2b-code-interpreter and the JS/TS package @e2b/code-interpreter. (The SDK source has since moved to the E2B monorepo; this repository still holds resources such as the sandbox template.) For agents, it is usually wrapped as a tool: the input is a code string, and the output is execution text or a structured result.
Installation and authentication are straightforward:
pip install e2b-code-interpreter
# or: npm i @e2b/code-interpreter
export E2B_API_KEY=e2b_***
The minimal loop is: create a sandbox → run_code / runCode → read the return value. A Python example (matching the official README):
from e2b_code_interpreter import Sandbox
with Sandbox.create() as sandbox:
sandbox.run_code("x = 1")
execution = sandbox.run_code("x += 1; x")
print(execution.text) # 2
JS/TS works the same way: after Sandbox.create(), call runCode twice, and the second call can read the x left by the first. When wiring this into an agent, the tool function typically looks like this: receive the code from the model → execute it on an existing (or temporarily created) Sandbox → return execution.text (plus any error information) to the model as the tool result. Never exec / eval this code in the host process.
Multiple calls within the same sandbox share interpreter state (variables, imported modules, etc.), which suits multi-step agents well: load data first, then transform, then plot or summarize, without cramming all the logic into a single tool call. Close the sandbox when the task is done to avoid dangling sessions and billing. When you need extra dependencies, use a custom sandbox template rather than running pip install on the host.
Isolation Boundaries and Capability Boundaries
Moving execution into E2B addresses host-side risk: code from the model or user cannot, by default, reach key files, source trees, or local processes on your machine, nor does it automatically inherit the agent host's local privileges and network identity. Sandboxes can be created and destroyed, so a task's dirty state doesn't have to linger on your business servers. For agents, this is the baseline isolation that makes it "safe enough to let it run code". And precisely because only the execution surface is isolated, you don't need to push the whole agent (with its large image and object storage mounts) into the sandbox.
But isolation is not a universal shield. Distinguish at least these layers:
- The sandbox is still a full execution environment. Code can read and write its visible file system, consume CPU/memory, and access the network according to product policy. Temporary data and intermediate results you pass in are readable and writable by processes inside the sandbox. What's isolated is "breaking out of the sandbox to hit the host", not "the sandbox is guaranteed to behave".
- Business trust assumptions don't disappear. If the agent writes sandbox output into a database as ground truth, or puts a high-privilege API key into the sandbox's environment variables, the problem shifts from "host compromised" to "fooled by tool results / secrets leaked into the execution surface". The sandbox won't validate output for you, nor enforce least privilege for you.
- Quotas and abuse are a separate concern. Malicious or runaway loops and mass sandbox creation hit your bill and availability, not local privilege escalation in the traditional sense. Rate limits, timeouts, and sandboxes per session are product-level controls that need their own design.
The default Code Interpreter template covers most "compute something, draw a chart" scenarios. When an agent needs specific library versions, system dependencies, or a customized runtime, build a custom sandbox template the official way (see the template guide in the repository) and bake dependencies into the image, rather than installing things ad hoc in every run_code or falling back to installing on the host. Templates customize the capability surface; the isolation boundary is still defined by the line between "remote sandbox vs. host".
Practical Notes
Keep the API key on the agent service side only. E2B_API_KEY is used to create and control sandboxes and is an infrastructure credential. Keep it in backend environment variables or a secrets manager; never put it in the frontend, prompts, or logs, and certainly never pass it to the model as a tool argument. Letting user browsers connect directly to E2B hands over your billing and sandbox-creation rights.
Manage sandbox lifecycle. Create sandboxes per session or per task, set timeouts, and close them when done (Python's with Sandbox.create() is a natural way to wrap up). Multi-step agents can reuse the same sandbox to keep variables, but don't share sandboxes across users or sessions, to avoid state bleeding between them. Long-idle sandboxes both cost money and widen the exposure window.
Treat results as untrusted input before feeding them back to the model. execution.text, stdout, and files generated in the sandbox should all be processed by the tool layer before being returned as tool results: truncate overly long output, distinguish success from errors, and return only a summary when appropriate. When you need charts or files, retrieve them the way the SDK / docs describe, then decide whether to persist them to your own object storage. Don't assume by default that "it ran, so it's safe to write to the database".
Three common pitfalls to remember: keys ending up in the repository or in sandbox environment variables; calling create without ever closing; and reading "we're on E2B" as "output is trustworthy and permissions don't need tightening". The first two are engineering mistakes; the third is a wrongly drawn threat model.
Summary
- If an agent runs code, the execution surface should be externalized. An interpreter with host-level privileges turns "generation" into arbitrary code execution; isolation is a prerequisite for the capability, not a nice-to-have.
- E2B + Code Interpreter is a practical implementation. Use
e2b-code-interpreter/@e2b/code-interpreterto wire tool calls to a remote sandbox; the host only sends code and collects results. - Know where the isolation boundary is. It blocks direct harm to the host; behavior inside the sandbox, output trust, keys, and quotas are still yours to lock down.
Further reading: E2B documentation, code-interpreter repository, E2B Cookbook.