خلاصہ: Claude Code hooks خودکار اسکرپٹ ہیں جو AI کوڈنگ سیشن کے دوران مخصوص لائف سائیکل پوائنٹس پر چلتی ہیں، ڈویلپرز کو حسب ضرورت کمانڈز چلانے، اعمال کی توثیق کرنے، کوڈ کو فارمیٹ کرنے، اطلاعات بھیجنے اور پروجیکٹ کے قواعد کو لاگو کرنے کی اجازت دیتی ہیں۔ یہ hooks Claude کے ورک فلو میں SessionStart، PreToolUse، اور PostToolUse جیسے ایونٹس کے ذریعے ضم ہوتے ہیں، جو configurable timeouts اور exit code کے ساتھ command-based، HTTP-based، اور prompt-based ایگزیکیوشن پیٹرنز کو سپورٹ کرتے ہیں۔
Claude Code کا hook سسٹم AI کوڈنگ اسسٹنٹ کو ایک مددگار ٹول سے مکمل خودکار ڈویلپمنٹ ماحول میں تبدیل کرتا ہے۔ زیادہ تر ڈویلپرز hooks کے ذریعے دستیاب کنٹرول کی حد کو نہیں سمجھتے۔
اصل بات یہ ہے کہ hooks صرف فائل میں ترمیم کے بعد اسکرپٹ چلانے کے بارے میں نہیں ہیں۔ وہ Claude کے پورے decision-making process کے دوران interception points فراہم کرتے ہیں۔ اس سے پہلے کہ وہ کوئی کمانڈ execute کرے۔ ٹول کال ناکام ہونے کے بعد۔ جب اسے اجازت کی ضرورت ہو۔ یہاں تک کہ user prompts کو پروسیس کرنے سے پہلے بھی۔
یہ گائیڈ وہ سب کچھ شامل کرتی ہے جو آفیشل دستاویزات فراہم کرتی ہے، پلس عملی پیٹرنز جو کمیونٹی کی بحثوں سے ظاہر ہوتے ہیں کہ وہ production environments میں واقعی کام کرتے ہیں۔
Claude Code Hooks اصل میں کیا کرتے ہیں
آفیشل Claude Code دستاویزات کے مطابق، hooks صارف کی طرف سے متعین کردہ شیل کمانڈز، HTTP endpoints، یا prompt injections ہیں جو Claude Code کے لائف سائیکل کے مخصوص نکات پر چلتی ہیں۔ وہ stdin کے ذریعے structured JSON ان پٹ وصول کرتے ہیں اور exit codes یا HTTP responses کے ذریعے workflow کو کنٹرول کرتے ہیں۔
خودکاری زیادہ تر گائیڈز کے تجویز کردہ سے گہری ہے۔ Hooks مکمل طور پر ٹول ایگزیکیوشن کو بلاک کر سکتے ہیں، Claude کے reasoning میں اضافی کنٹیکسٹ شامل کر سکتے ہیں، بیرونی سروسز کو ٹرگر کر سکتے ہیں، اور validation rules کو لاگو کر سکتے ہیں جن کا Claude کو احترام کرنا چاہیے۔
تین بنیادی hook اقسام موجود ہیں:
- Command hooks: شیل اسکرپٹ جو stdout، stderr، اور exit codes کے ذریعے بات چیت کرتے ہیں
- HTTP hooks: ریموٹ endpoints جو POST requests وصول کرتے ہیں اور JSON responses واپس کرتے ہیں
- Prompt hooks: مخصوص ایونٹس پر Claude کے کنٹیکسٹ میں شامل کردہ ڈائنامک ہدایات
ہر قسم مختلف خودکاری پیٹرنز کو پورا کرتی ہے۔ Command hooks مقامی توثیق اور فارمیٹنگ کو سنبھالتے ہیں۔ HTTP hooks بیرونی سروسز اور ڈیٹا بیس کے ساتھ ضم ہوتے ہیں۔ Prompt hooks بیرونی عمل کے بغیر Claude کے رویے کو تبدیل کرتے ہیں۔
Hook Lifecycle اور Event System
آفیشل دستاویزات Claude Code کے ایگزیکیوشن فلو کے دوران کئی hook ایونٹس (SessionStart, UserPromptSubmit, PreToolUse, PermissionRequest, PostToolUse, PostToolUseFailure, Notification، اور دیگر) کو متعین کرتی ہیں۔ کب ہر ایک چلتا ہے اسے سمجھنا یہ طے کرتا ہے کہ کون سی خودکاری ممکن ہے۔

