MCPInstall
athola avatar

hook-authoring

Guide creating Claude Code hooks with security-first design. Use for validation and enforcement.

Installs
113
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/athola/claude-night-market --skill hook-authoring
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads hook-authoring automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

When NOT To Use

  • Auditing a hook that already exists (use abstract:hooks-eval)
  • Choosing where a hook should live (use abstract:hook-scope-guide)
  • Authoring a skill rather than a hook (use abstract:skill-authoring)

Hook Authoring Guide

Overview

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.

Key Capabilities

  • PreToolUse: Validate, filter, or transform tool inputs before execution; inject context (2.1.9+)
  • PostToolUse: Log, analyze, or modify tool outputs after execution
  • UserPromptSubmit: Inject context or filter user messages before processing
  • Stop/SubagentStop: Cleanup, final reporting, or result aggregation
  • TeammateIdle/TaskCompleted: Multi-agent coordination and orchestration (2.1.33+)
  • PreCompact: State preservation before context window compaction

New in 2.1.9: PreToolUse hooks can now return additionalContext to inject information before a tool executes. This enables patterns like cache hints, security warnings, or relevant context injection.

Quick Start

Your First Hook (JSON - Claude Code)

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.

Your First Hook (Python - Claude Agent SDK)

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

Hook Event Types

Quick reference for the events most plugins use. Every event also receives the common fields (session_id, transcript_path, cwd, hook_event_name, and permission_mode where it applies). The full roster of 33 events is plugins/abstract/src/abstract/hook_events.py, and each event's input is in code.claude.com/docs/en/hooks.

EventTrigger PointParametersCommon Use Cases
PreToolUseBefore tool executiontool_name, tool_input, tool_use_idValidation, filtering, input transformation
PostToolUseAfter a tool succeedstool_name, tool_input, tool_responseLogging, metrics, updatedToolOutput to replace the result
PostToolUseFailureAfter a tool failstool_name, tool_input, errorFailure logging; the exit code is the first line of error
UserPromptSubmitUser sends messagepromptContext injection, content filtering
PermissionRequestPermission dialog showntool_name, tool_input, permission_suggestionsAuto-approve/deny with custom logic
NotificationClaude Code sends notificationmessage, title, notification_typeCustom notification handling
StopMain turn endsstop_hook_active, last_assistant_message, background_tasks, session_cronsFinal checks; read background_tasks before blocking
SubagentStopSubagent completesagent_id, agent_type, agent_transcript_path, last_assistant_messageResult processing, aggregation
TeammateIdleTeammate agent becomes idleteammate_name, team_nameWork assignment, load balancing
TaskCompletedTask marked completetask_id, task_subject, task_descriptionCoordination, chaining, reporting
PreCompactBefore context compacttrigger, custom_instructionsState preservation, checkpointing
SessionStartSession starts/resumessource, model, agent_typeInitialization, context loading
SessionEndSession terminatesreasonCleanup, final logging
WorktreeCreateAgent worktree creatednameCustom VCS setup, symlink .venv, pre-populate caches
WorktreeRemoveAgent worktree removedworktree_pathCleanup temp files, teardown worktree-scoped resources

SessionStart Input Schema (Claude Code 2.1.2+)

The SessionStart hook receives JSON input via stdin with these fields:

{
  "session_id": "abc123",
  "source": "startup",
  "agent_type": "my-agent"
}

Fields: source is one of "startup", "resume", "clear", or "compact". agent_type is populated when the --agent flag is used.

agent_type field: When Claude Code is launched with --agent my-agent, this field contains the agent name, enabling agent-specific initialization:

# Python example: Agent-aware SessionStart hook
input_data = json.loads(sys.stdin.read())
agent_type = input_data.get("agent_type", "")

if agent_type in ["code-reviewer", "quick-query"]:
    # Skip heavy context injection for lightweight agents
    print(json.dumps({"hookSpecificOutput": {"additionalContext": "Minimal context"}}))
else:
    # Full initialization for implementation agents
    print(json.dumps({"hookSpecificOutput": {"additionalContext": full_context}}))
# Bash example: Agent-aware SessionStart hook
HOOK_INPUT=$(cat)
AGENT_TYPE=$(echo "$HOOK_INPUT" | jq -r '.agent_type // empty')

case "$AGENT_TYPE" in
    code-reviewer|quick-query)
        echo '{"hookSpecificOutput": {"additionalContext": "Minimal context"}}'
        ;;
    *)
        echo '{"hookSpecificOutput": {"additionalContext": "Full context"}}'
        ;;
esac

Hooks in Frontmatter (Claude Code 2.1.0+)

New in 2.1.0: Define hooks directly in skill, command, or agent frontmatter. These hooks are scoped to the component's lifecycle.

Skill/Command/Agent Frontmatter Hooks

---
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"
---

The once: true Configuration

