Velamuvi AIAcademy

Lesson 9 of 39 · Tools

Shell and Sandboxed Code Execution

Let agents run shell commands and Python safely: LocalShellTool, ShellPolicy, approvals, DockerShellTool, and Monty and Hyperlight code sandboxes.

  • 12 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain the three layers of safety: policy, approval and sandbox
  • Run commands with LocalShellTool in persistent and stateless mode
  • Give an agent a shell tool that needs approval, through SupportsShellTool
  • Filter commands with ShellPolicy and ShellDecision
  • Run model-written Python in a sandbox with Monty or Hyperlight, and commands in Docker

An agent that can run things

Some questions are easiest to answer by running something: counting files, searching logs, adding up prices. Agent Framework can give a model a shell or a Python interpreter. That is powerful, and dangerous: the model writes the commands, and a model can be tricked by a prompt injection or simply be wrong.

Safety comes in three layers:

Try it yourselfPython
# Three layers between a model and your computer, in plain Python.
import re

DENY = [r"\brm\b", r"\bsudo\b"]


def policy(command):              # layer 1: a quick filter on the command text
    for pattern in DENY:
        if re.search(pattern, command):
            return f"denied by policy ({pattern})"
    return None


def approve(command):             # layer 2: a person says yes or no
    return command.startswith("ls")


def sandbox_run(command):         # layer 3: run it where it can't hurt you
    return f"ran {command!r} in a throwaway container"


for command in ["ls bookings", "rm -rf /", "python cleanup.py"]:
    print(f"{command:18} ->", policy(command) or (sandbox_run(command) if approve(command) else "rejected by a person"))

The policy catches obvious mistakes, approval is the real gate for a shell on your own computer, and a sandbox limits the damage of anything that gets through.

LocalShellTool

LocalShellTool from agent_framework.tools runs commands in a shell on the machine your code runs on (bash or sh on Linux and macOS, PowerShell on Windows). Its run() method returns a ShellResult with stdout, stderr, exit_code, timed_out and truncated.

import asyncio
import tempfile

from agent_framework.tools import LocalShellTool


async def main():
    folder = tempfile.mkdtemp()                         # a scratch folder, never your real files

    async with LocalShellTool(workdir=folder) as shell:  # mode="persistent" is the default
        await shell.run("mkdir bookings && echo 'City E, 1 day' > bookings/asha.txt")
        await shell.run("export SHOP=Velo")
        result = await shell.run("echo $SHOP; ls bookings")
        print("persistent:", result.stdout.split(), "exit code", result.exit_code)

    shell = LocalShellTool(mode="stateless", workdir=folder)
    await shell.run("export SHOP=Velo")
    result = await shell.run("echo shop=$SHOP")
    print("stateless: ", result.stdout.strip())

    result = await shell.run("ls missing-folder")
    print(result.format_for_model())


asyncio.run(main())
Output
persistent: ['Velo', 'asha.txt'] exit code 0
stateless:  shop=
stderr: ls: cannot access 'missing-folder': No such file or directory

exit_code: 2

The two modes are the ShellMode values:

  • "persistent" (the default) keeps one shell running, so export and other state carry over between commands. Use it with async with, which closes the shell at the end. One persistent shell belongs to one conversation: never share it between users.
  • "stateless" starts a fresh shell for every command, so nothing carries over.

workdir sets the folder; each command starts there again, but a command can still cd elsewhere. timeout (30 seconds by default) stops runaway commands: the ShellResult then has timed_out=True. max_stdout_bytes caps the output, and format_for_model() is the text the model sees.

Giving the shell to an agent

shell.as_function() turns the tool into a function tool called run_shell. Clients that understand shell tools implement the SupportsShellTool protocol, and their get_shell_tool(func=...) declares the function to the model as a local shell. With OpenAIChatClient, calling get_shell_tool() with no function gives you OpenAI's hosted shell in its own container instead.

import asyncio
import tempfile
from pathlib import Path

from agent_framework import Agent, Message, SupportsShellTool
from agent_framework.openai import OpenAIChatClient
from agent_framework.tools import LocalShellTool


