omarcevi.dev / workshops / coding-agent-workshop / 4 · Guardrails

Step 4 · Add guardrails

Step 3 works, and that's the problem. Nothing stops it from reading files outside the project, like ../.env, or running any command it likes. While preparing this workshop, after the tests went green it decided on its own to run git diff. Harmless this time.

First guardrail: the file tools refuse any path outside the workspace. Use _resolve(path) in read_file and write_file instead of WORKSPACE / path.

agents/step4_safe/agent.py
agent.pyagents/step4_safe/
def _resolve(path: str) -> Path:
    """Turns a project-relative path into a real path, refusing anything outside
    the workspace: "../.env", "/etc/passwd", or a symlink that points out."""
    file = (WORKSPACE / path).resolve()
    if not file.is_relative_to(WORKSPACE):
        raise PermissionError(f"{path!r} is outside the project folder.")
    return file

Second guardrail: writing and running ask you first. Wrapping a function in FunctionTool lets you configure it (add from google.adk.tools import FunctionTool):

agents/step4_safe/agent.py
agent.pyagents/step4_safe/
    tools=[
        list_files,
        read_file,
        # Wrapping a function in FunctionTool lets you configure it.
        FunctionTool(write_file, require_confirmation=True),
        FunctionTool(run_command, require_confirmation=True),
    ],

Now when the agent wants to write a file or run a command, the dev UI pauses and shows a card with the arguments. Tick Confirmed and press Submit to allow it, or press Submit without ticking to reject it. A rejected agent is told so, and carries on without that call.

Why writes too, when commands already ask? Approving python -m pytest approves whatever code the tests load. If writes didn't ask, the agent could add a conftest.py that runs on the next test run, and the card would still just say python -m pytest.

Try to get out of the folder:

Read ../pyproject.toml

It's refused. Then reset the project, ask it to fix the tests again, and approve the fix and each test run. If it asks for something you didn't ask for, like git diff, reject it and watch what it does.

These are guardrails, not a sandbox: an approved command can do anything you can. For real isolation, run the agent in a container or a VM.

The idea: the more an agent can do, the more you need to decide what it may do without asking.