Skip to content
Development
Skill

/hook-authoring

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

From plugin
claude-night-market
337200 skills59 agents162 commands1 MCP
Install
$ npx -y skills add athola/claude-night-market --skill hook-authoring --agent claude-code

How it fires

How this skill gets triggered: by you, by Claude, or both.

  • Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
  • You can call itInvoke it directly when you want it.
  • Slash command/hook-authoring

Context preview

The summary Claude sees to decide when to auto-load this skill.

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

SKILL.md

hook-authoring.SKILL.md
name: hook-authoring
description: 'Guide creating Claude Code hooks with security-first design. Use for validation and enforcement.'
alwaysApply: false
category: hook-development
tags:
- hooks
- sdk
- security
- performance
- automation
- validation
dependencies: []
estimated_tokens: 1200
complexity: intermediate
model_hint: standard
provides:
  patterns:
  - hook-authoring
  - security-patterns
  - performance-optimization
  infrastructure:
  - hook-validation
  - testing-framework
usage_patterns:
- writing-hooks
- hook-validation
- security-patterns
- performance-optimization
- sdk-integration

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`)

Table of Contents

  • [Overview](#overview)
  • [Key Capabilities](#key-capabilities)
  • [Quick Start](#quick-start)
  • [Your First Hook (JSON - Claude Code)](#your-first-hook-json-claude-code)
  • [Your First Hook (Python - Claude Agent SDK)](#your-first-hook-python-claude-agent-sdk)
  • [Hook Event Types](#hook-event-types)
  • [Claude Code vs SDK](#claude-code-vs-sdk)
  • [JSON Hooks (Claude Code)](#json-hooks-claude-code)
  • [Python SDK Hooks](#python-sdk-hooks)
  • [Security Essentials](#security-essentials)
  • [Critical Security Rules](#critical-security-rules)
  • [Example: Secure Logging Hook](#example-secure-logging-hook)
  • [Performance Guidelines](#performance-guidelines)
  • [Performance Best Practices](#performance-best-practices)
  • [Example: Efficient Hook](#example-efficient-hook)
  • [Scope Selection](#scope-selection)
  • [Decision Framework](#decision-framework)
  • [Scope Comparison](#scope-comparison)
  • [Common Patterns](#common-patterns)
  • [Validation Hook](#validation-hook)
  • [Logging Hook](#logging-hook)
  • [Context Injection Hook](#context-injection-hook)
  • [Testing Hooks](#testing-hooks)
  • [Unit Testing](#unit-testing)
  • [Module References](#module-references)
  • [Tools](#tools)
  • [Related Skills](#related-skills)
  • [Next Steps](#next-steps)
  • [References](#references)

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"}`).

**Verification:** Run the command with `--help` flag to verify availability.

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

**Verification:** Run the command with `--help` flag to verify availability.

Hook Event Types

Quick reference for all supported hook events:

| Event | Trigger Point | Parameters | Common Use Cases | |-------|--------------|------------|------------------| | **PreToolUse** | Before tool execution | `tool_name`, `tool_input` | Validation, filtering, input transformation | | **PostToolUse** | After tool execution | `tool_name`, `tool_input`, `tool_output` | Logging, metrics, output transformation | | **UserPromptSubmit** | User sends message | `message` | Context injection, content filtering | | **PermissionRequest** | Permission dialog shown | `tool_name`, `tool_input` | Auto-approve/deny with custom logic | | **Notification** | Claude Code sends notification | `message` | Custom notification handling | | **Stop** | Agent completes | `reason`, `result` | Final cleanup, summary reports | | **SubagentStop** | Subagent completes | `subagent_id`, `result` | Result processing, aggregation | | **TeammateIdle** | Teammate agent becomes idle | `agent_id`, `session_id` | Work assignment, load balancing (2.1.33+) | | **TaskCompleted** | Task finishes execution | `task_id`, `result` | Coordination, chaining, reporting (2.1.33+) | | **PreCompact** | Before context compact | `context_size` | State preservation, checkpointing | | **SessionStart** | Session starts/resumes | `session_id`, `source`, `agent_type` | Initialization, context loading | | **SessionEnd** |

Read more
Ships withclaude-night-market

A plugin marketplace for Claude Code. Install only the plugins you need to run git workflows, code review, spec-driven development, and autonomous agents from inside your Claude Code session.

Get the whole plugin

Other skills on claude-night-market.