Module 6: Advanced Hooks and Headless SDK
1. Module Introduction — Hooks as the Nervous System, the SDK as Programmatic Control
1. Module Introduction — Hooks as the Nervous System, the SDK as Programmatic Control
Description
So far, everything you've built with Claude Code is interactive. You write a prompt, Claude executes, you review. You created subagents with an identity of their own, gave them persistent memory, coordinated them in parallel, organized them into teams with task boards, and packaged them as distributable plugins. All functional. But there's a pattern you probably noticed: you're always there. There's always a human initiating the action, supervising the execution, deciding the next step.
Hooks and the headless SDK eliminate that dependency. Hooks are Claude Code's nervous system — they detect internal events (a tool runs, a subagent finishes, a session starts) and trigger automatic actions without your intervention. The headless SDK is the programmatic control — it runs Claude Code from Python or TypeScript scripts as if it were just another function in your pipeline.
The combination is what transforms Claude Code from an interactive tool into an automatable system: a hook detects that a subagent finished editing files → it triggers an automatic linting script → if the linting fails, an SDK script re-runs Claude Code to fix the errors → all without you touching the keyboard.
This module closes Phase 2 because it completes the stack: Agent Teams coordinate the execution, plugins package it, and hooks + SDK automate it. When you finish, you'll have an end-to-end workflow where hooks detect events, SDK scripts react, and the system self-corrects.
Where Are We in the Guide?
Context in the Guide
This guide has 8 modules organized into 3 phases:
Phase 1: Advanced Subagents (Modules 1-3) ← COMPLETED
├── Module 1: Custom Subagents ✅
├── Module 2: Agent Memory and Scopes ✅
└── Module 3: Parallel Sub-Agent Delegation ✅
Phase 2: Agent Teams and Plugins (Modules 4-6)
├── Module 4: Agent Teams ✅
├── Module 5: Plugins: Creating and Distributing ✅
└── Module 6: Advanced Hooks and Headless SDK ← YOU ARE HERE
Phase 3: Orchestration (Modules 7-8)
├── Module 7: Remote Control and CLAUDE.md for Teams
└── Module 8: Project: Complete Multi-Agent System
Total estimated duration: 8-10 hours (self-paced).
What changes with hooks and the SDK?
In the previous modules, the automation was at the agent level: the team lead decides what to do, but you start it. Hooks and the SDK move the automation to the system level: events trigger actions, scripts start sessions, and the complete cycle can run without human intervention. The mental shift is: you stop being the operator and start being the designer of the automation system.
From Interactive Tool to Automated System
What you have now
After 5 modules, your stack is:
┌─────────────────────────────────────────────┐
│ Your Current Workflow │
│ │
│ YOU ─prompt─→ Claude Code ─result─→ YOU │
│ │ │ │
│ │ ┌──────────────────────┐ │ │
│ └──│ Subagents (M1) │ │ │
│ │ Memory (M2) │ │ │
│ │ Parallelism (M3) │────┘ │
│ │ Agent Teams (M4) │ │
│ │ Plugins (M5) │ │
│ └──────────────────────┘ │
└─────────────────────────────────────────────┘
Problem: YOU are still the point of both initiation AND control.
What you'll have after this module
┌─────────────────────────────────────────────────────┐
│ Your Automated Workflow │
│ │
│ ┌──────────┐ ┌──────────────┐ ┌────────────┐ │
│ │ HOOKS │───→│ Claude Code │───→│ HOOKS │ │
│ │ (start) │ │ (executes) │ │ (reaction) │ │
│ └──────────┘ └──────┬───────┘ └──────┬─────┘ │
│ ▲ │ │ │
│ │ ┌──────┴───────┐ │ │
│ │ │ SDK Script │◀──────────┘ │
│ └──────────│ (Python/TS) │ │
│ └──────────────┘ │
│ │
│ YOU: design the system, don't operate it │
└─────────────────────────────────────────────────────┘
The difference: hooks detect events and the SDK lets scripts react programmatically. You design the rules once and the system executes them every time.
Hooks: The Nervous System
What hooks are
A hook is an automatic action that triggers when a specific event occurs inside Claude Code. It's not a plugin, it's not a subagent — it's a trigger: "when X happens, run Y."
Event Hook Action
─────────────────────────────────────────────────────────────────
Session starts → SessionStart → Install deps
Tool about to run → PreToolUse → Validate command
Tool finished → PostToolUse → Auto-lint
Subagent starts → SubagentStart → Log the start
Subagent finished → SubagentStop → Generate report
Claude about to respond → Stop → Quality check
Permission requested → PermissionRequest → Auto-approve
The 7 hook events
| Event | When it triggers | Matcher | Typical use case |
|---|---|---|---|
SessionStart | When a session starts | Not applicable | Environment setup, verify deps |
PreToolUse | Before running a tool | Tool name | Validate, block, modify |
PostToolUse | After running a tool | Tool name | Lint, test, logging |
SubagentStart | When a subagent starts | Agent type | Logging, resource allocation |
SubagentStop | When a subagent finishes | Agent type | Reports, cleanup |
Stop | When Claude finishes responding | Not applicable | Final validation, cleanup |
PermissionRequest | When a permission is needed | Not applicable | Conditional auto-approval |
Hook types
A hook can run three types of actions:
1. Command (shell script):
{
"type": "command",
"command": "./scripts/validate.sh"
}
2. HTTP endpoint:
{
"type": "http",
"url": "https://my-api.com/webhook",
"method": "POST"
}
3. MCP tool:
{
"type": "mcp",
"server": "my-server",
"tool": "my-tool"
}
The command type is the most common and the one you'll use in 90% of cases in this module.
Exit codes: the language of hooks
When a command hook runs a script, the exit code determines what happens:
| Exit Code | Meaning | Claude Code does... |
|---|---|---|
0 | Success, continue | Allows the operation |
1 | Error, report | Reports the error to Claude to decide |
2 | Block | Cancels the operation entirely |
Exit code 2 is particularly powerful in PreToolUse — it turns the hook into a gatekeeper that can block dangerous tools before they run.
Headless SDK: Programmatic Control
What headless mode is
Claude Code is normally interactive — you open it in the terminal, type, wait. In headless mode, Claude Code is an invocable service: you call it from a script, pass it a prompt, and receive the result as structured data.
# Interactive (what you always do)
claude
# Headless (what you'll learn here)
claude -p "Generate the changelog for the last sprint" \
--allowedTools "Read,Grep,Glob" \
--output-format json
The three output formats
| Format | Flag | When to use it |
|---|---|---|
text | --output-format text | Simple scripts, logging |
json | --output-format json | Programmatic parsing, CI/CD |
stream-json | --output-format stream-json | Real-time monitoring |
SDK in Python and TypeScript
Besides the CLI, Claude Code can be invoked from native SDKs:
Python — Ideal for data pipelines, CI scripts, automation:
import subprocess
import json
result = subprocess.run(
["claude", "-p", "Analyze src/ and report issues",
"--output-format", "json",
"--allowedTools", "Read,Grep,Glob"],
capture_output=True, text=True
)
output = json.loads(result.stdout)
TypeScript — Ideal for development tooling, build scripts, integration with JS frameworks:
import { execSync } from "child_process";
const result = execSync(
'claude -p "Analyze src/ and report issues" --output-format json --allowedTools "Read,Grep,Glob"',
{ encoding: "utf-8" }
);
const output = JSON.parse(result);
The Combination: Hooks + SDK
The real superpower
Hooks and the SDK are useful separately. Together they're transformative.
Scenario: Every time you edit a file, it auto-formats and tests
PostToolUse hook (matcher: "Edit|Write")
→ Runs ./scripts/lint-and-test.sh
→ If the lint fails (exit 1):
→ SDK script runs: claude -p "Fix lint errors in {file}"
→ Claude Code fixes automatically
→ The PostToolUse hook triggers again
→ The cycle repeats until the lint passes
Scenario: Automatic report at the end of each session
Stop hook
→ Runs ./scripts/generate-report.sh
→ The script uses the SDK to:
→ claude -p "Summarize what you did in this session"
→ Save the output to reports/session-{date}.md
→ Send a notification to Slack
The complete pipeline
SessionStart ──→ Setup environment (install deps, check versions)
│
PreToolUse ───→ Validate (block dangerous commands, restrict paths)
│
[Claude works]
│
PostToolUse ──→ React (auto-lint, auto-test after edits)
│
SubagentStop ─→ Report (log what each subagent did)
│
Stop ─────────→ Cleanup (generate session report, push to git)
│
SDK Script ───→ Orchestrate (trigger next session, parse results)
Each capsule of this module teaches you a piece of this pipeline. At the end, in the project (capsule 06), you build it complete.
Module Objective
By the end of this module you'll be able to:
- ✅ Configure SessionStart and PreToolUse hooks for automatic setup and command validation
- ✅ Use PostToolUse for auto-linting and auto-testing after each edit
- ✅ Implement SubagentStart/SubagentStop for tracking the subagent lifecycle
- ✅ Use Stop and PermissionRequest for cleanup and automatic approval
- ✅ Run Claude Code from Python with
subprocessand JSON parsing - ✅ Run Claude Code from TypeScript/Node.js with
child_processor the SDK package - ✅ Combine hooks + SDK in an end-to-end automated workflow
Professional objective
Hooks + SDK are the layer that turns Claude Code into automated development infrastructure. Teams that master this combination build CI pipelines that auto-fix code, changelog scripts that generate themselves, and quality systems that validate every change without intervention. It's the difference between "I use Claude Code" and "Claude Code works for me."
Module Roadmap
Capsule map
| # | Capsule | What you'll learn | Type |
|---|---|---|---|
| 01 | Introduction (this one) | Context, hooks + SDK mental model, why the combination matters | Intro |
| 02 | SessionStart and Advanced PreToolUse | Automatic environment setup, conditional validation, command blocking | Technical |
| 03 | PostToolUse, Subagent Events, and Stop | Post-execution reactions, subagent lifecycle, final cleanup | Technical |
| 04 | Headless SDK — Python | Running Claude Code from Python, JSON parsing, automation scripts | Technical |
| 05 | Headless SDK — TypeScript | Running Claude Code from Node.js, integration with JS tooling | Technical |
| 06 | Project: Automated Workflow | Complete pipeline: hooks + SDK integrated end-to-end | Project |
Learning flow
First you'll understand the startup and validation hooks — SessionStart to configure the environment automatically and PreToolUse to block dangerous operations (capsule 02). Then you'll see the reaction hooks — PostToolUse to act after each edit, SubagentStart/SubagentStop for the subagent lifecycle, and Stop for final cleanup (capsule 03). Next you'll learn to run Claude Code from Python — automation scripts, result parsing, CI/CD integration (capsule 04). You'll continue with TypeScript — the same programmatic power but integrated with JavaScript tooling (capsule 05). Finally, you'll build a complete automated workflow that combines hooks + SDK into a functional pipeline (capsule 06).
The progression is: configure the environment → validate → react → automate from Python → automate from TypeScript → integrate everything.
Each capsule is independent in concept but builds on the previous one in the final project. Capsules 02 and 03 cover hooks. Capsules 04 and 05 cover the SDK. Capsule 06 integrates everything.
Estimated module duration: 1.25-1.5 hours.
Connection to the Project
Module project: End-to-End Automated Workflow
In capsule 06 you'll build a complete pipeline:
-
SessionStart hook — Configures the environment: verifies dependencies, runs pending migrations, checks the git state.
-
PreToolUse hook — Validates commands: blocks
rm -rf, restricts file paths, prevents operations on production. -
PostToolUse hook — Auto-lint: every time Claude edits a file, the linter runs automatically. If it fails, Claude receives the error.
-
SubagentStop hook — Generates a report: when a subagent finishes, it logs what it did, how long it took, and which files it touched.
-
Python SDK script — Orchestrates the pipeline: a Python script starts Claude Code, passes it the task, and processes the results.
Your Python script
↓
claude -p "Implement feature X" (SDK)
↓
SessionStart hook → automatic setup
↓
Claude works → PreToolUse validates each command
↓
Claude edits files → PostToolUse auto-lint
↓
Subagent finishes → SubagentStop generates a log
↓
Claude finishes → Stop generates a report
↓
Your Python script ← receives the JSON result
↓
Processes, notifies, triggers the next task
Connection to the final project (Module 8)
In the capstone project, this pipeline becomes the automation layer of the complete multi-agent system. The hooks validate every action of every agent, and the SDK lets you orchestrate multiple sessions from a central script. Without hooks + SDK, the multi-agent system needs constant human supervision.
Prerequisites
Required knowledge
- ✅ Modules 1-5 completed — Custom subagents, memory, parallel delegation, Agent Teams, plugins
- ✅ Basic hooks — You've used PreToolUse at least once in previous guides
- ✅ Claude Code settings.json — You know it exists and where to configure preferences
- ✅ Basic Python — You can write scripts with subprocess, json, and file handling
- ✅ Terminal — You know how to write and run shell scripts (.sh)
Quick check
If you can answer "yes" to these questions, you're ready:
- Do you know what a PreToolUse hook is and when it triggers?
- Can you run
claude -p "something"in the terminal? - Do you know what an exit code is and the difference between
exit 0andexit 1? - Can you write a Python script that runs a command and captures its output?
- Do you understand JSON well enough to parse an object with
json.loads()?
You don't need
- ❌ Experience with all the hooks — you just need to know they exist
- ❌ Experience with the headless SDK — covered completely here
- ❌ Advanced TypeScript — the examples are basic and commented
- ❌ CI/CD infrastructure — it's mentioned but covered in depth in the CI/CD Pipelines guide
Limits: What Is NOT Covered in This Module
- ❌ Complete CI/CD — Covered in the CI/CD Pipelines guide. Here it's mentioned as a preview
- ❌ Remote control — Covered in Module 7. Here everything is local
- ❌ HTTP and MCP hooks — Mentioned, but the focus is on
command-type hooks - ❌ Advanced SDK with persistent sessions — Only one-shot invocation is covered
- ❌ Advanced hook debugging — Common errors are covered, not edge cases
Evidence of Success
By the end of this module, you'll know you succeeded if:
- ✅ You have a SessionStart hook that configures your environment automatically when you open Claude Code
- ✅ A PreToolUse hook blocks dangerous commands with exit code 2
- ✅ A PostToolUse hook auto-lints after each file edit
- ✅ A SubagentStop hook generates a log when a subagent finishes
- ✅ A Python script runs Claude Code, parses the JSON result, and makes decisions based on the output
- ✅ A TypeScript script does the same from the Node.js ecosystem
- ✅ You can explain how hooks + SDK combine to create an automated pipeline
Quick self-assessment test
If you can answer these questions by the end:
- What's the difference between exit code 1 and exit code 2 in a hook?
- How do you configure a hook that only triggers for the
Bashtool? - Which flag do you use to run Claude Code in headless mode?
- How do you parse Claude Code's result in Python?
- Why is
--allowedToolsimportant in headless mode?
Summary
- This module teaches the two automation layers of Claude Code: hooks (control from the inside) and the headless SDK (control from the outside)
- Hooks are the nervous system — they detect 7 types of events (SessionStart, PreToolUse, PostToolUse, SubagentStart, SubagentStop, Stop, PermissionRequest) and run automatic actions
- The headless SDK lets you run Claude Code from Python or TypeScript scripts with
claude -pand parse results as JSON - The hooks + SDK combination is what turns Claude Code from an interactive tool into an automated system: hooks detect → SDK reacts → the cycle repeats
- Hooks use exit codes (0 = continue, 1 = error, 2 = block) to communicate decisions
- The module closes Phase 2 by connecting plugins (packaging) with the automation that Phase 3 (Remote Control, capstone project) needs
- The project builds an end-to-end automated pipeline: SessionStart → PreToolUse → PostToolUse → SubagentStop → orchestrating SDK script
Additional Resources
- Claude Code Hooks (Anthropic Docs) — Official documentation of hooks, events, exit codes, and configuration
- Claude Code CLI Reference — The
-p,--output-format,--allowedToolsflags for headless mode - Claude Code Settings — Hook configuration in settings.json
- Create Custom Subagents — Hooks in subagent frontmatter
- Claude Code Best Practices — Best practices that include hooks and automation
- Claude Code Overview — General context of Claude Code as a system
- Claude Code Tips and Tricks — Automation and hook tips
- Multi-Agent Orchestration — Orchestration patterns where hooks and the SDK fit in
Next capsule: In capsule 02 you'll configure your first advanced hooks — SessionStart so Claude Code configures your environment automatically at startup, and advanced PreToolUse to validate commands, block dangerous operations, and restrict file paths. You'll see the configuration in settings.json, the JSON input format via stdin, and you'll master the exit codes that control the flow.