async def main():
    shop = Path(tempfile.mkdtemp())                     # a scratch folder with three booking files
    (shop / "bookings").mkdir()
    for name in ["asha.txt", "ben.txt", "chen.txt"]:
        (shop / "bookings" / name).write_text("City E, 1 day\n")

    client = OpenAIChatClient(model="MODEL_NAME")
    print("client supports shell tools:", isinstance(client, SupportsShellTool))

    async with LocalShellTool(workdir=shop) as shell:
        agent = Agent(
            client=client,
            instructions="You are Velo's back-office assistant. Use the shell to answer questions about files.",
            tools=[client.get_shell_tool(func=shell.as_function())],
        )
        session = agent.create_session()
        response = await agent.run("How many bookings do we have?", session=session)

        while response.user_input_requests:              # every command needs approval by default
            answers = []
            for request in response.user_input_requests:
                print("approve?", request.function_call.parse_arguments()["command"])
                answers.append(request.to_function_approval_response(approved=True))
            response = await agent.run(Message("user", answers), session=session)
        print(response.text)


asyncio.run(main())
Output
client supports shell tools: True
approve? ls bookings | wc -l
We have 3 bookings.

Every command needs approval by default (approval_mode="always_require"). The approval loop is the same as in the tool approvals lesson. In a real app, show the command to a person and send approved=False for anything unexpected.

ShellEnvironmentProvider(shell), which accepts any ShellExecutor such as LocalShellTool, is a context provider that tells the model which operating system, shell version and tools (such as git or python) it has, so it writes commands that work there.

ShellPolicy: filter commands

A ShellPolicy checks each command before approval and before it runs:

  1. denylist: any match is denied.
  2. allowlist: if you set one, a command must match one of its patterns.
  3. custom: a function that receives a ShellRequest and may return a ShellDecision ("allow" or "deny", with a reason) to override the result, or None to keep it.
import asyncio
import tempfile

from agent_framework.tools import LocalShellTool, ShellCommandError, ShellDecision, ShellPolicy, ShellRequest


def office_hours_only(request: ShellRequest) -> ShellDecision | None:
    if "curl" in request.command:
        return ShellDecision("deny", "no network access from the shell")
    return None                                         # None: keep the normal decision


policy = ShellPolicy(
    denylist=[r"\brm\b", r"\bsudo\b"],                 # checked first: any match is denied
    allowlist=[r"^(ls|cat|wc|grep|echo|curl)\b"],      # if set, the command must match one of these
    custom=office_hours_only,                           # gets the last word
)


async def main():
    for command in ["ls -la", "rm -rf bookings", "python -c 'print(1)'", "curl https://example.com"]:
        print(f"{command!r:30}", policy.evaluate(ShellRequest(command)))

    shell = LocalShellTool(mode="stateless", workdir=tempfile.mkdtemp(), policy=policy,
                           on_command=lambda command: print("audit:", command))
    print((await shell.run("echo hello")).stdout.strip())
    try:
        await shell.run("sudo reboot")
    except ShellCommandError as error:
        print("ShellCommandError:", error)


asyncio.run(main())
Output
'ls -la'                       ShellDecision(decision='allow', reason='')
'rm -rf bookings'              ShellDecision(decision='deny', reason='matches denylist pattern: \\brm\\b')
"python -c 'print(1)'"         ShellDecision(decision='deny', reason='command does not match allowlist')
'curl https://example.com'     ShellDecision(decision='deny', reason='no network access from the shell')
audit: echo hello
hello
ShellCommandError: Command rejected by policy: matches denylist pattern: \bsudo\b

run() raises ShellCommandError for a denied command. Through as_function(), the model gets the same message as the tool's result instead, so it can try something else. The on_command hook sees every allowed command: a simple audit log.

Containers: DockerShellTool

DockerShellTool has the same methods, but each command runs in a Docker (or Podman) container. The defaults are strict: no network, a read-only root file system, 512 MB of memory and an unprivileged user. Because the container is the boundary, it allows approval_mode="never_require".

from agent_framework.tools import DockerShellTool, is_docker_available

if is_docker_available():
    shell = DockerShellTool(
        image="python:3.12-slim",       # any image with bash; the default is a small Azure Linux image
        host_workdir="./reports",       # mounted at /workspace, read-only by default
        network="none",                 # the default: no network inside the container
        memory="512m",
        approval_mode="never_require",  # allowed here: the container is the boundary
    )

