Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

hook-authoring

БесплатноЗапускает вложенные скриптыНе проверен

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

atholaот athola2 299 установок в других каталогах

Об этом скилле

Night Market Skill: ported from claude-night-market/abstract. For the full experience with agents, hooks, and commands, install the Claude Code plugin.

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, or 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

Every event, its matcher and its input fields, including the SessionStart input schema, are in modules/hook-types.md.

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

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 updatedInput (2.1.0 Fix)

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.

Failing Closed (2.1.295)

A command or HTTP hook that fails to start, times o

Полный SKILL.md на ClawHub

Установить hook-authoring в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл hook-authoring?

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

Как установить скилл hook-authoring?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл hook-authoring запускает скрипты?

Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.

Похожие скиллы

Сравнить hook-authoring с