/abstract:hook-authoringfrom abstract
Guides creating Claude Code hooks with security-first design. Covers JSON and Python hooks for validation, logging, context injection, and workflow automation.
Ships in abstract. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
abstract:hooks-eval)abstract:hook-scope-guide)abstract:skill-authoring)Hooks are event interceptors that allow you to extend Claude Code and Claude Agent SDK behavior by executing custom logic at specific points in the agent lifecycle. They enable validation before tool use, logging after actions, context injection, workflow automation, and security enforcement.
This skill teaches you how to write effective, secure, and performant hooks for both declarative JSON (Claude Code) and programmatic Python (Claude Agent SDK) use cases.
New in 2.1.9: PreToolUse hooks can now return
additionalContextto inject information before a tool executes. This enables patterns like cache hints, security warnings, or relevant context injection.
Create a simple logging hook in .claude/settings.json:
{
"PostToolUse": [
{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "echo \"$(date): Executed $(jq -r '.tool_name')\" >> ~/.claude/audit.log"
}]
}
]
}
Note: Use string matchers ("Bash") not object matchers ({"toolName": "Bash"}).
This logs every Bash command execution with a timestamp.
Create a validation hook using the SDK:
from claude_agent_sdk import AgentHooks
class ValidationHooks(AgentHooks):
async def on_pre_tool_use(self, tool_name: str, tool_input: dict) -> dict | None:
"""Validate tool inputs before execution."""
if tool_name == "Bash":
command = tool_input.get("command", "")
if "rm -rf /" in command:
raise ValueError("Dangerous command blocked by hook")
# Return None to proceed unchanged, or modified dict to transform
return None
Every event, its matcher and its input fields, including the
SessionStart input schema, are in modules/hook-types.md.
New in 2.1.0: Define hooks directly in skill, command, or agent frontmatter. These hooks are scoped to the component's lifecycle.
---
name: validated-skill
description: Skill with lifecycle hooks
hooks:
PreToolUse:
- matcher: "Bash"
command: "./validate-command.sh"
once: true # NEW: Run only once per session
- matcher: "Write|Edit"
command: "./pre-edit-check.sh"
PostToolUse:
- matcher: "Write|Edit"
command: "./format-on-save.sh"
Stop:
- command: "./cleanup-and-report.sh"
---
once: true ConfigurationNew in 2.1.0: Use once: true to execute a hook only once per session, ideal for:
hooks:
PreToolUse:
- matcher: "Bash"
command: "./setup-environment.sh"
once: true # Runs only on first Bash call
SessionStart:
- command: "./initialize-session.sh"
once: true # Runs only once at session start
| Aspect | Frontmatter Hooks | Settings Hooks |
|---|---|---|
| Scope | Component lifecycle | Global/project |
| Location | In skill/agent/command | settings.json |
| Persistence | Active only when component runs | Always active |
| Use case | Component-specific validation | Cross-cutting concerns |
PreToolUse hooks can now return updatedInput when returning ask permission decision. A hook can then act as middleware while still requesting user consent:
{
"decision": "ask",
"updatedInput": {
"command": "modified-command --safe-flag"
}
}
Since 2.1.300 the harness validates updatedInput the way it validates
Claude's own input. Unknown keys are dropped and invalid input denies
the call. Return only the tool's real parameters.
A command or HTTP hook that fails to start, times out, or exits
unexpectedly lets the action through by default. Set
"onFailure": "block" on the hook entry, beside command, to block
the action instead. Use it for guards whose silence would be unsafe.
On the matcher group the key is ignored and the hook fails open.
Declarative configuration in .claude/settings.json, project .claude/settings.json, or plugin hooks/hooks.json:
{
"PreToolUse": [
{
"matcher": "Edit",
"hooks": [{
"type": "command",
"command": "echo 'WARNING: Editing production file' >&2"
}]
}
]
}
Important: Use string matchers (regex patterns), not object matchers. The object format {"toolName": "Edit"} is deprecated.
Matcher patterns:
"Edit" - Match single tool"Read|Write|Edit" - Match multiple tools (regex OR)".*" - Match all toolsPros: Simple, no code required, easy to version control Cons: Limited logic capabilities, shell command only
New in 2.1.63: Hooks can POST JSON to a URL and receive JSON responses instead of running shell commands. Use "type": "http" with a "url" field:
{
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [{
"type": "http",
"url": "https://my-service.example.com/hooks/validate-bash"
}]
}
]
}
The hook POSTs the standard hook input as JSON and expects a standard hook response JSON body.
When to use HTTP hooks over command hooks:
Pros: No local scripts needed, centralized logic, works in sandboxed environments Cons: Network latency, requires running HTTP service, external dependency
Programmatic callbacks using the AgentHooks base class, for logic
that needs full Python, complex validation or state. The base class,
callback signatures and implementation patterns are in
modules/sdk-callbacks.md.
Permission rules now correctly match commands prefixed with environment variable assignments. Before 2.1.38, NODE_ENV=production npm test would not match a rule for Bash(npm *).
# These now all match `Bash(npm *)`:
npm test
NODE_ENV=production npm test
FORCE_COLOR=1 CI=true npm test
When writing PreToolUse hooks that inspect bash commands, be aware that the permission system strips env var prefixes for matching, but your hook receives the full command string including prefixes.
Claude Code now validates heredoc delimiters to prevent command smuggling. The recommended pattern <<'EOF' (single-quoted) remains the safest approach. Always use single-quoted delimiters in heredoc patterns to prevent variable expansion.
Validate tool input, never log secrets, respect sandbox boundaries,
fail safe, rate-limit and sanitize logged content. The six rules and a
secret-redacting logging hook are in modules/security-essentials.md.
Keep hooks non-blocking and fail fast. The hook timeout is 10 minutes
(increased from 60s in 2.1.3), and most hooks should finish in under
30s. Budgets, async I/O, batching, bounded state and profiling are in
modules/performance-guidelines.md.
Plugin hooks are in hooks/hooks.json, which auto-loads when the
plugin is enabled. Listing it again in plugin.json causes duplicate
load errors. Project hooks are in .claude/settings.json and
global hooks in ~/.claude/settings.json. The decision framework is
modules/scope-selection.md, also served as abstract:hook-scope-guide.
Validation, logging, context injection and PreToolUse
additionalContext injection (2.1.9+) are written out in
modules/common-patterns.md.
Unit-test each callback directly: assert a dangerous input raises and a
safe input returns None. Test categories, fixtures and the security
test checklist are in modules/testing-hooks.md.
Hooks communicate decisions to Claude Code via exit codes:
| Exit Code | Meaning | stdout | stderr |
|---|---|---|---|
| 0 | Success/allow | Shown to Claude as system context | Ignored |
| 2 | Block/deny | Ignored | Shown to user as explanation (2.1.39+ fix) |
| Other | Error | Ignored | Shown to user as error message |
Use exit code 2 to block an action and display a message to the user:
#!/bin/bash
# Example: Block force pushes with user-facing message
command=$(echo "$1" | jq -r '.tool_input.command // empty')
if echo "$command" | grep -q 'push.*--force'; then
echo "Force push blocked: use --force-with-lease instead" >&2
exit 2
fi
exit 0
Important: Before Claude Code 2.1.39, stderr from exit code 2 was silently swallowed (#10964). Users would see a generic "hook error" instead of the custom message. This is now fixed: stderr is properly displayed to the user.
Plugin hooks: Before 2.1.39, plugin-installed hooks had a separate code path that also failed to show stderr for exit code 2 (#10412). Both plugin and project hooks now work correctly.
FORCE_AUTOUPDATE_PLUGINSForces plugin auto-update even when the main Claude Code auto-updater is disabled.
Use cases:
# Enable forced plugin updates
export FORCE_AUTOUPDATE_PLUGINS=1
claude
# Or inline
FORCE_AUTOUPDATE_PLUGINS=1 claude --agent my-agent
Note: This only affects plugin updates, not Claude Code core updates.
Hook not firing Verify hook pattern matches the event. Check hook logs for errors
Syntax errors Validate JSON/Python syntax before deployment
Permission denied Check hook file permissions and ownership
Hook blocking message not shown (pre-2.1.39) If using exit code 2 to block with a user-facing message and the message is not appearing, upgrade to Claude Code 2.1.39+. In older versions, use exit 0 with stdout as a workaround.
For detailed guidance on specific topics:
modules/hook-types.md - Detailed event signatures and parametersmodules/sdk-callbacks.md - Python SDK implementation patternsmodules/security-essentials.md - security
rules and a secret-redacting hookmodules/common-patterns.md - validation, logging
and context injection hooksmodules/performance-guidelines.md - Optimization techniquesmodules/scope-selection.md - Choosing plugin/project/globalmodules/testing-hooks.md - Testing strategies and fixturesmodules/observability-warnings.md - Copy-pasteable resolution pattern for binary-actionable drift hooksplugins/abstract/scripts/hook_validator.py)hook_validator.py before deploymenthooks/hooks.json,
.claude/settings.json, or ~/.claude/settings.json) with correct JSON or Python syntax.api[_-]?key, password,
token, secret, or credential appear in log output paths.abstract:validate-hook is available, it exits 0 on the authored hook file.modules/common-patterns.md (opens in a new tab)modules/hook-types.md (opens in a new tab)modules/observability-warnings.md (opens in a new tab)modules/performance-guidelines.md (opens in a new tab)modules/scope-selection.md (opens in a new tab)modules/sdk-callbacks.md (opens in a new tab)modules/security-essentials.md (opens in a new tab)modules/testing-hooks.md (opens in a new tab)scripts/README.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub athola/claude-night-market --plugin abstract14 skills in this plugin
/hooks-evalEvaluate hook security, performance, and SDK compliance. Use for audits.Other plugins' skills for the same job