This needs Docker on your computer, so the code checks is_docker_available() first. Without image=, it uses DOCKER_DEFAULT_IMAGE, a small Azure Linux image. A host folder passed as host_workdir is mounted read-only unless you set mount_readonly=False.

Sandboxed Python: Monty and Hyperlight

Shell commands are hard to make safe. Often the model only needs to calculate or combine data, and for that a Python sandbox is better. Both sandboxes give the model an execute_code tool and let its code call your tools with await tool_name(...).

  • Monty is a small Python interpreter written in Rust. It runs inside your process with no access to your files or network unless you allow it. MontyCodeActProvider adds the execute_code tool and instructions to an agent; MontyExecuteCodeTool is the same tool on its own, for tools=[...].
import asyncio

from agent_framework import Agent, tool
from agent_framework.monty import MontyCodeActProvider
from agent_framework.openai import OpenAIChatClient


@tool
def bike_price(model: str) -> int:
    """Daily rental price in EUR for one bike model."""
    return {"City E": 35, "Trail X": 50, "Kids 20": 15}[model]


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You are Velo's rental desk. Use execute_code for every calculation.",
        context_providers=[MontyCodeActProvider(tools=[bike_price])],   # adds execute_code + instructions
    )
    response = await agent.run("What do a City E, a Trail X and a Kids 20 cost together for 3 days?")

    for message in response.messages:
        for content in message.contents:
            if content.type == "function_call":
                print("code the model wrote:\n" + content.parse_arguments()["code"])
    print(response.text)


asyncio.run(main())
Output
code the model wrote:
total = 0
for model in ['City E', 'Trail X', 'Kids 20']:
    total += await bike_price(model=model)
print(total * 3)
Together they cost 300 EUR for 3 days.

One model call wrote a program that called bike_price three times; one tool call instead of three. resource_limits caps time and memory, and workspace_root or file_mounts share folders with the sandbox.

  • Hyperlight runs the code in a tiny virtual machine for stronger isolation. HyperlightCodeActProvider and HyperlightExecuteCodeTool work the same way, and add allowed_domains (plain strings, (domain, methods) tuples or AllowedDomain values) for the only network requests the code may make. Both sandboxes accept FileMount entries in file_mounts for extra folders:
from pathlib import Path

from agent_framework.hyperlight import HyperlightCodeActProvider

Path("reports").mkdir(exist_ok=True)                   # the folder must exist

codeact = HyperlightCodeActProvider(
    workspace_root="./reports",                         # readable inside the sandbox at /input
    allowed_domains=[("api.velo.example", "GET")],      # the only outbound requests allowed
    execution_timeout_seconds=10,
)

Common mistakes

Practice exercise

Write the decision logic of a shell policy: the same checks, in the same order, as ShellPolicy.evaluate().

Your solutionPython
import re


def evaluate(command, denylist, allowlist=None):
    # Same order as ShellPolicy, ignoring upper and lower case:
    # 1. an empty (or blank) command: ("deny", "command is empty")
    # 2. a denylist match: ("deny", "matches denylist pattern: " + the pattern)
    # 3. an allowlist that the command doesn't match: ("deny", "command does not match allowlist")
    # 4. anything else is allowed
    return "allow", ""


deny = [r"\brm\b", r"\bsudo\b"]
allow = [r"^(ls|cat|wc)\b"]
for command in ["ls bookings", "   ", "SUDO ls", "python app.py", "cat notes.txt"]:
    decision, reason = evaluate(command, deny, allow)
    print(f"{command!r}: {decision} {reason}".rstrip())
Knowledge check

For LocalShellTool, what is the real security boundary?

Summary

  • LocalShellTool runs commands on your machine, in "persistent" or "stateless" ShellMode, and every command needs approval by default.
  • Clients that implement SupportsShellTool turn it into a shell tool with get_shell_tool(func=shell.as_function()).
  • ShellPolicy (denylist, allowlist and a custom ShellDecision) filters commands, but it is not a security boundary.
  • DockerShellTool runs commands in a locked-down container.
  • MontyCodeActProvider and HyperlightCodeActProvider let the model write Python that runs in a sandbox and calls your tools.

Next: MCP Tools.

Finished reading? Tick it off to track your progress.