skillZs
★ LIVE SKILL TAGS ★
>>> LIVE SKILLS INDEX <<<
* OPEN SOURCE *
NO LOGIN, NO TRACKING
※ REAL INSTALL DATA ※
← back to all skills
laurigates/claude-plugins85 installs

hooks-configuration

Claude Code hooks configuration and development. Use when the user mentions hooks, PreToolUse, PostToolUse, SessionStart, SubagentStart, PermissionRequest, or TaskCompleted.

How do I install this agent skill?

npx skills add https://github.com/laurigates/claude-plugins --skill hooks-configuration
view source ↗

Is this agent skill safe to install?

  • Gen Agent Trust Hubpass

    The skill is a reference guide for configuring Claude Code hooks, providing examples for shell commands, HTTP requests, and LLM-powered prompts. It includes security best practices like input validation and variable quoting. It identifies surfaces for command execution and prompt modification, which are inherent features of the hooks system. A static detection for destructive commands was found to be a false positive, as the patterns are part of examples for blocking such commands.

  • Socketpass

    No alerts

  • Snykwarn

    Risk: MEDIUM · 1 issue

  • Runlayerfail

    1/1 file flagged

What does this agent skill do?

Claude Code Hooks Configuration

Expert knowledge for configuring and developing Claude Code hooks to automate workflows and enforce best practices.

When to Use This Skill

Use this skill when...Use something else when...
Configuring hook lifecycle events (PreToolUse, PostToolUse, etc.)Writing general shell scripts unrelated to hooks
Blocking dangerous commands or enforcing patternsSetting up CI/CD pipelines (use CI tooling)
Auto-formatting files after editsConfiguring Claude Code settings unrelated to hooks
Injecting context at session or subagent startWriting standalone automation scripts
Setting up PermissionRequest auto-approve/denyManaging project permissions via settings.json directly
Developing prompt or agent hooks for judgment-based decisionsBuilding MCP servers or custom tool integrations

Core Concepts

What Are Hooks? Hooks are user-defined shell commands that execute at specific points in Claude Code's lifecycle. Unlike relying on Claude to "decide" to run something, hooks provide deterministic, guaranteed execution.

Why Use Hooks?

  • Enforce code formatting automatically
  • Block dangerous commands before execution
  • Inject context at session start
  • Log commands for audit trails
  • Send notifications when tasks complete

Hook Lifecycle Events

EventWhen It FiresKey Use Cases
SessionStartSession begins/resumesEnvironment setup, context loading
SessionEndSession terminatesCleanup, state persistence
UserPromptSubmitUser submits promptInput validation, context injection
UserPromptExpansionA typed skill/command/MCP prompt expands, before it reaches ClaudeBlock a command, inject skill-specific context, log invocations
PreToolUseBefore tool executionPermission control, blocking dangerous ops
PostToolUseAfter tool completesAuto-formatting, logging, validation
PostToolUseFailureAfter tool execution failsRetry decisions, error handling
PermissionRequestClaude requests permission for a toolAuto approve/deny without user prompt
PermissionDeniedAuto mode denies a tool callAudit denials, tell the model it may retry (retry: true)
PostToolBatchA batch of parallel tool calls has resolved, before the next model callInject context once per batch, stop the loop
StopMain agent finishes respondingNotifications, git reminders
SubagentStartSubagent (Task tool) is about to startInput modification, context injection
SubagentStopSubagent finishesPer-task completion evaluation
WorktreeCreateNew git worktree created via EnterWorktreeWorktree setup, dependency install
WorktreeRemoveWorktree removed after session exitsCleanup, uncommitted changes alert
TeammateIdleTeammate in agent team goes idleAssign additional tasks to teammate
TaskCompletedTask in shared task list marked completeValidation gates before task acceptance
PreCompactBefore context compactionTranscript backup
NotificationClaude sends notificationCustom alerts
ConfigChangeClaude Code settings change at runtimeAudit config changes, validation
PreModelSwitchBefore the session model changes (/model, fallbackModel, safety-classifier fallback)Audit or record the outgoing model
PostModelSwitchAfter the session model has changedRe-apply per-model settings, log the new model

Stop vs SubagentStop: Stop fires at the session level when the main agent finishes a response turn. SubagentStop fires when an individual subagent (spawned via the Task tool) completes. Use Stop for session-level notifications; use SubagentStop for per-task quality gates.

For full schemas, examples, and timeout recommendations for each event, see .claude/rules/hooks-reference.md.

