On this pageHow do Codex hooks work?

Codex Hooks: How to Set Them Up and Use Them

Xtrusio5 min read

Short answer

Short answer: Codex hooks run a script or MCP tool when a chosen event occurs, such as before a local tool call. Define the hook in hooks.json or config.toml, then review and trust it with /hooks in the Codex CLI.

A developer at a code display beside the headline Codex Hooks

How do Codex hooks work?

A tool call triggers a hook event

  • PreToolUse

if the tool name matches

A matcher decides whether that event fits the rule

  • Bash

then the handler runs

The handler runs your script or MCP tool

  • handler

A tool call triggers an event such as PreToolUse. A matcher decides whether the call fits your rule. If it does, the handler runs your script or an MCP tool. A hook can log activity, check a prompt before submission or validate work when a turn stops.

Where should I put the hook?

Choose a user file when the hook should apply across projects. Choose a repository file when the rule belongs with one codebase.

Scope

JSON file

Inline configuration

User

~/.codex/hooks.json

~/.codex/config.toml

Repository

<repo>/.codex/hooks.json

<repo>/.codex/config.toml

Hooks add up across layers: Codex runs the matching hooks from every active layer, and a higher layer never replaces a lower one. Keep one format per layer; if a layer has both, Codex merges them and warns at startup. Repository hooks load only after you trust the project .codex/ layer.

How do I block a dangerous command with a hook?

Open the Codex CLI inside a Git repository. Then save a policy script, point a hook at it, and test it.

  1. Save the policy script as .codex/hooks/pre_tool_use_policy.py. This is our example, not OpenAI's. It reads the Bash command and prints a deny response when it finds rm -rf.For PreToolUse, Codex reads the JSON response and ignores plain text your script prints.
import json
import re
import sys

payload = json.load(sys.stdin)
tool_name = payload.get("tool_name", "")
command = payload.get("tool_input", {}).get("command", "")

if tool_name == "Bash" and re.search(r"(^|\s)rm\s+-rf(\s|$)", command):
    print(json.dumps({
        "hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "permissionDecision": "deny",
            "permissionDecisionReason": "Destructive command blocked by hook."
        }
    }))
  1. Add the hook entry in .codex/hooks.json. The command finds the script from the Git root.Prefer config.toml? The same hook can go there:
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "^Bash$",
        "hooks": [
          {
            "type": "command",
            "command": "/usr/bin/python3 \"$(git rev-parse --show-toplevel)/.codex/hooks/pre_tool_use_policy.py\"",
            "statusMessage": "Checking Bash command"
          }
        ]
      }
    ]
  }
}
[[hooks.PreToolUse]]
matcher = "^Bash$"
[[hooks.PreToolUse.hooks]]
type = "command"
command = '/usr/bin/python3 "$(git rev-parse --show-toplevel)/.codex/hooks/pre_tool_use_policy.py"'
timeout = 30
statusMessage = "Checking Bash command"
  1. Test the script by hand with this input:It should print a deny response.
printf '%s' '{"tool_name":"Bash","tool_input":{"command":"rm -rf build"}}' | python3 .codex/hooks/pre_tool_use_policy.py
  1. Test it in the CLI. Open /hooks, review the definition and trust it. Make an empty folder named build and ask Codex to run rm -rf build. The hook should block it.

Which events can you hook?

The table shows when each event runs and which events support a matcher.

Event

When it runs

Matcher filters

PreToolUse

Before a supported local tool

Tool name

PostToolUse

After a supported local tool

Tool name

PermissionRequest

When Codex requests permission

Tool name

SessionStart

When a session starts

Startup, resume, clear, compact or fork

PreCompact and PostCompact

Around compaction

Manual or auto

UserPromptSubmit

Before a prompt is submitted; a block reply stops submission

Ignored

Stop

When Codex is ready to finish its response; a block reply makes Codex continue, with your reason as its next prompt

Ignored

A matcher is a regular expression that picks which calls fire the hook. For tool events it matches the tool name, and shell commands count as Bash, so ^Bash$ fires only for shell commands. An asterisk, an empty string or no matcher fires on every call. Compaction events match manual or auto. UserPromptSubmit and Stop ignore matchers, so put that condition inside your script.

For UserPromptSubmit, this response blocks a prompt:

{
  "decision": "block",
  "reason": "Ask for confirmation before doing that."
}

Use PreToolUse when the decision must happen before a local tool call. Use PostToolUse for review or logging after output exists. Use UserPromptSubmit when the policy is about the user's prompt.

Put a policy before the action: a hook that runs after a tool cannot undo a file change or a command that already ran.

Should I use a command or an MCP tool?

Command handlers run a local process and receive their input as JSON on standard input. They are a practical fit for a repository script that already lives beside the code. An MCP tool handler calls a configured server tool instead. Codex does not run prompt or agent handlers, so use a command or an MCP tool.

Use synchronous handlers for policy. Setting async to true starts a command hook in the background while work continues. That is useful for logging. A hook that runs in the background cannot block, approve or change the action that started it. A command hook's timeout is measured in seconds; when omitted, most hooks use 600 seconds.

What can hooks not intercept?

Hosted tools such as WebSearch skip the local hook path, so PreToolUse and PostToolUse never fire for them. Treat hooks as a guardrail, not a complete security wall.

Why is my hook not running?

Start with the feature setting and the tool path.

  • If your config.toml turns hooks off, delete that line or set hooks = true.
[features]
hooks = false
  • If the hook never fires, compare its matcher with the tool name shown by Codex.

Older guides may tell you to enable codex_hooks. OpenAI now calls it a deprecated alias of hooks.

Frequently asked questions

Are Codex hooks on by default?

Yes. To turn them off, set hooks = false under [features] in config.toml.

Can I disable one hook?

Yes. Open /hooks in the Codex CLI and disable that non-managed hook.

What happens if a hook times out?

The tool can still run. A PreToolUse hook that errors or times out does not block the call.

Sources

  1. Hooks, OpenAI

Topics

  • codex hooks

Xtrusio

AI visibility research

Xtrusio is the Perception Engine for B2B brands.

Free check

See how AI engines answer about you

Get your free AI visibility check

Talk to us about the managed plan (free trial)