Skip to main content

08 - Claude Code Hooks: automation event-driven

Claude Code hooks: a PreToolUse guard and a PostToolUse log tested on sample inputs, with the exit code that blocks and the known limits.

What do you think about this article?

08 - Claude Code Hooks: automation event-driven
Claude Skills & MCPPhoto:Matheus BertelliPexels

At a Glance

Claude Code hooks: a PreToolUse guard and a PostToolUse log tested on sample inputs, with the exit code that blocks and the known limits.

You want certain things to happen always, even when the model forgets: that a file with secrets is never overwritten, that every edit leaves a line in a log, that a notification arrives when the work is done. The instructions written in a skill are a suggestion to the model; a Claude Code hook is a command that starts by itself, at a precise point in the session lifecycle, and that can also block what is about to happen. It is the part of the series with the highest risk and the greatest usefulness, because it runs code with your permissions without asking. Here I write a guard and a log, try them on sample inputs without starting any model, and line up the traps the documentation declares.

Hooks are not part of the MCP protocol: they are a Claude Code feature, as seen in the third article. They do meet MCP at two points, though: server tools appear in events like any other, with the name mcp__server__tool, and one hook type can itself call an MCP tool. How to move from controlling what runs to observing it you can find in the article on debugging and traces.

What a hook is, and what it receives

A hook is defined in Claude Code's settings files with three levels of nesting: an event (PreToolUse, PostToolUse, Stop and others), a group with a filter (matcher) and one or more handlers. The documentation lists five handler types: shell command, HTTP request, MCP tool call, prompt to a model and subagent; the first three do not involve a model, the last two have a model decide, and the documentation flags the agent as experimental. Here I use only commands, the only ones I can try without models. The events are many (the official table lists more than thirty) and group by frequency: one per session, one per turn, and two for each tool call, before and after.

A command-type hook receives on stdin a JSON object with fields common to all events and fields specific to the event. For tool events, the ones needed here, the fields are these.

FieldWhat it contains
session_idSession identifier
cwdWorking folder at the time of the call
hook_event_nameName of the event that fired
tool_nameTool name (Bash, Write, Edit, or mcp__server__tool)
tool_inputTool arguments; for Write and Edit it contains file_path, always absolute
tool_responseOnly in PostToolUse: the result

Two details in the documentation avoid recurring mistakes. The file path arrives already absolute and with the platform's separators: on Windows with the backslash, so a comparison written with the forward slash never matches and the call proceeds as if the hook had nothing to block. And hooks start from a shell with no terminal: they cannot write to /dev/tty, and to show a message to the user you need JSON fields such as systemMessage.

A guard: blocking writes to sensitive paths

The guard sits in the PreToolUse event, which fires after the model has composed the arguments and before the tool runs, and is the natural point to stop a write before it happens. It reads the JSON, extracts tool_input.file_path, normalizes it and compares it with three rules: climbing up a folder (..), the .git and .ssh folders, files that start with .env or end with .pem and .key. If a rule fires, it writes the reason to stderr and exits with code 2.

"""PreToolUse hook: refuses Write and Edit on protected paths. It also refuses when it does not understand the input."""
import json
import posixpath
import sys

SEGMENTI_PROTETTI = {".git", ".ssh"}
SUFFISSI_PROTETTI = (".pem", ".key")


def motivo_del_rifiuto(percorso):
    # Windows delivers paths with backslashes: normalize before comparing
    normalizzato = posixpath.normpath(percorso.replace("\\", "/"))
    segmenti = normalizzato.split("/")
    if ".." in percorso.replace("\\", "/").split("/"):
        return "the path contains '..'"
    if SEGMENTI_PROTETTI & set(segmenti):
        return f"the folder {sorted(SEGMENTI_PROTETTI & set(segmenti))[0]} is protected"
    nome = segmenti[-1]
    if nome.startswith(".env") or nome.endswith(SUFFISSI_PROTETTI):
        return f"{nome} may contain secrets"
    return None


def main():
    try:
        evento = json.load(sys.stdin)
        percorso = evento["tool_input"]["file_path"]
    except (json.JSONDecodeError, KeyError, TypeError):
        print("guard: input not recognized, blocking to be safe", file=sys.stderr)
        return 2
    motivo = motivo_del_rifiuto(percorso)
    if motivo:
        print(f"Write refused: {motivo}.", file=sys.stderr)
        return 2
    return 0


