Sub topic 4
The hook contract: event in, exit code and message out
This chapter assumes you can read and write JSON, run Python scripts from a shell, and understand that an AI coding agent calls tools such as a shell command or a file edit. Earlier chapters covered where hooks run in the agent lifecycle. This one covers the interface between the agent and the hook script.
What a contract is
A hook is an ordinary program. The agent does not import it or call a function in it. The agent starts it as a separate process, gives it input, waits for it to finish, and reads the result. The rules for that exchange are the hook contract.
The contract has three parts:
- Input. The agent writes one JSON document, the event, to the hook's standard input (stdin).
- Decision. The hook finishes with an exit code. The code tells the agent whether to continue.
- Message. The hook writes text to standard error (stderr) or standard output (stdout). The agent reads this text when it handles the result.
Hook systems such as Claude Code and Kiro CLI follow this general shape. Field names and some details differ between tools and versions, so check your agent's documentation before you rely on a specific name.
The event on stdin
The event describes the tool call the agent wants to make. A typical pre-action event for a shell command looks like this:
{
"hook_event_name": "preToolUse",
"cwd": "/home/dev/project",
"tool_name": "shell",
"tool_input": {
"command": "rm -rf build/"
}
}Here is what each field is for:
hook_event_namenames the lifecycle point that fired the hook. A script registered for several events uses it to tell them apart.cwdis the working directory the agent is using. You need it to resolve relative paths.tool_nameidentifies the tool, such as a shell tool or a file-writing tool.tool_inputholds the arguments for that tool. Its shape depends on the tool. A shell tool has acommand. A file tool has a path and content.
The tool name and the shape of tool_input are the parts that vary most between agents. Treat them as configuration to verify, not as constants to memorize. Also treat the whole event as untrusted data. The command text can come from a model that read a hostile web page or a file. Your hook should parse it and test it, and it should never execute it or paste it into another shell command.
Read the event once and in full. json.load(sys.stdin) consumes the stream. A second read returns nothing.
The decision: exit codes
The exit code is the only thing the agent uses to decide whether to proceed. The common convention for a pre-action hook is:
| Exit code | Meaning | What the agent does |
|---|---|---|
| 0 | Success, no objection | Runs the tool call |
| 2 | Block | Does not run the tool call and passes the stderr text back to the model |
| Any other non-zero | Hook error | Usually shows a warning and **runs the tool call anyway** |
The last row catches many authors. An unhandled Python exception exits with code 1. Under this convention, a crashed hook does not block anything. The action goes through, and your protection is gone without any visible failure. Never assume that "non-zero" means "stop". Only the specific blocking code does that, and your agent's documentation names it. Exit code 2 is what Claude Code and Kiro CLI use.
A later chapter covers failing closed. For now, remember that the contract gives a crash the weakest possible outcome. The script has to catch its own errors and turn them into exit code 2.
The message: stdout and stderr
A hook can write to two streams, and they do different jobs:
- stderr with exit code 2. The agent treats this text as the reason for the block and gives it to the model. This is how you tell the agent what went wrong and what to do instead.
- stdout with exit code 0. Some agents add this text to the conversation context or show it to the user. Others ignore it. Check how your agent handles it before you depend on it.
Keep the two apart in your code. A debugging print() to stdout is harmless when the hook blocks, but it can leak into the conversation when the hook allows. Send diagnostics to stderr only when you also mean to block, or write them to a log file.
A minimal hook that follows the contract
This script implements all three parts. It reads the event, applies one rule, and ends with a deliberate exit code and message.
#!/usr/bin/env python3
import json
import sys
FORBIDDEN_WORD = "mkfs"
def main():
event = json.load(sys.stdin)
command = event.get("tool_input", {}).get("command", "")
if FORBIDDEN_WORD in command:
print(
f"Blocked: the command contains '{FORBIDDEN_WORD}', "
"which can erase a disk. Describe what you need and ask the user.",
file=sys.stderr,
)
return 2
return 0
if __name__ == "__main__":
sys.exit(main())Returning the code from main() and passing it to sys.exit() once keeps the exit path in one place. That makes the script easier to reason about than one with sys.exit() calls scattered through the logic.
This script has a flaw that you should find before the next chapter. If stdin holds malformed JSON, json.load raises an exception, the interpreter exits with code 1, and the contract lets the command run. Here is the same input stage made safe:
import json
import sys
try:
event = json.load(sys.stdin)
command = event["tool_input"]["command"]
except (json.JSONDecodeError, KeyError, TypeError):
print("Blocked: hook could not read the tool call, so it was not allowed.", file=sys.stderr)
sys.exit(2)This version blocks when the event is unreadable or the expected fields are missing. One side effect is that the hook blocks every tool call that has no command, such as a file edit, if you attach it to all tools. Matchers solve that problem, and they are the next chapter's topic.
Common mistakes
- Using exit code 1 to block. The agent reads it as a hook failure and lets the action run. Use the documented blocking code.
- Writing the reason to stdout. On a block, the agent reads stderr. A reason on stdout may never reach the model.
- Vague messages. "Denied" gives the model nothing to act on. Say what was matched and what a safe alternative would be.
- Reading stdin twice, or not at all. Hooks that ignore stdin cannot see the command. Hooks that read it twice get an empty string on the second read.
- Slow or hanging hooks. The agent waits for the process. Agents usually enforce a timeout, and a timed-out hook is treated as an error, not a block. Keep hooks fast.
- Trusting field names across agents. A script written for one agent may look for a key that another agent names differently. A missing key then reads as an empty command, and every call passes the check.
Verifying the contract by hand
You can exercise the contract without any agent, because it is only stdin, an exit code, and a stream. Pipe a sample event into your script and print $?:
echo '{"tool_name":"shell","tool_input":{"command":"mkfs /dev/sda"}}' | python3 guard.py
echo "exit code: $?"
echo '{"tool_name":"shell","tool_input":{"command":"ls -la"}}' | python3 guard.py
echo "exit code: $?"The first call should print the block message and report exit code: 2. The second should print nothing and report exit code: 0. Add a third check with echo 'not json' | python3 guard.py. With the fail-closed input stage, it should report 2.
Summary
The contract is small. The agent sends JSON on stdin, and the hook answers with an exit code and a message on a stream. Exit 0 allows the call. Exit 2 blocks it and returns the stderr text to the model. Every other outcome, including a crash, is an error that normally lets the call proceed. Most of the work in a reliable hook is making sure it always ends in one of the two codes it chose on purpose.
Exercise
Your pre-action hook raises an uncaught KeyError because the event had no "command" field, and the agent then runs the shell command anyway. Why did that happen, and what change makes the hook block instead?
Show answer
An uncaught Python exception ends the process with exit code 1. Under the usual contract only the blocking code (2) stops the action, and any other non-zero code counts as a hook error that lets the tool call proceed. Wrap the parsing in try/except for JSONDecodeError, KeyError, and TypeError, print a reason to stderr, and call sys.exit(2). The hook then fails closed.
Exercise
A hook prints "Denied by policy" to stdout and exits with code 2. The model keeps retrying the same command. What two changes make the block effective and useful?
Show answer
Write the message to stderr, because the agent passes stderr to the model when a hook exits with code 2. Also make the message specific. Name the rule that matched and suggest a safe alternative, for example "Blocked: git push --force rewrites remote history. Use git push --force-with-lease or ask the user." That gives the model something it can act on.