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
343200 skills60 agents162 commands1 MCP

Claude Code

$ npx -y skills add athola/claude-night-market --skill hook-authoring --agent claude-code

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

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.

| Event | Trigger Point | Parameters | Common Use Cases | |-------|--------------|------------|------------------| | **PreToolUse** | Before tool execution | `tool_name`, `tool_input`, `tool_use_id` | Validation, filtering, input transformation | | **PostToolUse** | After a tool succeeds | `tool_name`, `tool_input`, `tool_response` | Logging, metrics, `updatedToolOutput` to replace the result | | **PostToolUseFailure** | After a tool fails | `tool_name`, `tool_input`, `error` | Failure logging; the exit code is the first line of `error` | | **UserPromptSubmit** | User sends message | `prompt` | Context injection, content filtering | | **PermissionRequest** | Permission dialog shown | `tool_name`, `tool_input`, `permission_suggestions` | Auto-approve/deny with custom logic | | **Notification** | Claude Code sends notification | `message`, `title`, `notification_type` | Custom notification handling | | **Stop** | Main turn ends | `stop_hook_active`, `last_assistant_message`, `background_tasks`, `session_crons` | Final checks; read `background_tasks` before blocking | | **SubagentStop** | Subagent completes | `agent_id`, `agent_type`, `agent_transcript_path`, `last_assistant_message` | Result processing, aggregation | | **TeammateIdle** | Teammate agent becomes idle | `teammate_name`, `team_name` | Work assignment, load balancing | | **TaskCompleted** | Task marked complete | `task_id`, `task_subject`, `task_description` | Coordination, chaining, reporting | | **PreCompact** | Before context compact | `trigger`, `custom_instructions` | State preservation, checkpointing | | **SessionStart** | Session starts/resumes | `source`, `model`, `agent_type` | Initialization, context loading | | **SessionEnd** | Session terminates | `reason` | Cleanup, final logging | | **WorktreeCreate** | Agent worktree created | `name` | Custom VCS setup, symlink .venv, pre-populate caches | | **WorktreeRemove** | Agent worktree removed | `worktree_path` | Cleanup 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-spe

Read more
@athola
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.

343200 skills60 agents1 MCP
Get the whole plugin

Stars on GitHub

Momentum

stars in total
343
Star history of athola/claude-night-market on GitHub, a chart by star-history.com

Other skills on claude-night-market.

More skills from other plugins.

brainstorming
Auto-invoked

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or…

@obra@obraInstall Skill
ask-matt

ask-matt

Ask which skill or flow fits your situation. A router over the skills in this repo.

skills11d309k
@mattpocock@mattpocockInstall Skill
accessibility
Auto-invoked

accessibility

Design, implement, and audit accessible UI to WCAG 2.2 Level AA across Web, iOS, and Android — semantic ARIA roles and labels,…

ecc13d293k
@affaan-m@affaan-mInstall Skill
compiler-commit

compiler-commit

Use when you want to verify compiler changes and commit with the correct convention. Runs tests, lint, and format, then commits…

react2d252k
@facebook@facebookInstall Skill

Questions about hook-authoring.

Which coding agents can use hook-authoring?
hook-authoring installs in Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode and Windsurf with the skills CLI, using each agent's flag shown on this page. Flowy's auto-invocation, which fires a skill when your prompt matches, runs in Claude Code only.