| Event | When It Fires | Can Block |
|---|---|---|
| SessionStart | When a session begins or resumes | No |
| UserPromptSubmit | When you submit a prompt, before Claude processes it | Yes |
| PreToolUse | Before a tool call executes | Yes |
| PermissionRequest | When a permission dialog appears | Yes |
| PostToolUse | After a tool call succeeds | No |
| PostToolUseFailure | After a tool call fails | No |
| Notification | When Claude Code sends a notification | No |
| SubmitMessage | When Claude submits a message to the user | No |
| ContextCompaction | When context window approaches limits | No |
The blocking capability matters most. PreToolUse hooks can prevent dangerous operations before they execute. Exit code 1 blocks the action. Exit code 0 allows it. Exit code 2 prompts Claude to reconsider.
But wait. PostToolUse hooks cannot undo actions since the tool already executed. This limitation shapes how validation logic gets structured. Critical checks belong in PreToolUse. Cleanup and formatting belong in PostToolUse.

Browse AI Tool Perks While Setting Up Claude Code
If you are working with Claude Code hooks, you may also be choosing other AI tools around your workflow. Get AI Perks collects startup credits and software discounts for AI and cloud tools in one place. The platform includes 200+ offers, with perk conditions and claim guidance for each one.
Looking for Claude or Other AI Tool Perks?
Check Get AI Perks to:
- browse Claude and other AI tool offers
- compare perk conditions before applying
- find startup discounts across your tool stack
👉 Visit Get AI Perks to explore current AI software perks.
Configuration and File Structure
Hooks are defined in the .claude/settings.json file within a project. The configuration schema supports global hooks and tool-specific matchers that filter when hooks execute.
Basic command hook structure:
| { “hooks”: [ { “event”: “PostToolUse”, “command”: “prettier –write”, “args”: [“${file}”] } ] } |
The ${file} variable expands to the actual file path from the tool input. According to the official documentation, hooks support these variable expansions in command and args fields.
Hook Location Hierarchy
Claude Code checks multiple locations for hook definitions, with a clear precedence order:
- Project-level: .claude/settings.json in the current workspace
- User-level: ~/.claude/settings.json for all sessions
- Plugin-provided: Hooks bundled with installed plugins
Project hooks override user hooks for the same event. This allows project-specific formatting rules while maintaining global notification handlers.
Matcher Patterns for Selective Execution
The matcher system filters hooks to specific tools or conditions. Without matchers, hooks fire for every occurrence of their event.
| { “hooks”: [ { “event”: “PreToolUse”, “matcher”: { “toolName”: “edit_file”, “pathPattern”: “src/**/*.ts” }, “command”: “./scripts/validate-typescript.sh” } ] } |
The pathPattern field accepts glob syntax. The toolName field matches against Claude’s built-in tools like edit_file, execute_command, read_file, and create_directory.
Community discussions reveal that matcher combinations work with AND logic. All specified matchers must match for the hook to execute.
Command Hooks: Shell Script Integration
Command hooks execute shell commands or scripts with structured JSON input. They represent the most common hook type for local automation.
The official documentation specifies that command hooks receive JSON via stdin with this structure:
| { “event”: “PreToolUse”, “toolName”: “edit_file”, “toolInput”: { “path”: “src/app.ts”, “content”: “…” }, “sessionId”: “abc123”, “turnId”: “turn-456” }Scripts parse this input to make decisions. A Python validation hook might look like:#!/usr/bin/env python3 import sys import json input_data = json.load(sys.stdin) tool_input = input_data.get(‘toolInput’, {}) file_path = tool_input.get(‘path’, ”) if file_path.startswith(‘protected/’): print(“Cannot edit protected files”, file=sys.stderr) sys.exit(1) sys.exit(0) |
Exit code 0 allows the operation. Exit code 1 blocks it and shows the stderr message to Claude. Exit code 2 triggers special behavior depending on the event.
Exit Code 2 Behavior
According to the official hooks reference documentation, exit code 2 has event-specific meaning (PreToolUse: blocks and prompts reconsideration; UserPromptSubmit: provides context without blocking; PermissionRequest: blocks permission):
- PreToolUse: Blocks the tool and prompts Claude to reconsider with the stderr message as context
- UserPromptSubmit: Provides the stderr output as additional context without blocking
- PermissionRequest: Blocks the permission grant
This creates a middle ground between hard blocking and allowing. Claude receives feedback about why the action might be problematic and can adjust its approach.
Asynchronous Command Hooks
The async: true flag runs hooks in the background without blocking Claude’s workflow. This matters for slow operations like deployment notifications or metric collection.
| { “event”: “PostToolUse”, “matcher”: { “toolName”: “execute_command” }, “command”: “./scripts/log-to-analytics.sh”, “async”: true, “timeout”: 30 } |
When an async hook fires, Claude Code starts the process and continues immediately. The timeout field sets the maximum execution time in seconds. If not specified, async hooks use a 10-minute default timeout.
Real talk: async hooks can’t block operations since they run after Claude proceeds. They work for logging, notifications, and cleanup—not validation.
HTTP Hooks: External Service Integration
HTTP hooks POST JSON payloads to remote endpoints and parse responses for decision control. They enable integration with validation services, databases, and third-party tools.
Basic HTTP hook configuration:
| { “event”: “PreToolUse”, “url”: “api.example.com/validate”, “headers”: { “Authorization”: “Bearer ${API_TOKEN}” }, “timeout”: 5 } |
The payload structure matches command hook input but arrives as HTTP POST body. The response determines Claude’s next action.
HTTP Response Handling
According to the official documentation, HTTP hooks interpret responses based on status code and body content:
| Status Code | Effect | Message Source |
|---|---|---|
| 200 | Allow operation | Response body (optional) |
| 400 | Block operation | Response body shown to Claude |
| 500 | Hook error, allow operation | Logged but not shown to Claude |
| Other | Allow operation | Hook failure doesn’t block workflow |
The response body can include a message field that Claude sees as context. This enables validation services to explain why an operation was blocked.
Environment Variable Interpolation
HTTP hooks support ${VAR} syntax in url, headers, and other string fields. Variables expand from the environment where Claude Code runs.
According to the official MCP documentation, environment variable expansion includes a default fallback syntax: ${VAR:-default} expands to VAR if set, otherwise uses the default value.
Security constraint: According to GitHub issue #28044, HTTP hooks can only access environment variables explicitly listed in the allowedEnvVars configuration field. This prevents accidental credential exposure.
Prompt Hooks: Context Injection
Prompt hooks inject dynamic instructions into Claude’s context at specific events. They modify behavior without external processes or API calls.
| { “event”: “SessionStart”, “prompt”: “You are working on a TypeScript project. Always use strict null checks and prefer async/await over promises.” } |
The injected text becomes part of Claude’s system instructions for that session. Prompt hooks can also use template variables that expand based on event data.
Dynamic Prompt Generation
According to the official documentation, prompt hooks support command fields that generate dynamic prompts:
| { “event”: “ContextCompaction”, “type”: “prompt”, “command”: “./scripts/generate-context-summary.sh” } |
The command receives the standard JSON input via stdin and outputs the prompt text to stdout. This enables context-aware instruction generation based on project state.
Agent-Based Hooks
Agent hooks specify a subagent that handles the event instead of direct prompt injection. The subagent receives context about the event and can perform multi-step reasoning.
| { “event”: “PostToolUseFailure”, “agent”: “debugger”, “agentPrompt”: “A tool call failed. Analyze the error and suggest fixes.” } |
The named subagent must be defined in the project configuration. Agent hooks enable complex decision logic that simple prompt injection can’t provide.
Practical Hook Patterns
Community discussions and official examples reveal specific automation patterns that work reliably in production.
Auto-Format Code After Edits
The most common pattern formats code automatically after Claude edits files:
| { “event”: “PostToolUse”, “matcher”: { “toolName”: “edit_file”, “pathPattern”: “**/*.{js,ts,jsx,tsx}” }, “command”: “prettier”, “args”: [“–write”, “${toolInput.path}”] } |
The ${toolInput.path} variable expands to the edited file path. PostToolUse ensures formatting happens after successful edits but doesn’t block Claude’s workflow.
Block Protected File Modifications
PreToolUse hooks enforce file protection rules:
| { “event”: “PreToolUse”, “matcher”: { “toolName”: “edit_file” }, “command”: “./scripts/check-protected.sh” } |
The script validates the target path against protected patterns and exits with code 1 to block prohibited edits.
Get Notified When Claude Needs Input
According to the official workflow guide, Notification hooks can trigger desktop alerts or send messages to external services:
| { “event”: “Notification”, “command”: “osascript”, “args”: [“-e”, “display notification \”${message}\” with title \”Claude Code\””] } |
This fires whenever Claude Code sends a notification, including when waiting for user input or after task completion.
Re-Inject Context After Compaction
ContextCompaction hooks restore important context when the conversation window fills:
| { “event”: “ContextCompaction”, “type”: “prompt”, “command”: “cat .claude/critical-context.md” } |
The command output gets injected back into Claude’s context after compaction removes older messages. This prevents loss of critical project-specific instructions.
Audit Configuration Changes
Track when Claude modifies configuration files:
| { “event”: “PostToolUse”, “matcher”: { “toolName”: “edit_file”, “pathPattern”: “**/{package.json,.env,*.config.*}” }, “command”: “git”, “args”: [“add”, “${toolInput.path}”], “async”: true } |
Async execution prevents blocking Claude while git operations complete. This creates an audit trail of configuration changes without manual staging.
JSON Output and Decision Control
Command hooks can output structured JSON to provide detailed feedback beyond simple exit codes. According to the official reference, JSON output enables multi-field responses that Claude interprets for decision making.
| { “allowed”: false, “message”: “This file is protected by team policy”, “suggestion”: “Create a new file in src/features/ instead” } |
The allowed field controls whether the operation proceeds. The message appears to Claude as context. The suggestion field provides alternative approaches.
For hooks to output JSON, they must:
- Write valid JSON to stdout
- Exit with code 0 (for allowed) or 1 (for blocked)
- Include at minimum the allowed boolean field
Claude Code parses the JSON and uses it to enhance the feedback loop. Exit codes still determine the primary decision, but JSON provides richer context.
Hook Input Fields Reference
All hooks receive a JSON object via stdin with common fields plus event-specific data. Understanding the complete schema enables more sophisticated hook logic.