New in 2.1.0: Use once: true to execute a hook only once per session, ideal for:

  • One-time setup/initialization
  • Resource allocation that shouldn't repeat
  • Session-level configuration
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

Frontmatter vs Settings Hooks

AspectFrontmatter HooksSettings Hooks
ScopeComponent lifecycleGlobal/project
LocationIn skill/agent/commandsettings.json
PersistenceActive only when component runsAlways active
Use caseComponent-specific validationCross-cutting concerns

PreToolUse updatedInput (2.1.0 Fix)

PreToolUse hooks can now return updatedInput when returning ask permission decision, enabling hooks to act as middleware while still requesting user consent:

{
  "decision": "ask",
  "updatedInput": {
    "command": "modified-command --safe-flag"
  }
}

Claude Code vs SDK

JSON Hooks (Claude Code)

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 tools

Pros: Simple, no code required, easy to version control Cons: Limited logic capabilities, shell command only

HTTP Hooks (Claude Code 2.1.63+)

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:

  • Enterprise environments where shell execution is restricted
  • Centralized hook logic shared across teams via a web service
  • Sandboxed or containerized setups without local script access
  • Integration with external validation/logging services

Pros: No local scripts needed, centralized logic, works in sandboxed environments Cons: Network latency, requires running HTTP service, external dependency

Python SDK Hooks

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.

Bash Permission Matching Notes

Environment Variable Wrappers (2.1.38+)

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.

Heredoc Delimiter Security (2.1.38+)

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.

Security Essentials

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.

Performance Guidelines

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.

Scope Selection

Plugin hooks live in hooks/hooks.json, which auto-loads when the plugin is enabled. Listing it again in plugin.json causes duplicate load errors. Project hooks live 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.

Common Patterns

Validation, logging, context injection and PreToolUse additionalContext injection (2.1.9+) are written out in modules/common-patterns.md.

Testing Hooks

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.

Hook Exit Codes

Hooks communicate decisions to Claude Code via exit codes:

Exit CodeMeaningstdoutstderr
0Success/allowShown to Claude as system contextIgnored
2Block/denyIgnoredShown to user as explanation (2.1.39+ fix)
OtherErrorIgnoredShown to user as error message

Blocking with Exit Code 2 (2.1.39+)

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.

Environment Variables (Claude Code 2.1.2+)

FORCE_AUTOUPDATE_PLUGINS

Forces plugin auto-update even when the main Claude Code auto-updater is disabled.

Use cases:

  • CI/CD pipelines that need latest plugin versions
  • Development environments testing plugin updates
  • Controlled update rollouts in enterprise settings
# 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.

Troubleshooting

Common Issues

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.

Module References

For detailed guidance on specific topics:

  • Hook Types: modules/hook-types.md - Detailed event signatures and parameters
  • SDK Callbacks: modules/sdk-callbacks.md - Python SDK implementation patterns
  • Security Essentials: modules/security-essentials.md - security rules and a secret-redacting hook
  • Common Patterns: modules/common-patterns.md - validation, logging and context injection hooks
  • Performance Guidelines: modules/performance-guidelines.md - Optimization techniques
  • Scope Selection: modules/scope-selection.md - Choosing plugin/project/global
  • Testing Hooks: modules/testing-hooks.md - Testing strategies and fixtures
  • Observability Warnings: modules/observability-warnings.md - Copy-pasteable resolution pattern for binary-actionable drift hooks

Tools

  • hook_validator.py: Validate hook structure and syntax (at plugins/abstract/scripts/hook_validator.py)

Related Skills

  • hook-scope-guide: Decision framework for hook placement (existing)
  • modular-skills: Design patterns for skill architecture
  • skills-eval: Quality assessment and improvement framework

Next Steps

  1. Choose your hook type (JSON vs SDK) based on complexity needs
  2. Select the appropriate scope (plugin/project/global)
  3. Implement following security and performance best practices
  4. Test thoroughly with unit and integration tests
  5. Validate using hook_validator.py before deployment

References

Exit Criteria

  • The authored hook file exists at a valid scope location (hooks/hooks.json, .claude/settings.json, or ~/.claude/settings.json) with correct JSON or Python syntax.
  • The hook fires on the target event: a test invocation of the matching tool call triggers the hook command or callback without error.
  • The hook contains no secret logging: no field names matching api[_-]?key, password, token, secret, or credential appear in log output paths.
  • Blocking hooks exit with code 2 and write the user-facing explanation to stderr (not stdout).
  • If abstract:validate-hook is available, it exits 0 on the authored hook file.

FAQ

What does the hook-authoring skill do?

Guide creating Claude Code hooks with security-first design. Use for validation and enforcement.

How do I install hook-authoring?

Run npx skills add https://github.com/athola/claude-night-market --skill hook-authoring in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/hook-authoring/ (personal) or .claude/skills/hook-authoring/ (project).

