CertSafari
    Anthropic Claude Certified Developer – Professional (CCDV-P)· Lessons

    Domain 7 · Lesson 19/25

    Guardrails on agent actions: hooks, approval gates and sandboxes

    Runtime Guardrail Systems

    18 min read
    3.67% of exam
    6 sources
    Published 19 Nov 2026
    Docs as of 18 Nov 2026

    What you will be able to do

    • Match the number and kind of guardrail layers to an agent's blast radius instead of applying every control everywhere
    • Sort an agent's actions by whether they can be undone, and prevent the irreversible ones by removing the capability, narrowing credentials or mounting read-only rather than asking the model to behave
    • Block an irreversible tool call deterministically with a PreToolUse hook or a deny rule, and explain why a prompt rule or a PostToolUse hook does not prevent it
    • Design approval gates that prompt only for high-risk actions, including unsandboxed retries
    • Choose sandbox and container settings that give an agent tool and web access while keeping credentials and production systems out of reach

    Key concept

    Deterministic enforcement — A control for an irreversible action has to run outside the model and fire on every matching call, whatever the model was told or persuaded to do. A hook or deny rule enforces policy. A system-prompt rule only asks the model to follow it.

    1.Fitting guardrail layers to an agent's risk profile

    A runtime guardrail is a control that sits around the model. It decides what reaches the model, what leaves it, and which of its actions actually run. Every layer has a cost: added latency, a false-positive rate, and for approval gates, human attention. The useful design question is not which guardrails exist. It is which ones this agent's worst case justifies.

    Start from what the agent can touch. Take an internal agent that reads wiki pages and posts a weekly summary to one Slack channel. Its worst case is small, visible and easy to correct. Adding an input classifier, approval on every call, a sandbox and a PII redactor would make it unusable for very little gain. Scoping its tools to a read-only wiki and a single channel does most of the protective work. A CI agent that runs shell commands against a staging database with permission prompts disabled is the opposite case. Its worst case cannot be undone, and nobody is watching when it happens. Least privilege comes first for both agents, because it limits the damage from anything the other layers miss.

    Choose from the following layers according to the risk profile:

    • Input and output screens: a small classifier model checks user messages and the agent's replies.
    • PII redaction at the tool boundary, so sensitive values never enter the context or the transcripts.
    • Deterministic action controls: deny rules and PreToolUse hooks that block a call before it runs.
    • Approval gates, kept for the few irreversible actions a human should actually look at.
    • Sandboxes and containers that limit what a command can reach after every other layer has failed.
    • Refusal handling and fallbacks, so a declined request ends in a safe response rather than a crash.

    Defenses aimed specifically at injected instructions, such as isolating untrusted content, are covered in threat defense for agentic systems.

    Destructive-action prevention starts by sorting actions on whether they can be undone, not on how alarming they sound. Deleting a local build directory is a nuisance. Dropping a production table with no backup is a loss. Spend prevention effort on the second group, and choose the strongest control that still lets the agent do its job: the further a control sits from the model's judgment, the less a bad prompt or a persuasive ticket can do to it.

    Four moves cover most destructive risk, listed from strongest to weakest:

    • Remove the capability. If the agent never needs a shell, disallowed_tools=["Bash"] takes the tool definition out of the request. An MCP tool given the always_deny policy is removed from Claude's context in every permission mode, including bypassPermissions. A tool the model cannot see cannot be misused.
    • Narrow the credentials. An agent that needs to read a staging database gets a role without write or drop grants, so the destructive statement fails at the database even if it is issued. Minimal IAM permissions on the agent's service account follow the same logic.
    • Make the target read-only. Mounting the code directory with :ro lets the agent analyze it but not modify it, which turns deletion from a policy question into an impossibility.
    • Deny the specific form of a call that the agent otherwise needs, using a deny rule or a PreToolUse hook. This is the narrowest control, because it matches command text, so it works best in front of one of the three moves above rather than alone.

    Checkpoint 1 of 6· Check yourself

    A CI agent runs shell commands against a staging database with permission prompts disabled, and nobody watches its runs. When you design its guardrails, which control comes first, and why?

    Sources1234

    2.Deterministic enforcement for irreversible actions

    A rule in a system prompt or CLAUDE.md is input to the model, and other input can outweigh it. When a ticket tells an unattended agent to "clean up old data", the rule against destructive commands is one more piece of text competing with the ticket. A larger model or a more forceful rule changes the odds but guarantees nothing. For an action you cannot undo, the control has to run outside the model and fire every time.

    The hook events show where such a control can sit. PreToolUse fires before a tool call executes and can block it. PostToolUse fires after a tool call succeeds, which for a deletion means after the data is gone. A PostToolUse hook that stops the session when it sees a deletion can raise an alarm, but it cannot prevent the deletion.

    Settings that route Bash calls shaped like rm through a blocking scriptjson
    {
      "hooks": {
        "PreToolUse": [
          {
            "matcher": "Bash",
            "hooks": [
              {
                "type": "command",
                "if": "Bash(rm *)",
                "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh",
                "args": []
              }
            ]
          }
        ]
      }
    }
    The handler denies rm -rf and returns no decision for every other commandbash
    #!/bin/bash
    # .claude/hooks/block-rm.sh
    COMMAND=$(jq -r '.tool_input.command')
    
    if echo "$COMMAND" | grep -q 'rm -rf'; then
      jq -n '{
        hookSpecificOutput: {
          hookEventName: "PreToolUse",
          permissionDecision: "deny",
          permissionDecisionReason: "Destructive command blocked by hook"
        }
      }'
    else
      exit 0  # no decision; normal permission flow applies
    fi

    A hook resolves in four steps. The event fires. The matcher filters by tool name (Bash). The if condition narrows the match to calls shaped like Bash(rm *). Then the handler runs. A handler that returns permissionDecision: "deny" blocks the call, and Claude receives the reason. A handler that exits 0 without output makes no decision, so the normal permission flow applies.

    Static deny rules give the same guarantee without a script. In the Agent SDK, disallowed_tools=["Bash(rm *)"] keeps Bash available but denies matching calls in every permission mode, including bypassPermissions. disallowed_tools=["Bash"] goes further and removes the tool definition from the request. The limitation is that matching works on the command text as written. Other Bash calls, including /bin/rm, fall through to the permission mode. Pattern-based controls stop the obvious form of a command, so they belong in front of a sandbox, not in place of one.

    Where a hook is defined decides who can turn it off. A hook in .claude/settings.json is committed with the project. A hook in managed policy settings applies organization-wide and is controlled by admins. In their locked-down configuration, managed settings block user, project, local and plugin hooks entirely. Claude Code also has one built-in gate. In default mode, an rm or rmdir recognized as removing the working directory or another critical path needs approval, and a matching allow rule doesn't skip that approval. This gate only decides whether to ask. It is a permission gate, not a sandbox, and it does not limit what a command can write.

    Checkpoint 2 of 6· Fill the gap

    This project setting must stop rm -rf before anything is deleted, even when the model has been talked into running it. Which hook event belongs in the blank?

    {
      "hooks": {
        " ? ": [
          {
            "matcher": "Bash",
            "hooks": [
              {
                "type": "command",
                "if": "Bash(rm *)",
                "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh",
                "args": []
              }
            ]
          }
        ]
      }
    }

    Checkpoint 3 of 6· Exam question

    Heron Games runs a live-operations platform for its multiplayer titles, and an unattended CI agent with permission prompts disabled handles maintenance tickets overnight, executing shell commands through its Bash tool. A user-supplied ticket asked it to "clean up old data", and the agent deleted a staging database the QA team needed for a release. The system prompt already forbids destructive commands, and the transcript shows the agent citing the ticket as its justification. Restoring from backup took most of a day because the deletion could not be undone. The engineering director now requires a change that still holds when the model is persuaded by ticket content, with no human reviewing individual commands. What is the most direct control to stop a recurrence?

    Sources523

    3.Approval gates reserved for high-risk actions

    An approval gate is only as good as the attention behind it. When every tool call needs a click, reviewers learn that the answer is always yes. Approving 98% of prompts within three seconds turns the gate into a delay, and the one bulk delete that mattered gets approved along with everything else. The fix is fewer, sharper prompts. Let rules and the sandbox settle routine calls, and keep human approval for actions that cannot be undone or that cross the trust boundary.

    The Agent SDK orders its decisions so that this is possible. Hooks can allow, deny or modify a request. Allow and deny rules settle the calls they match. The permission mode decides what remains. The canUseTool callback comes last and prompts a user only when no earlier step has resolved the call. Allow-listing tools does not hide the others: allowed_tools=["Read", "Grep"] auto-approves those two, and calls to any unlisted tool still fall through to the mode and the callback.

    With sandboxing on, some prompts become unnecessary and others still matter. A bare Bash ask rule is skipped for commands that run sandboxed, because the sandbox already limits what they can reach. A content-scoped ask rule such as Bash(git push *) still forces a prompt, sandboxed or not. That is what a well-placed gate looks like: no prompt for a sandboxed test run, and a prompt for the push that publishes.

    The riskiest moment is when a command fails inside the sandbox and Claude asks to retry it outside. The permission mode decides what happens to that retry:

    What happens when Claude asks to rerun a failed command outside the sandbox
    Permission modeUnsandboxed retry
    bypassPermissionsRuns without a prompt
    Manual and acceptEditsPrompt titled “Bash command (unsandboxed)”
    AutoA separate classifier model evaluates the underlying command
    dontAskClaude Code denies the retry

    Allow rules also apply to the retry. An allow rule such as Bash(curl *) approves the unsandboxed retry as well, so the command runs outside the sandbox without a prompt. An ask rule for Bash(dangerouslyDisableSandbox:true) makes every such retry prompt, even in auto and bypassPermissions mode, and it takes precedence over a matching allow rule. For an agent with nobody watching, set allowUnsandboxedCommands to false to remove the fallback entirely.

    Checkpoint 4 of 6· Check yourself

    With the sandbox enabled, an unattended agent runs in bypassPermissions mode and has an allow rule for Bash(curl *). A curl call fails inside the sandbox, and Claude asks to rerun it outside. What happens to the retry, and what removes this escape route?

    Sources26

    4.Sandboxes that allow tool and web access but keep production out of reach

    A sandbox is the layer that still holds when the model has been fooled and a pattern has been missed. It lets an agent run commands, install packages and reach approved websites while production systems stay unreachable from inside. Claude Code's built-in sandbox uses OS primitives: bubblewrap on Linux and Seatbelt on macOS. Each command runs with its traffic routed through a proxy that allows only the configured domains, and that allowlist starts empty. A connection that tries to bypass the proxy fails.

    Two defaults catch people out. Writes are limited to the working directory, a per-user temp directory and any directories you have added. Reads are not limited this way: they cover most of the machine, including ~/.ssh and ~/.aws/credentials. Environment variables are inherited from Claude Code, including any secrets in them. Close both gaps explicitly:

    Deny the agent's commands access to credential files and token environment variablesjson
    {
      "sandbox": {
        "enabled": true,
        "credentials": {
          "files": [
            { "path": "~/.aws/credentials", "mode": "deny" },
            { "path": "~/.ssh", "mode": "deny" }
          ],
          "envVars": [
            { "name": "GITHUB_TOKEN", "mode": "deny" },
            { "name": "NPM_TOKEN", "mode": "deny" }
          ]
        }
      }
    }

    The sandbox applies only to Bash commands. Built-in tools such as Read, Edit, WebFetch and WebSearch follow permission rules instead, so a denyRead entry does not stop Read, and allowedDomains does not limit WebFetch. Command hooks and local MCP servers run with your full access. Commands listed in excludedCommands also run unsandboxed. Each of these needs its own control.

    For a production agent, isolation usually moves to a container or VM. The hardened container pattern combines several flags. --network none cuts off external networks. Code is mounted read-only. --cap-drop ALL removes Linux capabilities. The process runs as a non-root user. Sensitive host directories such as ~/.ssh or ~/.aws are never mounted. Egress goes through a proxy outside the container that holds the credentials, so the agent never sees them. Credential handling itself is covered in identity and secrets management.

    Isolation technologies compared
    TechnologyIsolation strengthPerformance overhead
    Sandbox runtimeGood (secure defaults)Very low
    Containers (Docker)Setup dependentLow
    gVisorExcellent (with correct setup)Medium/High
    VMs (Firecracker, QEMU)Excellent (with correct setup)High

    Know the limits before you rely on the sandbox. Sandboxed processes share the host kernel, so if a kernel-level escape is in your threat model, use gVisor or a separate VM. By default the proxy checks the hostname the client supplies and does not inspect encrypted traffic, so code inside could use domain fronting to reach hosts outside the allowlist. An allowed domain can still be an exfiltration route if the agent holds permissive credentials for it.

    Checkpoint 5 of 6· Check yourself

    An agent's sandbox is enabled with an empty allowedDomains list, and filesystem.denyRead covers ~/.ssh. No other permission rules are set. Which of these can still reach data outside the boundary?

    Checkpoint 6 of 6· Fill the gap

    Sandboxed commands inherit Claude Code's environment, including any secrets in it. Which key belongs in the blank so GITHUB_TOKEN and NPM_TOKEN are kept away from the agent's commands?

    {
      "sandbox": {
        "enabled": true,
        "credentials": {
          "files": [
            { "path": "~/.aws/credentials", "mode": "deny" },
            { "path": "~/.ssh", "mode": "deny" }
          ],
          " ? ": [
            { "name": "GITHUB_TOKEN", "mode": "deny" },
            { "name": "NPM_TOKEN", "mode": "deny" }
          ]
        }
      }
    }

    Sources36

    Sources

    (6)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “Apply the principle of least privilege so that a successful injection can do minimal damage”
      ↩︎ Fitting guardrail layers to an agent's risk profile
    2. 2.
      “The Bash tool definition is removed from the request.”
      ↩︎ Fitting guardrail layers to an agent's risk profile
      “Calls matching rm * as written are denied in every permission mode, including bypassPermissions.”
      ↩︎ Deterministic enforcement for irreversible actions
      “prompt users for approval at runtime, when no earlier step resolves the call”
      ↩︎ Approval gates reserved for high-risk actions
      “Calls matching rm * as written are denied in every permission mode, including bypassPermissions.”
      ↩︎ Key concept
      “Other tools not listed here still exist, and calls to them that need approval fall through to the permission mode and canUseTool.”
      ↩︎ Exam trap 1
    3. 3.
      “Mounts code read-only so the agent can analyze but not modify it.”
      ↩︎ Fitting guardrail layers to an agent's risk profile
      “A matching allow rule doesn’t skip that approval.”
      ↩︎ Deterministic enforcement for irreversible actions
      “A connection to an outside host that skips the proxy fails.”
      ↩︎ Sandboxes that allow tool and web access but keep production out of reach
      “This is a permission gate, not a sandbox.”
      ↩︎ Exam trap 3
    4. 4.
      “Claude Code removes the tool from Claude’s context in every permission mode, including bypassPermissions.”
      ↩︎ Fitting guardrail layers to an agent's risk profile
    5. 5.
      “Before a tool call executes. Can block it”
      ↩︎ Deterministic enforcement for irreversible actions
      “Your user, project, local, and plugin hooks are blocked.”
      ↩︎ Deterministic enforcement for irreversible actions
    6. 6.
      “Content-scoped ask rules like Bash(git push *) still force a prompt even for sandboxed commands”
      ↩︎ Approval gates reserved for high-risk actions
      “the rule takes precedence over a matching allow rule”
      ↩︎ Approval gates reserved for high-risk actions
      “Inherited from Claude Code, including any secrets in its environment”
      ↩︎ Sandboxes that allow tool and web access but keep production out of reach
      “A denyRead entry doesn’t stop the Read tool, and allowedDomains doesn’t limit WebFetch”
      ↩︎ Exam trap 2
      “it also approves the retry, so the command runs outside the sandbox with no prompt”
      ↩︎ Checkpoint
      “A denyRead entry doesn’t stop the Read tool, and allowedDomains doesn’t limit WebFetch”
      ↩︎ Checkpoint

    Continue to part 2 of 2

    Screening agent content: classifiers, PII redaction, refusals and tuning

    Spotted a mistake, or was something unclear? Tell us.