Code sandbox for AI agents
Let an AI agent run the Python it writes, safely. Each snippet gets a fresh MicroVM with no network, a hard time limit and capped memory, and the agent gets back the output or the traceback.
What this tutorial proves
- Untrusted code, including code an AI wrote, runs in its own MicroVM, never shared with another tenant.
- With
network: nonethe code cannot reach the internet, your other runs or your machine. - A hostile snippet (an endless loop, a memory bomb, a fork bomb) ends with a clear result, not a hung or crashed task.
- An agent can use the platform as a tool: Claude writes the code, the task runs it, Claude reads the result.
What you build
- A Python task that takes a program in its payload, runs it, and returns stdout, stderr and the exit code.
- A short agent script on your machine. Claude gets one tool,
run_python, and each call starts a run of the task.
you ──question──▶ agent.py (your machine) ──▶ Claude (claude-opus-5-5)
▲ │ tool call: run_python(code)
│ ▼
└── result JSON ◀── ignitify task:run code-sandbox --wait --json
│
fresh MicroVM, no network: python3 main.pyThe task's nature
| Setting | Value | Why |
|---|---|---|
runtime | python | Python 3.11 and the standard library. No packages to install. |
network.type | none | No network at all. The strongest setting, and the right one for untrusted code. |
duration | short | A snippet runs for 30 seconds at most. |
preset | std.small | 256 MiB. The snippet gets 128 MiB, the rest is the runtime and the VM. |
timeout_sec | 60 | Covers the snippet's own limit and start-up. |
Before you start
- A plan with the
std.smallpreset. This tutorial uses Starter. - The CLI, installed and signed in. See Install.
- For the agent: Python 3.10 or later, the
anthropicpackage, and an Anthropic API key.
$ ignitify loginCreate the task
$ ignitify task:create code-sandbox --lang pythontasks/code-sandbox/
├── task.yaml Python, no network, std.small
├── main.py the shell: run(payload, ctx)
├── sandbox.py payload checks, resource limits, the child process
├── requirements.txt empty: only the standard library is used
├── agent.py runs on your machine; kept out of the deploy by .ignitifyignore
└── .ignitifyignore agent.pyThe code
The VM is the security boundary. Inside it, sandbox.py runs the program as a child process, so the task can still answer when the program hangs, crashes or floods its output. The child gets resource limits and an empty environment, and a timeout kills it with everything it started.
# Code sandbox for AI agents: run a snippet of untrusted Python and return what it printed.
#
# Payload: {"code": "<python source>", "stdin": "<optional>", "timeout_sec": 10 (at most 30)}
# Result: {"ok", "exit_code", "signal", "timed_out", "duration_ms", "stdout", "stderr",
# "stdout_truncated", "stderr_truncated", "python"}
#
# An agent calls this as a tool: `ignitify task:run code-sandbox --payload '{"code": ...}' --wait --json`.
# Each run gets a fresh MicroVM with no network (task.yaml), so the code cannot reach the internet,
# other runs or your machine. A failing snippet is a normal result (ok: false), not a failed run:
# the agent reads the traceback and tries again. Only a bad payload fails the run.
#
# This file is the shell. The checks, limits and the child process live in sandbox.py.
import os
from sandbox import execute, parse_payload
# The code drive is read-only; the scratch disk ($HOME) is the only place to write.
WORKDIR = os.environ.get("HOME", "/mnt/scratch")
def run(payload, ctx):
job = parse_payload(payload)
result = execute(job, WORKDIR)
ctx.metric("sandbox_duration_ms", result["duration_ms"])
print(f"exit={result['exit_code']} timed_out={result['timed_out']} duration_ms={result['duration_ms']}")
return result"""The pure parts of code-sandbox, and the one function that runs the code.
The VM is the security boundary: one fresh MicroVM per run, with no network. Inside it, the
untrusted code runs in a child process so the task can still answer when that code hangs,
crashes, eats memory or prints megabytes: a wall-clock timeout, resource limits, and capped
output. The child never sees the task's environment.
"""
import json
import os
import resource
import signal
import subprocess
import sys
import tempfile
import time
from dataclasses import dataclass
MAX_CODE_BYTES = 8 * 1024 # the payload limit is 10 KiB, with room for the other fields
MAX_STDIN_BYTES = 1024
DEFAULT_TIMEOUT_S = 10.0
MAX_TIMEOUT_S = 30.0
MEMORY_MB = 128 # address space of the child; the std.small VM has 256 MiB
MAX_FILE_MB = 16 # the largest file the child may write
MAX_PROCS = 64 # stops a fork bomb from filling the VM
RESULT_BUDGET = 9 * 1024 # the result limit is 10 KiB
@dataclass(frozen=True)
class Job:
code: str
stdin: str
timeout_s: float
def parse_payload(payload: dict) -> Job:
"""Check the payload: `code` is required; `stdin` and `timeout_sec` are optional."""
code = payload.get("code")
if not isinstance(code, str) or not code.strip():
raise ValueError("payload.code must be a non-empty string of Python source")
if len(code.encode()) > MAX_CODE_BYTES:
raise ValueError(f"payload.code is over {MAX_CODE_BYTES} bytes")
stdin = payload.get("stdin", "")
if not isinstance(stdin, str) or len(stdin.encode()) > MAX_STDIN_BYTES:
raise ValueError(f"payload.stdin must be a string of at most {MAX_STDIN_BYTES} bytes")
timeout = payload.get("timeout_sec", DEFAULT_TIMEOUT_S)
if not isinstance(timeout, (int, float)) or timeout <= 0:
raise ValueError("payload.timeout_sec must be a positive number")
return Job(code=code, stdin=stdin, timeout_s=min(float(timeout), MAX_TIMEOUT_S))
def _limits(timeout_s: float):
"""Resource limits for the child, applied after fork and before the code starts."""
def apply() -> None:
cpu = int(timeout_s) + 1
resource.setrlimit(resource.RLIMIT_CPU, (cpu, cpu))
resource.setrlimit(resource.RLIMIT_AS, (MEMORY_MB << 20, MEMORY_MB << 20))
resource.setrlimit(resource.RLIMIT_FSIZE, (MAX_FILE_MB << 20, MAX_FILE_MB << 20))
resource.setrlimit(resource.RLIMIT_NPROC, (MAX_PROCS, MAX_PROCS))
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
return apply
def _cut(text: str, limit: int) -> tuple[str, bool]:
"""The first `limit` characters, and whether anything was cut."""
return (text, False) if len(text) <= limit else (text[:limit], True)
def _signal_name(code: int) -> str | None:
"""A negative return code means the child died of a signal."""
return signal.Signals(-code).name if code < 0 else None
def fit(result: dict) -> dict:
"""Shrink stdout and stderr until the JSON result fits the platform's result limit."""
out, err = result["stdout"], result["stderr"]
while len(json.dumps(result).encode()) > RESULT_BUDGET and (out or err):
out, err = out[: len(out) * 3 // 4], err[: len(err) * 3 // 4]
result = {**result, "stdout": out, "stderr": err, "stdout_truncated": True, "stderr_truncated": bool(err) or result["stderr_truncated"]}
return result
def execute(job: Job, workdir: str) -> dict:
"""Run the code in a child Python with limits, and describe what happened."""
with tempfile.TemporaryDirectory(dir=workdir) as tmp:
script = os.path.join(tmp, "main.py")
with open(script, "w", encoding="utf-8") as f:
f.write(job.code)
started = time.monotonic()
# -I: no user site, no environment variables, no script directory on sys.path from outside.
child = subprocess.Popen(
[sys.executable, "-I", "-X", "utf8", script],
cwd=tmp,
env={"PATH": "/usr/bin:/bin", "HOME": tmp, "LANG": "C.UTF-8"},
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
preexec_fn=_limits(job.timeout_s),
start_new_session=True, # its own process group, so a timeout kills every child it made
)
try:
raw_out, raw_err = child.communicate(job.stdin.encode(), timeout=job.timeout_s)
timed_out = False
except subprocess.TimeoutExpired:
os.killpg(child.pid, signal.SIGKILL)
raw_out, raw_err = child.communicate()
timed_out = True
duration_ms = round((time.monotonic() - started) * 1000)
stdout, out_cut = _cut(raw_out.decode("utf-8", "replace"), 4000)
stderr, err_cut = _cut(raw_err.decode("utf-8", "replace"), 2000)
return fit({
"ok": child.returncode == 0 and not timed_out,
"exit_code": child.returncode,
"signal": _signal_name(child.returncode),
"timed_out": timed_out,
"duration_ms": duration_ms,
"stdout": stdout,
"stderr": stderr,
"stdout_truncated": out_cut,
"stderr_truncated": err_cut,
"python": sys.version.split()[0],
})schema_version: 1
slug: code-sandbox # must match this directory's name
runtime: python
execution:
duration: short # a snippet runs for 30 s at most
network:
type: none # no network at all: the code cannot reach the internet or anything else
run:
payload:
code: |
import platform, sys
print("hello from", platform.machine(), sys.version.split()[0])
preset: std.small # 256 MiB: the snippet gets 128 MiB, the rest is the runtime and the VM
timeout_sec: 60 # covers the snippet's own 30 s limit and start-up# code-sandbox
Run untrusted Python, such as code an AI agent wrote, in a fresh MicroVM with no network, and get back what it printed. A failing program is a normal result (`ok: false` with the traceback), so the agent can read it and try again.
## Files
- `task.yaml`: Python runtime, no network, a 30 s limit per snippet, the `std.small` preset.
- `main.py`: the shell: `run(payload, ctx)`.
- `sandbox.py`: the payload checks, the resource limits and the child process.
- `agent.py`: runs on your machine, not on the platform. Claude writes code and calls this task as a tool. `.ignitifyignore` keeps it out of the deploy.
## Payload and result
| Field | Default | Meaning |
| :-- | :-- | :-- |
| `code` | none | The Python program (required, at most 8 KiB) |
| `stdin` | `""` | Text for standard input (at most 1 KiB) |
| `timeout_sec` | 10 | Wall-clock limit for the program (at most 30) |
Result: `ok`, `exit_code`, `signal`, `timed_out`, `duration_ms`, `stdout` (first 4,000 characters), `stderr` (first 2,000), `stdout_truncated`, `stderr_truncated`, `python`.
## Limits inside the VM
The VM is the boundary: one per run, no network. Inside it, the program runs as a child process with a 128 MiB memory cap, a CPU-time cap, a 16 MiB file-size cap, at most 64 processes, no core dumps, and an empty environment (`PATH`, `HOME`, `LANG` only). A timeout kills the child and everything it started.
## Lifecycle
```bash
ignitify login
ignitify task:create code-sandbox --lang python
ignitify task:validate code-sandbox
ignitify task:deploy code-sandbox
ignitify task:run code-sandbox --wait
ignitify task:run code-sandbox --wait --payload '{"code":"print(sum(range(10**6)))"}'
```
With an agent:
```bash
pip install anthropic
export ANTHROPIC_API_KEY=...
python agent.py "How many primes are there below 1,000,000? Check it by running code."
```Create .ignitifyignore with one line, agent.py, so the agent script stays on your machine.
Validate and deploy
$ ignitify task:validate code-sandbox✓ task config valid
$ ignitify task:pack code-sandboxignored by .ignitifyignore: agent.py
$ ignitify task:deploy code-sandbox✓ Image built · <build time>✓ Deployment Createddeployment_id <deployment-id>
Run a snippet
The default payload prints the machine and the Python version. Pass your own program with --payload.
$ ignitify task:run code-sandbox --wait$ ignitify task:run code-sandbox --wait --json --payload '{"code":"import math\nprint(math.factorial(20))"}' | jq .result{
"ok": true,
"exit_code": 0,
"signal": null,
"timed_out": false,
"duration_ms": 14,
"stdout": "2432902008176640000\n",
"stderr": "",
"stdout_truncated": false,
"stderr_truncated": false,
"python": "3.11.2"
}A program that fails is still a completed run. The result has ok: false and the traceback in stderr, which is what an agent needs to fix its code. Only a bad payload fails the run, for example code over 8 KiB.
Try to break it
We ran these snippets through sandbox.py. Each one ends with a clear result, and the task keeps working:
| Snippet | Code | What happens |
|---|---|---|
| Endless loop | while True: pass | Killed at the time limit (SIGKILL), timed_out: true |
| Background child | subprocess.Popen(["sleep","100"]) | The whole process group is killed at the time limit |
| Memory bomb | bytearray(512 * 1024 * 1024) | MemoryError: the 128 MiB cap holds |
| Fork bomb | os.fork() in a loop | Refused after 64 processes (Errno 11) |
| Huge output | print('x' * 100000) | Cut to fit the result limit, stdout_truncated: true |
| Large file | write 64 MiB to disk | OSError: File too large (16 MiB cap) |
| Read secrets | print(os.environ) | Only PATH, HOME and LANG are there |
$ ignitify task:run code-sandbox --wait --json --payload '{"code":"while True: pass","timeout_sec":3}' | jq '.result | {ok, timed_out, signal}'Give it to an agent
agent.py runs on your machine. It gives Claude one tool, run_python. The SDK's tool runner handles the loop: Claude writes a program, the tool runs it as a task run, and Claude reads the JSON result before it answers.
"""agent.py — Claude writes Python, and the Ignitify code-sandbox task runs it.
Runs on your machine, not on the platform. Claude gets one tool, run_python; each call starts a
run of code-sandbox in a fresh MicroVM with no network, and the JSON result goes back to Claude.
pip install anthropic
ignitify login # the CLI must be signed in; this script calls it
export ANTHROPIC_API_KEY=... # or sign in with `ant auth login`
python agent.py "How many primes are there below 1,000,000? Check it by running code."
"""
import json
import subprocess
import sys
import anthropic
from anthropic import beta_tool
client = anthropic.Anthropic()
@beta_tool
def run_python(code: str, stdin: str = "") -> str:
"""Run a Python 3.11 program in a fresh, isolated MicroVM and return the result as JSON.
The result has ok, exit_code, timed_out, duration_ms, stdout and stderr. Print what you want
to see. There is no network and only the standard library; the time limit is 10 seconds.
Args:
code: The complete Python program to run.
stdin: Optional text for standard input.
"""
payload = json.dumps({"code": code, "stdin": stdin})
proc = subprocess.run(
["ignitify", "task:run", "code-sandbox", "--payload", payload, "--wait", "--json"],
capture_output=True, text=True, timeout=300,
)
# --wait --json prints the finished run, as `run:get` does. A refused payload fails the run.
try:
run = json.loads(proc.stdout)
except json.JSONDecodeError:
return json.dumps({"ok": False, "error": proc.stderr.strip()[-2000:] or "the CLI printed no JSON"})
if run.get("result") is None:
return json.dumps({"ok": False, "status": run.get("status"), "error": proc.stderr.strip()[-2000:]})
return json.dumps(run["result"])
def main() -> None:
question = " ".join(sys.argv[1:]) or "What is the 50th Fibonacci number? Check it by running code."
runner = client.beta.messages.tool_runner(
model="claude-opus-5-5",
max_tokens=16000,
# A safety decline is re-run on Anthropic's recommended fallback model, server-side.
betas=["server-side-fallback-2026-07-01"],
fallbacks="default",
system="When a question can be answered by computing, write a Python program and run it with run_python. "
"Read the result before you answer. If the program fails, fix it and run it again.",
tools=[run_python],
messages=[{"role": "user", "content": question}],
)
last = None
for message in runner:
last = message
for block in message.content:
if block.type == "tool_use":
print(f"→ run_python: {len(block.input.get('code', ''))} characters of code")
elif block.type == "text":
print(block.text)
if last is not None and last.stop_reason == "refusal":
print("Claude declined this request.")
if __name__ == "__main__":
main()$ pip install anthropic$ python agent.py "How many primes are there below 1,000,000? Check it by running code."The script uses claude-opus-5-5, and turns on fallbacks: "default": if Claude declines a request on safety grounds, the API re-runs it on Anthropic's recommended fallback model.
Clean up
$ ignitify task:delete code-sandbox --yesNext steps
- Allow some packages: add them to
requirements.in, generate the hashedrequirements.txt, and redeploy. - Give the code a little network: switch to
egresswith anegress_allowlist. See Network access. - Read about sizes and limits: Choose a VM size and disk.