MCPcopy
hub / github.com/disler/claude-code-hooks-mastery

github.com/disler/claude-code-hooks-mastery @main sqlite

repository ↗ · DeepWiki ↗
49 symbols 109 edges 14 files 15 documented · 31%
README

Claude Code Hooks Mastery

Claude Code Hooks - Quickly master how to use Claude Code hooks to add deterministic (or non-deterministic) control over Claude Code's behavior. Plus learn about Claude Code Sub-Agents, the powerful Meta-Agent, and Team-Based Validation with agent orchestration.

Claude Code Hooks

Table of Contents

Prerequisites

This requires: - Astral UV - Fast Python package installer and resolver - Claude Code - Anthropic's CLI for Claude AI

Optional Setup:

Optional: - ElevenLabs - Text-to-speech provider (with MCP server integration) - ElevenLabs MCP Server - MCP server for ElevenLabs - Firecrawl MCP Server - Web scraping and crawling MCP server (my favorite scraper) - OpenAI - Language model provider + Text-to-speech provider - Anthropic - Language model provider - Ollama - Local language model provider

Hook Lifecycle & Payloads

This demo captures all 13 Claude Code hook lifecycle events with their JSON payloads:

Hook Lifecycle Overview

flowchart TB
    subgraph SESSION["🟢 Session Lifecycle"]
        direction TB
        SETUP[["🔧 Setup

(init/maintenance)"]]
        START[["▶️ SessionStart

(startup/resume/clear)"]]
        END[["⏹️ SessionEnd

(exit/sigint/error)"]]
    end

    subgraph MAIN["🔄 Main Conversation Loop"]
        direction TB
        PROMPT[["📝 UserPromptSubmit"]]
        CLAUDE["Claude Processes"]

        subgraph TOOLS["🛠️ Tool Execution"]
            direction TB
            PRE[["🔒 PreToolUse"]]
            PERM[["❓ PermissionRequest"]]
            EXEC["Tool Executes"]
            POST[["✅ PostToolUse"]]
            FAIL[["❌ PostToolUseFailure"]]
        end

        subgraph SUBAGENT["🤖 Subagent Lifecycle"]
            direction TB
            SSTART[["🚀 SubagentStart"]]
            SWORK["Subagent Works"]
            SSTOP[["🏁 SubagentStop"]]
        end

        NOTIFY[["🔔 Notification

(Async)"]]
        STOP[["🛑 Stop"]]
    end

    subgraph COMPACT["🗜️ Maintenance"]
        PRECOMPACT[["📦 PreCompact"]]
    end

    SETUP --> START
    START --> PROMPT
    PROMPT --> CLAUDE
    CLAUDE --> PRE
    PRE --> PERM
    PERM --> EXEC
    EXEC --> POST
    EXEC -.-> FAIL
    CLAUDE -.-> SSTART
    SSTART --> SWORK
    SWORK --> SSTOP
    POST --> CLAUDE
    CLAUDE --> STOP
    CLAUDE -.-> NOTIFY
    STOP --> PROMPT
    STOP -.-> END
    PROMPT -.-> PRECOMPACT
    PRECOMPACT -.-> PROMPT

1. UserPromptSubmit Hook

Fires: Immediately when user submits a prompt (before Claude processes it)
Payload: prompt text, session_id, timestamp
Enhanced: Prompt validation, logging, context injection, security filtering

2. PreToolUse Hook

Fires: Before any tool execution
Payload: tool_name, tool_input parameters
Enhanced: Blocks dangerous commands (rm -rf, .env access)

3. PostToolUse Hook

Fires: After successful tool completion
Payload: tool_name, tool_input, tool_response with results

4. Notification Hook

Fires: When Claude Code sends notifications (waiting for input, etc.)
Payload: message content
Enhanced: TTS alerts - "Your agent needs your input" (30% chance includes name)

5. Stop Hook

Fires: When Claude Code finishes responding
Payload: stop_hook_active boolean flag
Enhanced: AI-generated completion messages with TTS playback (LLM priority: OpenAI > Anthropic > Ollama > random)

6. SubagentStop Hook

Fires: When Claude Code subagents (Task tools) finish responding
Payload: stop_hook_active boolean flag
Enhanced: TTS playback - "Subagent Complete"

7. PreCompact Hook

Fires: Before Claude Code performs a compaction operation
Payload: trigger ("manual" or "auto"), custom_instructions (for manual), session info
Enhanced: Transcript backup, verbose feedback for manual compaction

8. SessionStart Hook

Fires: When Claude Code starts a new session or resumes an existing one Payload: source ("startup", "resume", or "clear"), session info Enhanced: Development context loading (git status, recent issues, context files)

9. SessionEnd Hook

Fires: When Claude Code session ends (exit, sigint, or error) Payload: session_id, transcript_path, cwd, permission_mode, reason Enhanced: Session logging with optional cleanup tasks (removes temp files, stale logs)

10. PermissionRequest Hook

Fires: When user is shown a permission dialog Payload: tool_name, tool_input, tool_use_id, session info Enhanced: Permission auditing, auto-allow for read-only ops (Read, Glob, Grep, safe Bash)

11. PostToolUseFailure Hook

Fires: When a tool execution fails Payload: tool_name, tool_input, tool_use_id, error object Enhanced: Structured error logging with timestamps and full context

12. SubagentStart Hook

Fires: When a subagent (Task tool) spawns Payload: agent_id, agent_type, session info Enhanced: Subagent spawn logging with optional TTS announcement

13. Setup Hook

Fires: When Claude enters a repository (init) or periodically (maintenance) Payload: trigger ("init" or "maintenance"), session info Enhanced: Environment persistence via CLAUDE_ENV_FILE, context injection via additionalContext

What This Shows

  • Complete hook lifecycle coverage - All 13 hook events implemented and logging (11/13 validated via automated testing)
  • Prompt-level control - UserPromptSubmit validates and enhances prompts before Claude sees them
  • Intelligent TTS system - AI-generated audio feedback with voice priority (ElevenLabs > OpenAI > pyttsx3)
  • Security enhancements - Blocks dangerous commands and sensitive file access at multiple levels
  • Personalized experience - Uses engineer name from environment variables
  • Automatic logging - All hook events are logged as JSON to logs/ directory
  • Chat transcript extraction - PostToolUse hook converts JSONL transcripts to readable JSON format
  • Team-based validation - Builder/Validator agent pattern with code quality hooks

Warning: The chat.json file contains only the most recent Claude Code conversation. It does not preserve conversations from previous sessions - each new conversation is fully copied and overwrites the previous one. This is unlike the other logs which are appended to from every claude code session.

UV Single-File Scripts Architecture

This project leverages UV single-file scripts to keep hook logic cleanly separated from your main codebase. All hooks live in .claude/hooks/ as standalone Python scripts with embedded dependency declarations.

Benefits: - Isolation - Hook logic stays separate from your project dependencies - Portability - Each hook script declares its own dependencies inline - No Virtual Environment Management - UV handles dependencies automatically - Fast Execution - UV's dependency resolution is lightning-fast - Self-Contained - Each hook can be understood and modified independently

This approach ensures your hooks remain functional across different environments without polluting your main project's dependency tree.

Key Files

  • .claude/settings.json - Hook configuration with permissions
  • .claude/hooks/ - Python scripts using uv for each hook type
  • user_prompt_submit.py - Prompt validation, logging, and context injection
  • pre_tool_use.py - Security blocking and logging
  • post_tool_use.py - Logging and transcript conversion
  • post_tool_use_failure.py - Error logging with structured details
  • notification.py - Logging with optional TTS (--notify flag)
  • stop.py - AI-generated completion messages with TTS
  • subagent_stop.py - Simple "Subagent Complete" TTS
  • subagent_start.py - Subagent spawn logging with optional TTS
  • pre_compact.py - Transcript backup and compaction logging
  • session_start.py - Development context loading and session logging
  • session_end.py - Session cleanup and logging
  • permission_request.py - Permission auditing and auto-allow
  • setup.py - Repository initialization and maintenance
  • validators/ - Code quality validation hooks
    • ruff_validator.py - Python linting via Ruff (PostToolUse)
    • ty_validator.py - Python type checking (PostToolUse)
  • utils/ - Intelligent TTS and LLM utility scripts
    • tts/ - Text-to-speech providers (ElevenLabs, OpenAI, pyttsx3)
    • tts_queue.py - Queue-based TTS management (prevents overlapping audio)
    • llm/ - Language model integrations (OpenAI, Anthropic, Ollama)
    • task_summarizer.py - LLM-powered task completion summaries
  • .claude/status_lines/ - Real-time terminal status displays
  • status_line.py - Basic MVP with git info
  • status_line_v2.py - Smart prompts with color coding
  • status_line_v3.py - Agent sessions with history
  • status_line_v4.py - Extended metadata support
  • status_line_v5.py - Cost tracking with line changes
  • status_line_v6.py - Context window usage bar
  • status_line_v7.py - Session duration timer
  • status_line_v8.py - Token usage with cache stats
  • status_line_v9.py - Minimal powerline style
  • .claude/output-styles/ - Response formatting configurations
  • genui.md - Generates beautiful HTML with embedded styling
  • table-based.md - Organizes information in markdown tables
  • yaml-structured.md - YAML configuration format
  • bullet-points.md - Clean nested lists
  • ultra-concise.md - Minimal words, maximum speed
  • html-structured.md - Semantic HTML5
  • markdown-focused.md - Rich markdown features
  • tts-summary.md - Audio feedback via TTS
  • .claude/commands/ - Custom slash commands
  • prime.md - Project analysis and understanding
  • plan_w_team.md - Team-based build/validate workflow
  • crypto_research.md - Cryptocurrency research workflows
  • cook.md - Advanced task execution
  • update_status_line.md - Dynamic status updates
  • .claude/agents/ - Sub-agent configurations
  • crypto/ - Cryptocurrency analysis agents
  • team/ - Team-based workflow agents
    • builder.md - Implementation agent (all tools)
    • validator.md - Read-only validation agent
  • hello-world-agent.md - Simple greeting example
  • llm-ai-agents-and-eng-research.md - AI research specialist
  • meta-agent.md - Agent that creates other agents
  • work-completion-summary.md - Audio summary generator
  • logs/ - JSON logs of all hook executions
  • user_prompt_submit.json - User prompt submissions with validation
  • pre_tool_use.json - Tool use events with security blocking
  • post_tool_use.json - Tool completion events
  • post_tool_use_failure.json - Tool failure events with error details
  • notification.json - Notification events
  • stop.json - Stop events with completion messages
  • subagent_stop.json - Subagent completion events
  • subagent_start.json - Subagent spawn events
  • pre_compact.json - Pre-compaction events with trigger type
  • session_start.json - Session start events with source type
  • session_end.json - Session end events with reason
  • permission_request.json - Permission request audit log
  • setup.json - Setup events with trigger type
  • chat.json - Readable conversation transcript (generated by --chat flag)
  • ai_docs/ - Documentation resources
  • cc_hooks_docs.md - Complete hooks documentation from Anthropic
  • claude_code_status_lines_docs.md - Status line input schema and configuration
  • user_prompt_submit_hook.md - Comprehensive UserPromptSubmit hook documentation
  • uv-single-file-scripts.md - UV script architecture documentation
  • anthropic_custom_slash_commands.md - Slash commands documentation
  • anthropic_docs_subagents.md - Sub-agents documentation
  • ruff.toml - Ruff linter configuration for Python code quality
  • ty.toml - Type checker configuration for Python type validation

Hooks provide deterministic control over Claude Code behavior without relying on LLM decisions.

Features Demonstrated

  • Prompt validation and security filtering
  • Context injection for enhanced AI responses
  • Command logging and auditing
  • Automatic transcript conversion
  • Permission-based tool access control
  • Error handling in hook execution

Run any Claude Code command to see hooks in action via the logs/ files.

Hook Error Codes & Flow Control

Claude Code hooks provide powerful mechanisms to control execution flow and provide feedback through exit codes and structured JSON output.

Exit Code Behavior

Hooks communicate status and control flow through exit codes:

| Exit Code | Behavior | Description

Extension points exported contracts — how you extend this code

TaskRow (Interface)
* Database row type (raw from SQLite)
apps/task-manager/src/db/repository.ts
Task (Interface)
(no doc)
apps/task-manager/src/types.ts
TaskStats (Interface)
(no doc)
apps/task-manager/src/types.ts
AddCommandArgs (Interface)
(no doc)
apps/task-manager/src/types.ts
ListCommandArgs (Interface)
(no doc)
apps/task-manager/src/types.ts

Core symbols most depended-on inside this repo

formatError
called by 12
apps/task-manager/src/utils/formatter.ts
padRight
called by 8
apps/task-manager/src/utils/formatter.ts
close
called by 6
apps/task-manager/src/db/repository.ts
findById
called by 5
apps/task-manager/src/db/repository.ts
formatSuccess
called by 3
apps/task-manager/src/utils/formatter.ts
formatInfo
called by 3
apps/task-manager/src/utils/formatter.ts
isOverdue
called by 2
apps/task-manager/src/utils/formatter.ts
formatTask
called by 2
apps/task-manager/src/utils/formatter.ts

Shape

Function 29
Interface 9
Method 8
Class 2
Enum 1

Languages

TypeScript98%
Python2%

Modules by API surface

apps/task-manager/src/db/repository.ts13 symbols
apps/task-manager/src/utils/formatter.ts11 symbols
apps/task-manager/src/types.ts9 symbols
apps/task-manager/src/utils/validation.ts5 symbols
apps/task-manager/src/db/database.ts3 symbols
apps/task-manager/src/commands/list.ts2 symbols
apps/task-manager/src/db/migrations.ts1 symbols
apps/task-manager/src/commands/stats.ts1 symbols
apps/task-manager/src/commands/delete.ts1 symbols
apps/task-manager/src/commands/complete.ts1 symbols
apps/task-manager/src/commands/add.ts1 symbols
apps/hello.py1 symbols

Dependencies from manifests, versioned

@types/bun1.1.6 · 1×
@types/yargs17.0.32 · 1×
chalk5.3.0 · 1×
yargs17.7.2 · 1×

For agents

$ claude mcp add claude-code-hooks-mastery \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact