Skip to content
New: answer your agents from your phoneLearn more

Claude Code hooks, with a real example.

Hooks run your own commands at fixed points in a Claude Code session. Add your first one, learn the five events you'll use most, then see a hook that cuts what the agent reads from command output by 90%.

What Claude Code hooks are

A hook is a shell command Claude Code runs at a set point in a session: before a tool runs, after it finishes, when Claude needs your input, when it stops. The agent doesn't decide whether to run it, so use hooks for anything that must happen every time, like formatting a file after an edit or blocking a dangerous command.

Add your first hook

Hooks live in a hooks block in a Claude Code settings file. This one, adapted from Claude Code's hooks guide, shows a macOS notification whenever Claude is waiting for you. Add it to ~/.claude/settings.json, creating the file if it doesn't exist:

{
  "hooks": {
    "Notification": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
          }
        ]
      }
    ]
  }
}

Type /hooks in Claude Code to check it's listed under Notification. If your settings already have a hooks block, add the new event beside the existing ones rather than replacing it.

The file you put a hook in sets its reach: ~/.claude/settings.json for all your projects, .claude/settings.json in a repository to share it with your team, or .claude/settings.local.json for that project on your machine only.

The hooks you'll use most

  • PreToolUse runs before a tool call and can block it, for example refusing edits to a lock file.
  • PostToolUse runs after a tool call succeeds, for example running a formatter on the file Claude just edited, or changing what Claude reads back.
  • Notification runs when Claude Code sends a notification, such as waiting for a permission decision.
  • Stop runs when Claude finishes responding.
  • SessionStart runs when a session starts or resumes, and can add context to it.

The matcher narrows a tool hook to certain tools: "Bash" for shell commands, "Edit|Write" for file edits.

How a hook talks back

Claude Code passes the event to your command as JSON on standard input: the session, the working directory, and for tool hooks the tool's name and input, plus its result after it runs. Your command answers with its exit code. Exit 0 lets things carry on. Exit 2 blocks the action, and what you print to standard error tells Claude why. For finer control, exit 0 and print a JSON object instead, which is how a PostToolUse hook replaces what Claude reads.

Example: trimming command output

A coding agent runs cargo test and thirty-seven tests pass. The agent reads forty-four lines to learn that, and it reads them again on every later turn, because a tool result stays in the conversation for the rest of the session.

ket uses a PostToolUse hook to trim that. The same command, as the model receives it:

    Finished `test` profile [unoptimized + debuginfo] target(s) in 1.79s

running 37 tests
37 passed

test result: ok. 37 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
[ket: 44 lines → 6 · ≈686 → 49 tokens · full output in the session transcript]

2,745 bytes became 275, 90% less to read. The trim kept the summary line, and it would have kept a warning or a failure too.

Why trim after the command runs

We first tried rewriting the command before it ran, piping its output through a filter. We threw that away. A pipeline reports the filter's exit status instead of the test runner's, so a filter one pattern short turns a failing run into a green one, and the agent carries on building on a failure it was told didn't happen.

A PostToolUse hook runs once the command has finished, so the command runs exactly as the agent wrote it and reports its own exit status. ket then trims the output only when all of this holds:

  • The command succeeded. PostToolUse fires only on success, so a failed run reaches the agent whole.
  • ket has a recipe for the program: cargo, go, pytest, jest, package installs, listings and diffs. Anything else passes through untouched.
  • The output is long enough to bother with, and the recipe cuts enough of it.

The recipes stay simple. A build loses its Compiling lines and keeps each warning whole. A test run collapses its passes to a count and keeps any line that says FAILED or panicked. A listing folds repeats into one line with a count. Long output loses its head and keeps its tail, where the summary is.

The gotcha: match the tool's output shape

To replace what the model reads, a PostToolUse hook returns updatedToolOutput. For the Bash tool it must be an object in the tool's own shape, not a string:

{
  "hookSpecificOutput": {
    "hookEventName": "PostToolUse",
    "updatedToolOutput": { "stdout": "…", "stderr": "", "interrupted": false }
  }
}

Our first version returned a plain string, and Claude Code ignored it without an error: the hook fired, trimmed the output, and the model read the original anyway. Check the session transcript, which records what the model received.

Don't judge a hook like this by the cost figures either. Claude Code serves identical reruns from the prompt cache, and the rest of the prompt shifts between runs by more than the few hundred tokens a trim saves. Compare the tool result's size before and after instead.

Nothing extra written to disk

The trailer says where the rest went. By default that's the session transcript, which Claude Code keeps and which holds every tool result whole. ket writes no second copy, because command output can include a token or an environment variable. If you want ket recall <id>, turn the copy on in config; ket then writes it readable only by you and deletes it after a day.

Turning it on in ket

The filter is a setting on an Economy level, in the pack your team loads from its own URL. The standard pack turns it on at Heavy and Max, alongside a cap on how much successful output the agent takes inline. Your own config overrides the pack either way. It works with Claude Code today; Codex can replace a tool result from a hook too, but only by framing the replacement as a block, which tells the model something different.