if __name__ == "__main__":
    sys.exit(main())

Three lines decide. The normalization with replace and posixpath.normpath makes Windows and Unix paths uniform, for the reason seen in the previous section. The return 2 is the block: the reason on stderr reaches the model as the reason for the refusal, so a well-written message tells it what to do instead. And the except branch chooses a behavior for incomprehensible input: the guard blocks, to be safe. A security check that, when in doubt, lets things through is a check that can be bypassed by feeding it a strange input. The price is the false positive: .env.example, for instance, turns out blocked like .env, and has to be handled with a finer rule if you need to write it.

The exit code: 2 blocks, 1 does not

Here is the costliest trap. The documentation defines three outcomes: with exit 0 the action proceeds (and any JSON fields printed apply); with exit 2 the action is blocked, where the event allows it; with any other code, including 1, the error is non-blocking and the action proceeds, and only a warning appears in the transcript. A guard that exits with 1 after writing "refused" to stderr therefore gives the impression of working and blocks nothing. I wrote the wrong variant of the guard (identical, with return 1 in place of return 2) and a small program that applies the documentation's table to the two scripts, with sample inputs built with the fields listed above.

"""Reproduces the documented table (exit code x stdout) and tries the guards on sample inputs."""
import json
import subprocess
import sys


def esito(codice, stdout):
    """What Claude Code does with the call, according to the documentation table (PreToolUse only)."""
    try:
        campi = json.loads(stdout).get("hookSpecificOutput", {}) if stdout.strip().startswith("{") else {}
    except json.JSONDecodeError:
        campi = {}
    if codice == 2:
        return "BLOCKS"
    if campi.get("permissionDecision") == "deny":
        return "BLOCKS"
    return "proceeds" if codice == 0 else "proceeds (non-blocking error)"


def evento(strumento, percorso):
    return json.dumps({"session_id": "s1", "cwd": "/project", "hook_event_name": "PreToolUse",
                       "tool_name": strumento, "tool_input": {"file_path": percorso, "content": "x"}, "tool_use_id": "t1"})


CASI = [
    ("Write", "/project/src/app.py"),
    ("Edit", "/project/.env"),
    ("Write", "/project/.git/config"),
    ("Write", "C:\\project\\.git\\config"),
    ("Write", "/project/src/../.env.local"),
    ("Write", "/project/keys/server.pem"),
]
for script in ("guardia.py", "guardia_sbagliata.py"):
    print(f"== {script}")
    for strumento, percorso in CASI + [("Write", None)]:
        ingresso = evento(strumento, percorso) if percorso else "not json"
        p = subprocess.run([sys.executable, script], input=ingresso, capture_output=True, text=True)
        motivo = p.stderr.strip() or "-"
        print(f"{(percorso or '(malformed input)'):<34} exit={p.returncode} {esito(p.returncode, p.stdout):<32} {motivo}")

The esito function is a reproduction of the documented table for the PreToolUse event, not Claude Code's code: exit 2 always blocks; with other codes a valid JSON with permissionDecision: "deny" blocks, otherwise the action proceeds. The CASI list contains a normal file, two sensitive paths in Unix form, one in Windows form, one with folder climbing, a .pem key, plus an input that is not JSON.

$ python esito.py
# Output:
# == guardia.py
# /project/src/app.py                exit=0 proceeds                         -
# /project/.env                      exit=2 BLOCKS                           Write refused: .env may contain secrets.
# /project/.git/config               exit=2 BLOCKS                           Write refused: the folder .git is protected.
# C:\project\.git\config             exit=2 BLOCKS                           Write refused: the folder .git is protected.
# /project/src/../.env.local         exit=2 BLOCKS                           Write refused: the path contains '..'.
# /project/keys/server.pem           exit=2 BLOCKS                           Write refused: server.pem may contain secrets.
# (malformed input)                  exit=2 BLOCKS                           guard: input not recognized, blocking to be safe
# == guardia_sbagliata.py
# /project/src/app.py                exit=0 proceeds                         -
# /project/.env                      exit=1 proceeds (non-blocking error)    Write refused: .env may contain secrets.
# /project/.git/config               exit=1 proceeds (non-blocking error)    Write refused: the folder .git is protected.
# C:\project\.git\config             exit=1 proceeds (non-blocking error)    Write refused: the folder .git is protected.
# /project/src/../.env.local         exit=1 proceeds (non-blocking error)    Write refused: the path contains '..'.
# /project/keys/server.pem           exit=1 proceeds (non-blocking error)    Write refused: server.pem may contain secrets.
# (malformed input)                  exit=1 proceeds (non-blocking error)    guard: input not recognized, blocking to be safe