Common Input Fields
Every hook receives these base fields:
- event: The hook event name (e.g., “PreToolUse”)
- sessionId: Unique identifier for the current Claude session
- turnId: Identifier for the current conversation turn
- timestamp: ISO 8601 timestamp when the event fired
Tool Event Fields
PreToolUse, PostToolUse, and PostToolUseFailure events include:
- toolName: Name of the tool being invoked (edit_file, execute_command, etc.)
- toolInput: Object containing the tool’s input parameters
- toolResponse: Tool output data (PostToolUse only)
- error: Error details including message and code (PostToolUseFailure only)
The toolInput structure varies by tool. For edit_file it contains path and content. For execute_command it contains command and args.
Permission Event Fields
PermissionRequest events include:
- permissionType: Type of permission requested (file_write, command_execute, etc.)
- requestedAction: Specific action requiring permission
- resourcePath: File path or resource identifier affected
MCP Tool Hooks
According to the official hooks reference, hooks can match against Model Context Protocol (MCP) tools using the mcpTool matcher field. This enables hook execution when Claude uses external tools provided by MCP servers.
| { “event”: “PreToolUse”, “matcher”: { “mcpTool”: “database/query” }, “command”: “./scripts/validate-sql.sh” } |
The mcpTool value matches against the tool name in format server-name/tool-name. This allows validation logic for database queries, API calls, or other external operations.
GitHub feature requests indicate growing interest in deeper MCP integration, including hooks that can inspect MCP server notifications and respond to external events.
Security Considerations
Hooks execute with the same permissions as Claude Code itself. This creates security implications for multi-user environments and shared configurations.
Command Execution Sandbox
According to GitHub issue #28044, HTTP hooks route through a sandbox proxy that restricts network access and filters environment variables. Command hooks have no such restrictions—they run with full shell access.
The documentation recommends these practices:
- Never store credentials in hook commands
- Use environment variables for sensitive data
- Validate all input from ${…} expansions
- Implement timeout limits for external services
- Use async hooks for non-critical operations to prevent blocking on failures
Hook Execution Isolation
User-level hooks in ~/.claude/settings.json apply to all projects. This creates risks when working across different trust boundaries. Project-level hooks override user hooks but can’t completely disable them.
The /hooks menu in Claude Code shows all active hooks for the current session. Reviewing this list before working on sensitive projects helps identify potential security concerns.
Debugging and Troubleshooting
Hook failures don’t always surface clearly in Claude’s conversation. The official documentation provides several debugging approaches.
Hook Execution Logs
Claude Code logs hook execution to the session debug output. According to the troubleshooting guide, enabling debug logging reveals:
- Which hooks matched for each event
- The JSON input sent to each hook
- Stdout and stderr output from hook processes
- Exit codes and execution time
- HTTP response codes and bodies for HTTP hooks
Enable debug logging by setting CLAUDE_DEBUG=1 in the environment before starting Claude Code.
Testing Hooks Independently
Command hooks can be tested outside Claude Code by manually constructing JSON input:
| echo ‘{“event”:”PreToolUse”,”toolName”:”edit_file”,”toolInput”:{“path”:”test.txt”}}’ | ./scripts/my-hook.sh |
This validates hook logic without triggering actual Claude operations. The exit code and stdout/stderr output should match expected behavior.
Common Hook Failures
Community discussions identify these frequent issues:
- Timeout errors: Default 10-minute timeout too short for slow operations—increase with timeout field
- Path expansion failures: Variables like ${file} undefined for events that don’t include file context
- Permission errors: Hook scripts lack execute permissions—run chmod +x script.sh
- JSON parse errors: Malformed JSON output from hooks—validate with jq before returning
- Environment variable unavailability: Variables not propagated to hook process—check Claude Code’s environment
Hook Performance Implications
Synchronous hooks block Claude’s workflow until completion. The default 10-minute timeout prevents indefinite hangs, but even short delays accumulate across multiple operations.
Practitioners report that simple validation hooks have negligible performance impact. File formatting hooks cause noticeable but acceptable performance impact. External API calls can create workflow friction. Heavy computation operations benefit from async execution.
Hook Batching
Multiple hooks can match the same event. According to the reference documentation, hooks execute sequentially in definition order. If any hook blocks the operation, remaining hooks don’t execute.
This matters for performance. Five synchronous hooks at 200ms each add one second per event. Combining related validations into a single hook reduces overhead.
Advanced Patterns
Beyond basic automation, hooks enable sophisticated workflow customization.
Stateful Hook Chains
Hooks can maintain state between executions using files or databases. A PostToolUse hook might record successful operations that a PreToolUse hook later validates against:
| #!/bin/bash # Record successful edits echo “${toolInput.path}” >> .claude/edit-history.txt |
A companion PreToolUse hook could check this history to prevent redundant operations or enforce ordering constraints.
Conditional Hook Activation
Environment variables control hook behavior at runtime. Setting CLAUDE_SKIP_HOOKS=1 disables hooks for emergency situations.
Hooks themselves can check environment flags:
| #!/bin/bash if [ “$STRICT_MODE” = “1” ]; then # Apply strict validation exit 1 fi exit 0 |
This enables development mode versus production mode behavior without configuration changes.
Multi-Stage Validation
PreToolUse hooks can implement multi-tier validation where exit code 2 allows Claude to proceed with warnings:
- Hard failures (exit 1): Block dangerous operations
- Soft warnings (exit 2): Alert Claude to reconsider
- Pass with context (exit 0 + JSON): Provide additional information
This creates a validation spectrum more nuanced than binary allow/deny.
Integration with CI/CD
According to the official platform integration documentation, Claude Code runs in CI/CD environments for automated code review and issue triage. Hooks extend this automation.
GitHub Actions workflows can define hooks that enforce team policies during automated sessions:
| – name: Run Claude Code with strict hooks env: STRICT_MODE: 1 run: | claude “Review this PR and suggest improvements” |
The STRICT_MODE flag activates conditional validation logic in hook scripts. This ensures automated sessions follow more rigid rules than interactive development.
Audit Trail Generation
PostToolUse hooks in CI environments create detailed audit logs of all Claude operations:
| { “event”: “PostToolUse”, “command”: “./scripts/log-to-database.sh”, “async”: true } |
Background logging doesn’t impact performance but provides complete operation history for compliance and debugging.
The /hooks Menu
Claude Code provides a /hooks command that displays all active hooks for the current session. According to the official documentation, this menu shows:
- Hook event type
- Matcher patterns
- Command or URL endpoint
- Whether the hook runs async
- Configuration source (project, user, or plugin)
Selecting a hook shows its complete configuration and allows temporary disabling for the current session.
Disable or Remove Hooks
Hooks can be disabled without removing configuration by adding “enabled”: false to the hook definition. This preserves the configuration while preventing execution.
To permanently remove a hook, delete its entry from the appropriate settings.json file. Changes take effect on the next session restart or when running /reload.
Hooks in Skills and Agents
According to the official documentation, hooks defined within skill or subagent configurations apply only when that skill or agent executes. This enables specialized automation for specific workflows.
A debugging subagent might include hooks that log all tool calls:
| { “name”: “debugger”, “hooks”: [ { “event”: “PostToolUse”, “command”: “./scripts/log-debug.sh”, “async”: true } ] } |
These hooks only fire during debugger agent sessions, not during normal Claude Code operation.
Reference Scripts by Path
Hook commands support both relative and absolute paths. Relative paths resolve from the project root where Claude Code runs.
Best practices from community discussions:
- Store hook scripts in .claude/hooks/ directory
- Use descriptive names: validate-typescript.sh not hook1.sh
- Make scripts executable: chmod +x .claude/hooks/*.sh
- Include shebang line: #!/usr/bin/env bash or #!/usr/bin/env python3
- Add error handling with set -e in bash scripts
Future Hook Capabilities
GitHub feature requests reveal planned and requested hook enhancements:
- Inline script hooks: Define hook logic directly in settings.json without external files
- MCP tool integration: Invoke MCP server tools from hooks instead of shell commands
- Multi-agent collaboration: Hooks that coordinate between Claude instances on different machines
- Enhanced typing: TypeScript type definitions for hook input/output schemas
According to GitHub issue #4274, the request for integrated hook types (MCP tool, inline script, API call) aims to simplify configuration and improve developer experience.
Frequently Asked Questions
Can hooks prevent Claude from executing dangerous commands?
Yes. PreToolUse hooks can block any tool execution by exiting with code 1. This includes file edits, command execution, and MCP tool calls. The hook receives the complete tool input and can validate against any criteria before allowing the operation.
How do I debug a hook that isn’t working?
Enable debug logging with CLAUDE_DEBUG=1 before starting Claude Code. Check the session logs for hook execution details including which hooks matched, the JSON input sent, stdout/stderr output, and exit codes. Test hooks independently by piping sample JSON to the hook script.
Do hooks work with all Claude Code platforms?
Hooks work in the CLI, desktop app, and VS Code extension. According to the official documentation, hooks execute wherever Claude Code runs with access to the file system. Browser-based Claude and mobile apps don’t support hooks due to sandboxing constraints.
Can hooks modify Claude’s responses or behavior?
Prompt hooks inject instructions that influence Claude’s behavior. Agent hooks delegate event handling to specialized subagents. However, hooks cannot directly modify Claude’s generated text or reasoning process—they work by providing context and blocking operations.
What’s the difference between async and sync hooks?
Synchronous hooks block Claude’s workflow until completion or timeout. Asynchronous hooks run in the background without blocking. Sync hooks can prevent operations through exit codes. Async hooks cannot block since Claude continues before the hook completes. Use async for logging and notifications, sync for validation.
How do I share hooks across a team?
Commit the .claude/settings.json file to version control. Project-level hooks apply to all team members who clone the repository. For organization-wide policies, teams can maintain a shared user-level settings file that members copy to ~/.claude/settings.json.
Can HTTP hooks call internal APIs behind firewalls?
Yes, if Claude Code runs in an environment with network access to those APIs. HTTP hooks make standard POST requests from the machine running Claude Code. Corporate firewalls and VPNs apply normally. The sandbox proxy mentioned in documentation controls environment variable exposure, not network routing.
Do hooks increase Claude Code’s token usage?
Prompt hooks inject text into Claude’s context, which consumes tokens. Command and HTTP hooks don’t directly affect token usage, but their output (error messages, suggestions) becomes part of the conversation context. Exit code 2 with explanatory messages adds more context than exit code 1 with simple blocking.
Conclusion
Claude Code hooks transform the AI assistant from a powerful tool into a fully automated development platform. The event system provides interception points throughout Claude’s workflow—from session initialization through context compaction.
Command hooks handle local validation and formatting. HTTP hooks integrate external services and databases. Prompt hooks modify behavior through context injection. Together, these enable automation patterns that enforce team policies, maintain code quality, and integrate with existing development infrastructure.
The matcher system filters hooks to specific tools and file patterns. Exit codes and JSON output control decision flow. Async execution prevents blocking on slow operations. The complete configuration schema supports everything from simple auto-formatting to complex multi-stage validation.
Start with basic PostToolUse hooks for code formatting. Add PreToolUse validation as policies emerge. Experiment with prompt hooks for behavior modification. Build HTTP integrations for team-wide enforcement.
Check the official Claude Code documentation for the complete hooks reference and updated configuration schema as new capabilities ship.

