Practical technical guides / Recent development

Codex 0.173.0 Lets a Failed PreToolUse Hook Block the Tool

Codex rust-v0.173.0 adds onFailure block for synchronous hooks. What counts as a failure, which events support it, and how to write a guard that fails closed.

By Sandeep Belgavi · Published 2026-12-02

Codex rust-v0.173.0 adds onFailure block for synchronous hooks. What counts as a failure, which events support it, and how to write a guard that fails closed.

The release note

Codex rust-v0.173.0, published on 2 December 2026, adds an opt-in failure policy for supported synchronous command and MCP tool hooks. Setting onFailure to block can stop a tool when its PreToolUse check fails. The change is pull request 62831, "Let required hooks block continuation on failure", merged on 20 November. The option is not present in the configuration schema at rust-v0.172.0.

Hooks in Codex run your own code at points in the agent's loop: before a tool call, when a permission is requested, after a tool returns, when a prompt is submitted, before and after context compaction, when a session or subagent starts, when the agent wants to stop, and on interrupt. A hook can be a shell command or a call to a tool on an MCP server. Teams use them as guards: a PreToolUse hook that scans a shell command for secrets or destructive patterns, or a policy check that denies writes outside a directory.

Until this release, a guard that failed was treated as a guard that had nothing to say. If the scanner crashed, timed out or returned output that could not be parsed, the hook was recorded as failed and the tool call went ahead. For a guard, that is fail-open: the check exists to stop risky calls, and the moments it cannot run are exactly the moments nobody is checking. The new option lets you choose fail-closed per handler.

What counts as a failure

The tests that ship with the change were inspected, in the hooks crate's failure policy test file, because they state the behaviour more precisely than the release note. The policy enum in the configuration schema has two values, continue and block, and continue is the default. The tests run each case under no policy, continue and block, and assert that the call is blocked only when the policy is block and the hook failed.

Hook outcomeCounted as a failureBlocks with onFailure block
MCP tool returns an erroryesyes
MCP server disconnectsyesyes
MCP request times outyesyes
Output that is not valid JSON, such as an unterminated objectyesyes
Empty output or an empty JSON objectnono
Plain text such as hook finishedonly for Stop, SubagentStop and Interruptonly for those events
Command hook that fails to startyesyes
Command exits non-zero, prints invalid JSON or exceeds its timeoutyes, in the Unix testsyes
Command exits 0 with no outputnono

Each failed run is recorded with an error entry, with status Blocked when the policy blocked and Failed when it did not. A completed hook has status Completed and no error entry.

Two more tests matter for design. In the first, two hooks are registered for the same event: a command hook with onFailure set to block that fails, and an MCP hook that succeeds and explicitly allows the call, for PreToolUse even rewriting the input. The call is still blocked. A failure-block cannot be outvoted by another hook's approval. In the second, configurations that the engine cannot enforce are rejected when hooks load: onFailure set to block on an asynchronous handler, on a SessionEnd hook, or on a PreModelRequest or PostModelRequest hook produces a load error that begins onFailure:block requires a synchronous, and the handler is not registered. The tests cover the eleven events that support it: PreToolUse, PermissionRequest, PostToolUse, PreCompact, PostCompact, SessionStart, UserPromptSubmit, SubagentStart, SubagentStop, Stop and Interrupt.

What blocking means depends on the event. For PreToolUse, the tool does not run, and the reason recorded says the hook failed and is configured to block continuation on failure. For PermissionRequest, the request is denied. For PostToolUse, the tool has already run; blocking returns feedback instead of continuing normally. For Interrupt, cancellation has already happened, and the tests note that only the hook's lifecycle status changes.

Configuring a fail-closed guard

In a hooks.json file, the option sits on each handler. This example uses the Bash tool name from the upstream tests. Confirm the actual tool name and input fields exposed by your installation; an unmatched guard never runs:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "^Bash$",
        "hooks": [
          {
            "type": "command",
            "command": "python3 /opt/guards/shell_guard.py",
            "timeout": 10,
            "onFailure": "block"
          }
        ]
      }
    ]
  }
}