The two guards produce the same message on stderr for the same cases, but the first blocks and the second does not: in the second all the rows say "proceeds (non-blocking error)". The Windows row shows that the normalization works, the one with .. that the climbing check fires before the one on the name, and the last that the malformed input is treated as a case to block. The program is deterministic: I ran it twice with identical output.

Blocking with JSON, and why not to mix

The documentation provides a second way to decide: instead of exiting with 2, the hook exits with 0 and prints a JSON object on stdout, which for PreToolUse has the form {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "..."}}. There are four possible decisions (allow, deny, ask, defer) and, if several hooks answer differently, the winner is, in order, deny, then defer, then ask, then allow. JSON gives more control (you can, for example, rewrite the arguments with updatedInput), but it has iron rules: there must be nothing but the object on stdout, because text printed by the shell profile makes it unreadable, and an invalid object is a non-blocking error. The documentation advises choosing one approach per hook, because if you mix them exit 2 still keeps its blocking effect.

For a guard as simple as this one, exit code 2 is enough and has fewer ways to break. JSON pays off when you need "ask the user" (ask) instead of forbidding, or when an argument must be corrected instead of refused.

Wiring hooks to the configuration, and checking it

The settings file binds the scripts to the events. The group has the Write|Edit filter: a string made only of letters, digits and | is treated as a list of exact names, and for regular expressions the documentation specifies that the match is not anchored (Edit.* would also match NotebookEdit). I used the form with args (direct execution without a shell), which according to the documentation is preferable whenever you cite a path with a placeholder like ${CLAUDE_PROJECT_DIR}, because every element passes as a single argument with no need for quotes.

{
  "$schema": "https://json.schemastore.org/claude-code-settings.json",
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "python3",
            "args": [
              "${CLAUDE_PROJECT_DIR}/.claude/hooks/guardia.py"
            ],
            "timeout": 10
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "python3",
            "args": [
              "${CLAUDE_PROJECT_DIR}/.claude/hooks/registro.py"
            ],
            "timeout": 10
          }
        ]
      }
    ]
  }
}

The timeout is in seconds and has a default value that surprises: 600 for commands. A guard hook left hanging for ten minutes stops the session, so a low value is advisable, as here. The documentation also describes the onFailure field, available from version 2.1.295: with the value "block" the action does not proceed if the hook fails (for example because the script path is wrong and the command does not start). I did not put it in the example because the schema published on schemastore does not know it: removing that single field, the validation below passes, and with the field it does not (measured). The documentation warns that the schema can lag behind on newly documented keys, so that error would have been a false alarm. The real risk is the other one: a guard with the wrong path does not start, produces a warning and lets everything through, and that is why the field exists.

$ python valida_policy.py settings-esempio.json settings-sbagliato.json
# Output:
# settings-esempio.json: valid
# settings-sbagliato.json: hooks/PreToolUse/0/hooks/0: {'type': 'shell', 'command': 'python3', 'args': ['${CLAUDE_PROJECT_DIR}/.claude/hooks/guar
# settings-sbagliato.json: hooks/PreToolUse/0/matcher: 5 is not of type 'string'

The good file passes; the second contains a numeric filter and a non-existent handler type (shell) and is rejected with two reports. As in the article on governance, validation says the file is well formed, not that the hooks do what you think: to find out you open /hooks in a session, which shows each configured hook with its origin (user, project, local settings, plugin), and you look at the claude --debug log, which records events, evaluated filters, exit code and output of each hook.

A log: the hook that decides nothing