Configuration

File Locations

Hooks are configured in settings files:

  • ~/.claude/settings.json - User-level (applies everywhere)
  • .claude/settings.json - Project-level (committed to repo)
  • .claude/settings.local.json - Local project (not committed)

Claude Code merges all matching hooks from all files.

Frontmatter Hooks (Skills and Commands)

Hooks can also be defined directly in skill and command frontmatter using the hooks field:

Example frontmatter: references/frontmatter-hooks.md.

Basic Structure

{
  "hooks": {
    "EventName": [
      {
        "matcher": "ToolPattern",
        "hooks": [
          {
            "type": "command",
            "command": "your-command-here",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

Matcher Patterns

  • Exact match: "Bash" - matches exactly "Bash" tool
  • Regex patterns: "Edit|Write" - matches either tool
  • Wildcards: "Notebook.*" - matches tools starting with "Notebook"
  • All tools: "*" - matches everything
  • MCP tools: "mcp__server__tool" - targets MCP server tools

Input/Output Schema Summary

Hooks receive JSON via stdin with common fields (session_id, transcript_path, cwd, permission_mode, hook_event_name). Event-specific fields include tool_name and tool_input for PreToolUse, plus tool_response for PostToolUse, and subagent_type/subagent_prompt for SubagentStart.

Exit codes: 0 = allow, 2 = block (stderr shown to Claude), other = non-blocking error.

JSON responses vary by event: PreToolUse uses hookSpecificOutput with permissionDecision; Stop/SubagentStop use decision/reason; SubagentStart uses updatedPrompt; SessionStart uses hookSpecificOutput with additionalContext.

For detailed hook schemas and examples, see REFERENCE.md.

Common Hook Patterns

Worked scripts (block dangerous commands, auto-format after edits, tool reminders, SessionStart context): references/hook-patterns.md.

For additional patterns (subagent injection, desktop notifications, audit logging, auto-approve, worktree setup, task gating), see REFERENCE.md.

Prompt-Based and Agent-Based Hooks

Four hook types: command (shell script, exit code), http (HTTPS endpoint), prompt (single-turn LLM call), and agent (multi-turn with tool access). Use command for deterministic rules; prompt/agent for judgment-based decisions. Add async: true for fire-and-forget; once: true to run only once per session.

Prompt and agent hooks work on PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest, Stop, SubagentStop, TaskCompleted, UserPromptSubmit. All other events support command hooks only.

For hook type details, CLAUDE_ENV_FILE, and configuration examples, see REFERENCE.md and .claude/rules/prompt-agent-hooks.md.

Handling Blocked Commands

When a PreToolUse hook blocks a command:

SituationAction
Hook suggests alternativeUse the suggested tool/approach
Alternative won't workAsk user to run command manually
User says "proceed"Still blocked - explain and provide command for manual execution

Critical: User permission does NOT bypass hooks. Retrying a blocked command will fail again.

When command is legitimately needed:

  1. Explain why the command is required
  2. Describe alternatives considered and why they won't work
  3. Provide exact command for user to run manually
  4. Let user decide

Timeout Guidelines

The default hook timeout is 600s (10 minutes) since Claude Code 2.1.50. Set explicit timeouts to document intent and prevent "Hook cancelled" errors:

Hook TypeRecommended TimeoutUse Case
SessionStart120–300sTests, linters, dependency checks
SessionEnd60–120sLogging, cleanup, state saving
Stop / SubagentStop30–60sGit status checks, quick validations
PreToolUse10–30sQuick validations
PostToolUse30–120sLogging, notifications
PermissionRequest5–15sKeep fast for good UX

For slow work, run it in a background subshell: references/hook-patterns.md.

Best Practices

AreaKey Points
ScriptRead stdin with cat; parse with jq; quote all vars; exit 2 to block, 0 to allow; stderr for messages; keep < 5s
Config$CLAUDE_PROJECT_DIR for portable paths; explicit timeouts; specific matchers over wildcards; test before enabling
SecurityValidate all inputs; use absolute paths; avoid .env / .git/ directly; review before deploy

Debugging

Hook cancelled, failing, or not firing: references/troubleshooting.md.

Add the canonical catalog link to the repository README so users can inspect current installs and available audits. The publishing guide covers the complete discovery path.

<a href="https://skillzs.dev/skills/laurigates/claude-plugins/hooks-configuration">View hooks-configuration on skillZs</a>