Which AI agents can use hook-authoring?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is hook-authoring safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains hook-authoring?

It is published by athola in athola/claude-night-market. It has 113 recorded installs.

More from athola/claude-night-market

View all →
athola avatar

project-planning

athola/claude-night-market

Converts a specification into a phased, dependency-ordered implementation plan. Use after specification is complete and before execution begins.

athola avatar

code-quality-principles

athola/claude-night-market

Applies KISS, YAGNI, and SOLID principles for clean code with reduced complexity. Use when refactoring or reviewing code for over-engineering.

athola avatar

slop-detector

athola/claude-night-market

Detects AI-generated writing patterns in prose. Use when reviewing docs for slop, vague language, or identity leaks before publishing.

Docs & Writing183 installs
athola avatar

bloat-detector

athola/claude-night-market

Detects codebase bloat via dead code, duplication, complexity, and doc bloat scans. Use when codebase feels large or before a release.

athola avatar

doc-generator

athola/claude-night-market

Generates or remediates documentation with human-quality writing. Use when creating new docs, rewriting AI-generated content, or applying style profiles.

Docs & Writing162 installs
athola avatar

project-brainstorming

athola/claude-night-market

Guides project ideation via Socratic questioning to produce a validated brief. Use before specification when requirements are unclear.

161 installs

Popular security skills

View category →
microsoft avatar

azure-compliance

microsoft/azure-skills

Run Azure compliance and security audits with azqr plus Key Vault expiration checks. Covers best-practice assessment, resource review, policy/compliance validation, and security posture checks. WHEN: compliance scan, security audit, BEFORE running azqr (compliance cli tool), Azure best practices, Key Vault expiration check, expired certificates, expiring secrets, orphaned resources, compliance assessment.

OfficialSecurity752.6K installs
lllllllama avatar

minimal-run-and-audit

lllllllama/rigorpilot-skills

Rigor Run skill for README-first deep learning repo reproduction. Use when the task is specifically to capture or normalize evidence from the selected smoke test or documented inference or evaluation command and write standardized reprooutputs/ files, including patch notes when repository files changed. Do not use for training execution, initial repo intake, generic environment setup, paper lookup, target selection, hidden scientific-meaning changes, or end-to-end orchestration by itself.

Security502.3K installs
coreyhaines31 avatar

seo-audit

coreyhaines31/marketingskills

When the user wants to audit, review, or diagnose SEO issues on their site. Also use when the user mentions "SEO audit," "technical SEO," "why am I not ranking," "SEO issues," "on-page SEO," "meta tags review," "SEO health check," "my traffic dropped," "lost rankings," "not showing up in Google," "site isn't ranking," "Google update hit me," "page speed," "core web vitals," "crawl errors," "indexing issues," "stuck on page 2," "striking distance keywords," "title tag rewrite," "low CTR," "local SEO," "Google Business Profile," or "map pack." Use this even if the user just says something vague like "my SEO is bad" or "help with SEO" — start with an audit. For building pages at scale to target keywords, see programmatic-seo. For adding structured data, see schema. For AI search optimization, see ai-seo.

Security261.5K installs
firebase avatar

firebase-security-rules-auditor

firebase/agent-skills

Audits Firebase (Firestore, Cloud Storage) security rules for vulnerabilities, privilege escalation, role bypasses, create vs update inconsistencies, resource exhaustion, type safety, size limits, and hasOnly ownership checks. Use when auditing/reviewing rules, running red-team rule assessments, or scoring against auditor checklists. Don't use for Firebase CLI (login, deploy), Auth, Crashlytics, Remote Config, or database queries.

OfficialSecurity151.8K installs
cloudflare avatar

security-audit

cloudflare/security-audit-skill

Security guidance and vulnerability review for codebases, APIs, services, CLI tools, libraries, and daemons. Use for security questions, focused reviews, vulnerability research, security audits, or pen tests. Run the complete workflow only for explicit codebase audit or pen-test requests, full/comprehensive/end-to-end reviews, or requested report artifacts.

Security119.6K installs
coreyhaines31 avatar

competitors

coreyhaines31/marketingskills

When the user wants to create competitor comparison or alternative pages for SEO and buyer-facing use. Also use when the user mentions 'alternative page,' 'vs page,' 'competitor comparison,' 'comparison page,' '[Product] vs [Product],' '[Product] alternative,' 'competitive landing pages,' 'how do we compare to X,' 'competitor teardown,' 'audit our competitor pages,' 'are our comparison pages out of date,' or 'competitive asset audit.' Use this for any content that positions your product against competitors. Covers four formats: singular alternative, plural alternatives, you vs competitor, and competitor vs competitor. For auditing existing claims (not researching competitors from scratch, which is competitor-profiling; not technical SEO on these pages, which is seo-audit), use the asset audit here. For internal battle cards and sales-specific competitor docs, see sales-enablement.

Security93.1K installs