When an agent runs code, the code it runs can come from untrusted input: a document, a web page, or a user message. If that code runs on the host, it can read files, reach the network, or change things it should never touch. A sandbox is a container that the code runs inside, with no access to the host beyond what you allow. Anthropic’s server tools run code in a sandboxed container for exactly this reason, and CrewAI’s code execution mode offers a safe Docker mode versus an unsafe direct mode. Use the safe mode, always, for untrusted input: no network unless the task needs it, no host files, and a time limit on every run.
What you need
- An agent that runs code from model output or user input
- A sandbox the code can run in, such as a container, with no host access by default
- A list of what the sandbox may reach: files, network, and time limit
Step 1: Run all code inside the sandbox, never on the host
Route every code execution through the sandbox, with the host filesystem and network off by default. A code step that can run on the host will run on the host.
Step 2: Allow only what the task needs
Open the minimum the task requires: the input files it must read, the output folder it may write, and the network only if the task needs it. Everything else stays closed.
Step 3: Test with a hostile input and confirm the host is untouched
Feed the agent an input that tries to read a host file or reach the network, and confirm the sandbox blocks it and the host is unchanged. If the input escapes, the sandbox is misconfigured.
Worked example: synthetic sandbox check
The table below is a synthetic example. It shows the expected result of sandboxing; no code was run.
| Attempt | Blocked? | Host unchanged? |
|---|---|---|
| Read a host file | Yes | Yes |
| Reach the network | Yes | Yes |
| Write to the output folder | No – allowed | Yes |
| No escape from the sandbox | Yes | Pass |
Expected result (UNTESTED). the hostile reads and network attempts are blocked, the allowed write works, and the host is unchanged. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- A sandbox is only as strong as its configuration; an open network or a mounted host folder defeats it.
- Sandboxed code runs slower, so set a time limit and expect the overhead.
- A sandbox blocks access, not bad logic: wrong code still produces wrong results.
- Test the sandbox with a hostile input, not just with friendly ones.