Not every hook is for blocking. The second script, in the PostToolUse event (after a successful tool), appends a line to a JSON Lines file with the tool name, the file touched and the session. It does nothing if the REGISTRO_HOOK variable is not set, and it never writes to the repository: the path is chosen by whoever uses it.

"""PostToolUse hook: appends a line to a JSON Lines log. It does nothing if REGISTRO_HOOK is not set."""
import json
import os
import sys

destinazione = os.environ.get("REGISTRO_HOOK")
if destinazione:
    evento = json.load(sys.stdin)
    riga = {
        "event": evento.get("hook_event_name"),
        "tool": evento.get("tool_name"),
        "file": evento.get("tool_input", {}).get("file_path"),
        "session": evento.get("session_id"),
    }
    with open(destinazione, "a", encoding="utf-8") as registro:
        registro.write(json.dumps(riga, ensure_ascii=False) + "\n")

The script opens the file for appending ("a"), one line per event, and exits with 0 without printing anything on stdout: a log-only hook must not interfere. A limit declared by the documentation: PostToolUse does not fire when a Bash command or an external process rewrites the same file, so this log sees the writes made with the Write and Edit tools, not all the modifications. To observe a file whoever the author is, the documentation points to the FileChanged event.

$ echo '<sample PostToolUse event>' | REGISTRO_HOOK=registro.jsonl python registro.py; cat registro.jsonl
# Output:
# {"event": "PostToolUse", "tool": "Write", "file": "/project/src/app.py", "session": "s1"}

The line is the expected one: a sample event, with only the four fields the script extracts. In real use the log grows with every edit and must be rotated or limited; the line does not contain the contents of the files, a deliberate choice, because a log with the contents would become a second place to look for secrets.

Testing a guard with tests, without a session

Since the guard is a script that reads a JSON and returns a code, you test it like any program: seven tests, of which five on the decision function and two on the behavior of the process (code 2 and reason on stderr, malformed input). The least obvious case is the last of the first class: a file called gitflow.md contains the word "git" but must not be blocked, and comparing on the path segments, instead of on the substring, guarantees it.

import json
import subprocess
import sys
import unittest

from guardia import motivo_del_rifiuto


class RefusalReason(unittest.TestCase):
    def test_normal_file_passes(self):
        self.assertIsNone(motivo_del_rifiuto("/project/src/app.py"))

    def test_env_and_variants(self):
        self.assertIn(".env", motivo_del_rifiuto("/project/.env"))
        self.assertIsNotNone(motivo_del_rifiuto("/project/.env.local"))

    def test_git_with_backslashes(self):
        self.assertIn(".git", motivo_del_rifiuto("C:\\project\\.git\\HEAD"))

    def test_parent_directory_traversal(self):
        self.assertIn("..", motivo_del_rifiuto("/project/src/../.env"))

    def test_a_file_containing_the_word_git_passes(self):
        self.assertIsNone(motivo_del_rifiuto("/project/docs/gitflow.md"))


class ProcessExit(unittest.TestCase):
    def run_guard(self, ingresso):
        return subprocess.run([sys.executable, "guardia.py"], input=ingresso, capture_output=True, text=True)

    def test_block_with_code_2_and_reason_on_stderr(self):
        evento = {"tool_name": "Write", "tool_input": {"file_path": "/p/.env"}}
        p = self.run_guard(json.dumps(evento))
        self.assertEqual(p.returncode, 2)
        self.assertIn("refused", p.stderr)

    def test_malformed_input_blocks(self):
        self.assertEqual(self.run_guard("{").returncode, 2)

The run_guard function really starts the script with subprocess, so the test also verifies the real exit code, which is the part the wrong variant falsifies. A test that only imports the function and checks the returned value would not have discovered it.

$ python -m unittest -v test_guardia
# Output:
# test_block_with_code_2_and_reason_on_stderr (test_guardia.ProcessExit.test_block_with_code_2_and_reason_on_stderr) ... ok
# test_malformed_input_blocks (test_guardia.ProcessExit.test_malformed_input_blocks) ... ok
# test_a_file_containing_the_word_git_passes (test_guardia.RefusalReason.test_a_file_containing_the_word_git_passes) ... ok
# test_env_and_variants (test_guardia.RefusalReason.test_env_and_variants) ... ok
# test_git_with_backslashes (test_guardia.RefusalReason.test_git_with_backslashes) ... ok
# test_normal_file_passes (test_guardia.RefusalReason.test_normal_file_passes) ... ok
# test_parent_directory_traversal (test_guardia.RefusalReason.test_parent_directory_traversal) ... ok
#
# ----------------------------------------------------------------------
# Ran 7 tests in Xs
#
# OK