The same handler can be written in TOML configuration as a [[PreToolUse]] table with a matcher and a nested [[PreToolUse.hooks]] table holding type, command, timeout and onFailure.

The guard itself should treat its own uncertainty as failure. A script that catches every exception and prints an empty object turns a crash into a pass, and the new option never sees it. Let unexpected errors escape, exit non-zero, and keep the allowed path explicit.

import json
import re
import sys

DENY = [re.compile(p) for p in (r"\brm\s+-rf\s+/", r"\bcurl\b.*\|\s*sh\b", r"AKIA[0-9A-Z]{16}")]

def decide(event: dict) -> dict:
    command = event["tool_input"]["command"]          # KeyError on malformed input: exit non-zero
    for pattern in DENY:
        if pattern.search(command):
            return {"hookSpecificOutput": {"hookEventName": "PreToolUse",
                                           "permissionDecision": "deny",
                                           "permissionDecisionReason": f"blocked by {pattern.pattern}"}}
    return {}

if __name__ == "__main__":
    print(json.dumps(decide(json.load(sys.stdin))))

The regex checks are a teaching fixture, not a shell parser or a security boundary; quoting, alternate commands and indirect execution can evade them. Use sandbox permissions and structured action adapters for enforcement. This guard has three outcomes: a deny decision, an empty object that lets the call proceed, and an uncaught exception. With onFailure set to block, the third outcome now stops the tool instead of letting it through.

Worked example: a guard with an unreliable scanner

An engineering team runs Codex against a repository that contains the store's order export scripts. They have a PreToolUse guard that calls an internal MCP scanner to check shell commands for paths outside the repository. Suppose the scanner's server restarts during a deploy and, for a couple of minutes, every hook call fails with a disconnect. Under the default policy each of those calls is recorded as a failed hook and the shell command runs unchecked; the test table above shows a disconnect counts as a failure. With onFailure set to block, the same minutes produce blocked tool calls with a recorded reason instead.

The cost is availability. A guard that blocks on failure makes the guard's uptime part of the agent's uptime. That trade is right for guards that protect against irreversible actions and wrong for hooks that only add context or logging.

Rollout steps

  1. Upgrade to rust-v0.173.0 or later everywhere the hooks are used, including CI runners. Older versions do not know the option.
  2. Classify each hook as a guard or as an enrichment. Only guards get block.
  3. Make each guard fail loudly: no blanket exception handlers that print an empty object, and a timeout shorter than the hook timeout for any network call inside it.
  4. Set onFailure to block on guards and keep the default on everything else.
  5. Run the hook outside Codex with valid input, malformed input and a stopped dependency, and check the exit status and output in each case.
  6. Watch the hook run statuses after rollout. A rise in Blocked runs means a guard dependency is unhealthy, not that the agent is misbehaving.

Failure modes

  • Asynchronous guards. A guard configured as asynchronous cannot block, and the configuration with block fails to load. Make guards synchronous.
  • Fail-closed stops. A failed Stop hook with block keeps the agent from finishing its turn normally. If the dependency behind it stays down, every attempt to finish fails the same way. Use block on Stop only for checks that must pass before work is handed back.
  • Text output on stop-type events. Plain text output from a Stop, SubagentStop or Interrupt hook counts as a failure. A hook that prints a friendly message there will block if the policy is block.
  • Mixed versions. Configuration shared between users on different Codex versions behaves differently. Pin the version in team setup.

When you do not need it

Hooks that format output, add context or log events should keep the default. Their failure should never stop work. If a guard's dependency is not reliable enough to be on the critical path, fix the dependency or move the check to a place where failure is easier to handle, such as a sandbox or a permission rule, before turning on blocking.

How to verify it

The companion example codex_hook_failure_policy contains the guard above and tests that drive it with a safe command, a denied command, malformed input and a simulated scanner outage, asserting the exit status and output for each. It also checks a hooks.json file against the rules from the tests: guards marked block must be synchronous and attached to a supported event. It does not run Codex itself, so pair it with one manual run of a blocked tool call on the version you deploy.

Primary references and authorship

Sources checked 2026-12-02. Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/codex_hook_failure_policy. Views are my own and do not represent any employer, past or present.