agexsDocs

Claude Code hooks: events, settings.json and examples

Claude Code hooks explained: every hook event, the settings.json format, matchers, exit codes and JSON that block or allow, plus examples and security tips.

Claude Code hooks are commands, HTTP endpoints, MCP tools or prompts that Claude Code runs at fixed points in a session: before a tool call, after an edit, when you submit a prompt, when a session starts. You define them in settings.json. A hook gets the event as JSON, and it can block the action, allow it, or add text to Claude's context through its exit code and output.

What a hook is

The hooks reference lists five handler types:

  • command: a shell command. It reads the event JSON on stdin and answers with an exit code and stdout.
  • http: a POST of the same JSON to a URL. The response body uses the same JSON format.
  • mcp_tool: a call to a tool on an MCP server you have configured.
  • prompt: a single-turn check by a Claude model that returns a decision as JSON.
  • agent: a subagent that can read files before it decides. Marked experimental.

Most hooks are command hooks. The rest of this guide uses them.

Every hook event

Events fire per session (SessionStart, SessionEnd), per turn (UserPromptSubmit, Stop) or on every tool call (PreToolUse, PostToolUse). These are the ones you will use most:

EventWhen it firesMatcher filtersCan block on exit 2
SessionStartA session starts or resumesstartup, resume, clear, compact, forkNo
UserPromptSubmitYou submit a prompt, before Claude sees itNo matcherYes, rejects the prompt
PreToolUseBefore a tool call runsTool nameYes, blocks the call
PermissionRequestA tool call needs a permission decisionTool nameNo, use the JSON decision
PostToolUseAfter a tool call succeedsTool nameNo, stderr goes to Claude
PostToolUseFailureAfter a tool call failsTool nameNo, stderr goes to Claude
NotificationClaude Code sends a notificationNotification typeNo
SubagentStart, SubagentStopA subagent starts or finishesAgent typeStop only
StopClaude finishes respondingNo matcherYes, Claude keeps working
PreCompact, PostCompactBefore and after compactionmanual, autoPreCompact only
SessionEndThe session endsWhy it endedNo

Checked November 2026.

The reference lists more: Setup, UserPromptExpansion, PreSkillShellCommand, PostToolBatch, PermissionDenied, MessageDisplay, TaskCreated, TaskCompleted, StopFailure, TeammateIdle, InstructionsLoaded, ConfigChange, CwdChanged, DirectoryAdded, FileChanged, WorktreeCreate, WorktreeRemove, PreModelSwitch, PostModelSwitch, Elicitation and ElicitationResult. Each has its own input fields and decision rules in the hook events section.

The settings.json format

Hooks nest three levels deep: the event, a matcher group, and one or more handlers.

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "/path/to/lint-check.sh", "timeout": 30 }
        ]
      }
    ]
  }
}

Where you put it sets the scope:

  • ~/.claude/settings.json: all your projects, only on your machine.
  • .claude/settings.json: one project, can be committed to git.
  • .claude/settings.local.json: one project, not shared.
  • Managed policy settings: set by an admin for the organization.
  • A plugin's hooks/hooks.json, or the frontmatter of a skill or subagent.

Hooks from different files add up; they do not replace each other. Type /hooks in Claude Code to see every configured hook and where it comes from. "disableAllHooks": true turns them all off, but not managed hooks from outside managed settings.

Use ${CLAUDE_PROJECT_DIR} to point at scripts in the repo, such as "${CLAUDE_PROJECT_DIR}/.claude/hooks/check.sh".

Matchers and the if field

The matcher decides when a group fires. Its meaning depends on the characters in it:

  • "*", "" or no matcher: every occurrence.
  • Only letters, digits, _, -, spaces, , and |: exact names. Bash matches the Bash tool; Edit|Write matches either.
  • Any other character: an unanchored JavaScript regex. mcp__memory__.* matches every tool of the memory MCP server. Edit.* also matches NotebookEdit, so write ^Edit$ for an exact match.

For tool events, a handler can also set if with permission rule syntax, for example "Bash(git *)" or "Edit(*.ts)". The docs call this filter best effort: for hard allow and deny, use the permission system.

Exit codes and JSON output

A command hook talks back through its exit code:

  • Exit 0: success. Claude Code reads any JSON on stdout. On SessionStart and UserPromptSubmit, plain text stdout is added to Claude's context.
  • Exit 2: blocking error. On events that can block, the action stops and stderr is the reason. A PreToolUse hook that exits 2 blocks the call, and Claude sees the stderr.
  • Any other code: non-blocking error. The action goes ahead. That includes exit 1, so a policy hook must use exit 2.

For finer control, exit 0 and print one JSON object, and nothing else, on stdout. For PreToolUse the decision goes in hookSpecificOutput:

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Database writes are not allowed"
  }
}

permissionDecision can be allow (skip the prompt), deny (block the call), ask (prompt the user) or defer (only in -p mode). When several hooks disagree, deny wins over defer, then ask, then allow. A hook's allow does not bypass deny rules from settings. A hook's deny holds in every permission mode, including bypassPermissions.

UserPromptSubmit, PostToolUse, Stop and some others use a top-level "decision": "block" with a reason instead. Universal fields such as continue: false with a stopReason stop Claude entirely, and systemMessage shows a warning to the user. The decision control table lists which fields each event reads.

Example: block rm -rf

Save this as .claude/hooks/block-rm.sh and make it executable. It needs jq.

#!/bin/bash
cmd=$(jq -r '.tool_input.command')
if echo "$cmd" | grep -Eq '(^|[;&| ])rm +-[a-zA-Z]*r[a-zA-Z]*f|rm +-[a-zA-Z]*f[a-zA-Z]*r'; then
  echo "Blocked: rm -rf is not allowed. Delete files one by one or ask the user." >&2
  exit 2
fi
exit 0

Register it on PreToolUse for the Bash tool:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "\"${CLAUDE_PROJECT_DIR}\"/.claude/hooks/block-rm.sh",
            "onFailure": "block"
          }
        ]
      }
    ]
  }
}

By default a hook that times out, cannot start or has a wrong path does not block. onFailure: "block" makes the call fail closed instead. It needs a recent Claude Code version. A regex on a command string is easy to get around, so treat this as a guard against mistakes, not a sandbox.

Example: auto-format after edits

From the hooks guide: run Prettier on every file Claude writes or edits.

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\""
          }
        ]
      }
    ]
  }
}

A successful run shows nothing in the chat. PostToolUse cannot undo the edit; exit 2 only sends stderr to Claude.

Example: inject context

On UserPromptSubmit and SessionStart, plain stdout becomes context. This adds the current branch to every prompt:

{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          { "type": "command", "command": "echo \"Current git branch: $(git branch --show-current)\"" }
        ]
      }
    ],
    "SessionStart": [
      {
        "matcher": "compact",
        "hooks": [
          { "type": "command", "command": "echo 'This repo uses Bun, not npm. Run bun test before committing.'" }
        ]
      }
    ]
  }
}

The compact matcher runs after every compaction, so key facts come back after the summary. You can also return additionalContext inside hookSpecificOutput. Some limits from the docs:

  • Each string is capped at 10,000 characters. Longer output goes to a file, and Claude only gets a path and a preview.
  • Write facts ("The deploy target is staging"), not system style orders, or Claude may treat the text as a prompt injection.
  • UserPromptSubmit hooks default to a 30 second timeout. A stuck hook stalls every prompt.
  • For text that never changes, CLAUDE.md is the better place.

Security notes

The security section is short and worth reading:

  • Command hooks run with your full user permissions. Review every hook before you add it.
  • In an interactive session, hooks wait until you accept the workspace trust dialog for the folder. In -p and SDK sessions there is no dialog, so hooks in a repo's .claude/settings.json run in a folder you never trusted. Review .claude/ first, or pass --settings '{"disableAllHooks": true}'.
  • Quote shell variables ("$VAR"), check file paths for .., use absolute paths, and skip .env, .git/ and keys.
  • Admins can set allowManagedHooksOnly in managed settings so that only managed hooks run.

Where plain hooks stop

Hooks are a good engine, but each one is a script you write and keep up to date:

  • Scripts per machine and repo. Every teammate needs the same files and settings, and a fix has to reach all of them.
  • Fail open by default. A wrong path or a timeout lets the action through unless you set onFailure.
  • Block or allow, little in between. "Ask me first, but only in production" or "remind once per session" means writing that logic yourself.
  • No memory. A hook can print static text or run a command, but it does not learn from what you correct.

How agexs brain uses hooks

agexs brain is shared memory for coding agents, and it runs through these same hook events. Its Claude Code plugin adds hooks on session start, every prompt, tool calls and the end of each answer.

  • Memories pushed in: your always-on rules at session start, a project's memories on the first work there, and matching memories on every prompt.
  • Rules the agent cannot skip: a rule can block a command or edit, stop and ask you first, remind the agent at the right moment, or add memories. You write it in plain words in chat, and it works once you confirm it.
  • Trial run: before you save a rule, it shows how often the rule would have fired in the last 7 days.
  • One place for the team: rules can apply to everyone, one person or one space.

If agexs brain is unreachable, its hooks give up after a few seconds and the agent keeps working. An owner can set risky commands to be blocked in that case.

Setup

Install the agexs CLI, then:

agexs login
agexs install claude

This installs the Claude Code plugin with its hooks and MCP server. Your own hooks in settings.json keep running next to it. See Plans and billing.

FAQ

Where do I put Claude Code hooks?

In a settings file under "hooks": ~/.claude/settings.json for all projects, .claude/settings.json to share with a repo, or .claude/settings.local.json for yourself only. Plugins, skills and subagents can bring their own.

How do I block a command with a Claude Code hook?

Add a PreToolUse hook with matcher Bash, read tool_input.command from stdin, and exit 2 with a reason on stderr. Or exit 0 and print JSON with permissionDecision set to deny.

Why does my hook not block anything?

Exit 1 does not block; only exit 2 does. Also check that stdout holds only the JSON object (shell profile output breaks it), that the script path exists, and that the hook did not time out.

Can a hook add context to Claude?

Yes. On SessionStart and UserPromptSubmit, plain stdout is added as context. Other events such as PreToolUse and PostToolUse accept additionalContext in hookSpecificOutput.

Do hooks run in bypassPermissions mode?

Yes. PreToolUse hooks fire in every permission mode, and a deny blocks the tool even with --dangerously-skip-permissions.

Last updated on

On this page