The seven tests pass; the duration is replaced by an X because it changes with every run. I ran the suite twice with the same outcome. It does not replace a test in a real Claude Code session, which I could not run without a model: what these tests show is that the script respects the documented contract (JSON in, code and stderr out), not that Claude Code calls it as expected.

What a hook does not guarantee

The documentation's page on risks opens with a clear warning: hook commands run with all the permissions of your user and can modify, delete or read any file the user can reach. Its guidance is that of any program that takes data from outside: validate the input, always quote shell variables, block path climbing, use absolute paths, skip sensitive files. For hooks there is one more reason: the tool_input fields are written by the model, which may have been steered by text read in a file or on a page (the instruction injection discussed in the article on governance). A hook that builds a shell command by concatenating a received argument, or passes it to eval, gives whoever controls that text the execution of code with your permissions.

Other limits are declared in the documentation and are worth knowing before trusting a guard. PreToolUse fires only when the model calls a tool: files cited with @ in the prompt are inserted without any call, so no hook, not even one on Read, sees them; to forbid them you need a deny rule on reading. A handler's if filter, which accepts the permission-rule syntax, is a "best effort" check: when Claude Code cannot work out which commands a shell text runs, it launches the hook anyway, and the documentation recommends using the permission system, not a hook, for an absolute prohibition or authorization. A guard is a second line of defense, not the only one.

Finally, whoever controls the repository controls the hooks. In an interactive session Claude Code holds back the hooks of every settings file until you accept trust in the folder, but in non-interactive sessions with -p the dialog does not appear and the folder is treated as trusted: before running claude -p on a repository written by others, the documentation suggests reviewing its files in .claude/, using --bare or turning hooks off with "disableAllHooks": true. Administrators have the allowManagedHooksOnly key, seen in the article on governance, which blocks user, project and plugin hooks (with the exception of plugins force-enabled by managed settings): managed hooks cannot be turned off from the outside.

Frequently asked questions

Can a hook stop Claude from reading a file?

A hook on Read can block reads made with the tool, but not those of files cited with @. For absolute prohibitions the documentation points to the permission system's deny rules, which cover that case too.

What is the difference between a hook and a skill?

A skill is text and scripts the model can choose to use; a hook starts by itself at an event, without the model deciding. The skill steers, the hook guarantees only what is written in its code, and for that reason it must be written and tested like any program.

Can a hook call an MCP server?

Yes: there is the mcp_tool handler type, which calls a tool of a configured MCP server and treats its text like a command's output. I did not try it, because it requires a Claude Code session.

What you can do now, and the path of the series

You can write a command hook that reads the event from stdin, you know that only exit 2 blocks (and 1 does not), you can test the guard with tests that really start the script, and you know the limits the documentation declares: hooks run with your permissions, do not see files cited with @, do not replace permission rules. The path, in eight stages, is this.

  1. Claude Skills: introduction and architecture: what a skill is, how it is loaded and what the vendor documents.
  2. Building a Claude Skill from scratch: a SKILL.md with scripts and tests, validated.
  3. MCP: protocol, server and test clients: revision 2026-07-28, with no handshake or sessions.
  4. MCP TypeScript client: typed outcomes, timeouts and tests with an in-memory transport.
  5. Skills, plugins and MCP servers in an organization: managed settings, plugin review, a schema to validate.
  6. Distributing skills with plugins: catalog, versions and updates.
  7. Debugging and tracing MCP calls: traceparent in _meta, the stdout rule, host timeouts.
  8. Claude Code Hooks: this article, events and guards.

The thread that ties the stages together is a single idea: every capability you give an assistant (a skill, a server, a hook) is also a surface, and each time I tried to show together how to build it, how to test it without a model and what the documentation says can go wrong. The part that remains yours is deciding where a guard is enough and where a permission is needed, and doing it for each project rather than once and for all.

Sources

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects