hook-authoring
БесплатноЗапускает вложенные скриптыНе проверенGuide creating Claude Code hooks with security-first design. Use for validation and enforcement.
Об этом скилле
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
additionalContextto 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 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 ig
Установить 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 запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic