We earn commissions when you shop through the links below.
This Claude Code hooks and subagents tutorial is for developers who want to go beyond basic prompting and actually wire Claude Code into their existing workflows with precision. Hooks let you intercept the agent lifecycle — before a tool runs, after it completes, when a session starts or ends — while subagents let you spin up parallel or sequential AI workers that each own a focused slice of a bigger task. Together, they’re the two most powerful levers for building serious automation with Claude Code.
What are Claude Code hooks?
Hooks are event-driven callbacks that fire at specific points in the Claude Code execution lifecycle. They’re defined in your claude.json configuration file and let you inject custom logic without modifying the core agent behavior.
The main hook events you’ll work with are:
- PreToolUse — fires before Claude executes a tool call (bash, file write, etc.)
- PostToolUse — fires after a tool completes, with access to the result
- Notification — fires when Claude wants to surface information to the user
- Stop — fires when the agent is about to end a session
Hooks receive a JSON payload over stdin and can write JSON back to stdout to influence behavior — blocking a tool call, modifying output, or logging telemetry.
Configuring your first hook
Hooks live in your project-level or user-level claude.json. Here’s a minimal example that logs every tool call to a local file:
{
"hooks": {
"PreToolUse": [
{
"matcher": ".*",
"hooks": [
{
"type": "command",
"command": "python3 /home/user/scripts/log_tool_use.py"
}
]
}
]
}
}And here’s the Python script that receives the hook payload and logs it:
#!/usr/bin/env python3
import sys
import json
import datetime
def main():
payload = json.load(sys.stdin)
tool_name = payload.get("tool_name", "unknown")
tool_input = payload.get("tool_input", {})
log_entry = {
"timestamp": datetime.datetime.utcnow().isoformat(),
"tool": tool_name,
"input": tool_input
}
with open("/tmp/claude_tool_log.jsonl", "a") as f:
f.write(json.dumps(log_entry) + "\n")
# Return empty decision = allow the tool to proceed
print(json.dumps({"decision": "approve"}))
if __name__ == "__main__":
main()The decision field in your stdout controls what happens next. Use approve to let the tool run, block to prevent it with an error message, or omit it to pass through silently.
Blocking dangerous tool calls
One practical use case is preventing Claude from running destructive commands in production environments. Here’s a hook that blocks any bash command containing rm -rf:
#!/usr/bin/env python3
import sys
import json
def main():
payload = json.load(sys.stdin)
tool_name = payload.get("tool_name", "")
tool_input = payload.get("tool_input", {})
if tool_name == "Bash":
command = tool_input.get("command", "")
if "rm -rf" in command:
print(json.dumps({
"decision": "block",
"reason": "Destructive rm -rf commands are not allowed in this environment."
}))
return
print(json.dumps({"decision": "approve"}))
if __name__ == "__main__":
main()You can get as sophisticated as you want here — checking against an allowlist of paths, validating that file writes stay within the project directory, or posting a Slack notification when Claude touches certain sensitive files.
What are Claude Code subagents?
Subagents are separate Claude Code instances that a parent agent spawns to handle discrete subtasks. They’re the mechanism behind multi-agent workflows — where one orchestrator breaks a large task into chunks and delegates each chunk to a focused worker.
The parent agent calls the Task tool to launch a subagent, passing it a prompt and optionally a working directory and tool permissions. Subagents can themselves spawn further subagents, giving you a tree structure for complex pipelines.
When to use subagents instead of a single long-running agent:
- Tasks with independent parallel workstreams (e.g., running tests while also writing docs)
- When you want isolated context windows so one task’s output doesn’t pollute another’s reasoning
- Large codebases where specialization (a “refactoring agent” vs. a “test-writing agent”) improves quality
- Workflows where failure in one branch shouldn’t block others
Orchestrating subagents in practice
Let’s build a real example: a parent agent that analyzes a repository and delegates three tasks to subagents in parallel — writing a README, generating a test suite, and creating a deployment config.
You’d prompt the orchestrator like this:
You are an orchestration agent. Given the codebase in the current directory:
1. Launch a subagent to write a comprehensive README.md
2. Launch a subagent to generate a Jest test suite for all exported functions
3. Launch a subagent to create a docker-compose.yml for local development
Run all three subagents in parallel using the Task tool.
Wait for all three to complete, then summarize what was created.Internally, Claude Code will issue three concurrent Task tool calls. Each subagent gets its own context and works independently. The parent waits for all three to resolve before continuing.
You can constrain what tools a subagent has access to by setting permissions in the task prompt — for example, telling the test-writing subagent it may only read files and write to the /tests directory.
Combining hooks and subagents
This is where the Claude Code hooks and subagents tutorial gets really interesting. You can use PostToolUse hooks on the parent to react when a subagent completes — logging results, triggering external webhooks, or feeding output into the next stage of a pipeline.
{
"hooks": {
"PostToolUse": [
{
"matcher": "Task",
"hooks": [
{
"type": "command",
"command": "python3 /home/user/scripts/notify_on_task_complete.py"
}
]
}
]
}
}
#!/usr/bin/env python3
import sys
import json
import urllib.request
def main():
payload = json.load(sys.stdin)
result = payload.get("tool_result", {})
output = result.get("output", "")
# Post a summary to a webhook (e.g., Slack, Make.com scenario)
data = json.dumps({"text": f"Subagent completed: {output[:200]}"}).encode()
req = urllib.request.Request(
"https://hooks.slack.com/services/YOUR/WEBHOOK/URL",
data=data,
headers={"Content-Type": "application/json"}
)
urllib.request.urlopen(req)
print(json.dumps({}))
if __name__ == "__main__":
main()If you’re building more complex automation pipelines around Claude Code — routing results to other services, triggering follow-up workflows — Make is a solid platform for connecting Claude Code’s webhook outputs to hundreds of other services without writing glue code.
Permissions and security model
Subagents inherit the permission set of their parent by default, but you can narrow permissions per task. This matters a lot in production automation contexts. A subagent that only needs to read files shouldn’t have write access — principle of least privilege applies just as much to AI agents as to human users.
Claude Code’s permission model lets you specify allowed tools per session. Combine this with your PreToolUse hooks for defense in depth: the permission model is the first gate, and your hooks are the second.
Deploying Claude Code automation
Running hooks and long-lived subagent workflows means you need a persistent environment — not just your local laptop. I deploy my Claude Code automation scripts on DigitalOcean droplets, which gives me a stable Ubuntu environment with consistent file paths, cron scheduling, and no worry about my laptop sleeping mid-task.
For projects where I want zero-config deploys with auto-scaling, Railway is my go-to for running the supporting API services that Claude Code hooks call into.
Debugging tips
Hooks are powerful but can be opaque when something goes wrong. A few practices that have saved me hours:
- Always log the full incoming payload to a file during development. You can’t debug what you can’t see.
- Return explicit
approvedecisions rather than empty JSON — it’s clearer and less likely to cause unexpected behavior in future Claude Code versions. - Test hook scripts independently by piping fake payloads:
echo '{"tool_name": "Bash", "tool_input": {"command": "ls"}}' | python3 your_hook.py - Use the
--debugflag when running Claude Code sessions during development to see hook invocations in the terminal output.
Wrapping up
This Claude Code hooks and subagents tutorial covered the full picture: how hooks intercept the agent lifecycle to give you control over tool execution, how subagents enable parallel and hierarchical AI workflows, and how to wire both together into production-grade automation. The combination is genuinely powerful — you’re not just prompting an AI, you’re building an event-driven system where AI is one component among many.
Start small: add a logging hook to your next Claude Code project to understand what’s actually happening under the hood. Once you see the data flowing through, the more ambitious orchestration patterns will make immediate sense.