Skip to content

hooks

Hooks are user-defined commands that an AI coding agent runs automatically at fixed points in its workflow, such as before a tool call or when a session ends. Because a hook is code, its rule fires on every matching event rather than depending on whether the LLM follows an instruction in its prompt.

The harness runs each hook when the agent loop reaches the matching lifecycle event. Typical events include session start, prompt submission, the moments before and after a tool call, and the point where the agent stops. A matcher can narrow a hook to specific tools, such as shell commands or file edits.

Most hooks are shell scripts that receive a JSON description of the event on standard input. A hook that runs before an action can block it, usually by exiting with code 2 or by printing a JSON decision to standard output. Other hooks only observe the event or add context. Common uses include running a formatter after each edit, rejecting destructive commands, logging activity, and sending notifications.

Step through one agent session below to see which lifecycle events trigger a configured hook, what JSON each hook receives, and how an exit code of 2 stops a tool call before it runs:

Interactive diagram — enable JavaScript to view.

Claude Code, Cursor, and Gemini CLI all read hooks from JSON configuration files. Hooks run with the user’s own permissions, so a hook file checked into a repository deserves the same scrutiny as any other script.

A woman leans against a factory conveyor belt carrying code files and folders, while three overhead hooks lower onto the line beside a machine panel showing the Python logo.

Tutorial

How to Automate Your Workflow With Claude Code Hooks

Learn how to use Claude Code hooks that auto-format your Python code after every edit, enforce your chosen tools, and ping you when a task finishes.

intermediate projects tools

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Martin Breuss • Updated Nov. 24, 2026