
sc-hooks
SimpleClaude hooks for auto-formatting, lint checks, and tool monitoring
- version
- 8.2.1
- GitHub stars
- 116
Install
/plugin install sc-hooks@simpleclaudeRun it inside Claude Code after adding the marketplace with /plugin marketplace add kylesnowschwartz/SimpleClaude.
Contents
Discovered from sourceAgents 3
sc-hooks
SimpleClaude hooks for auto-formatting, lint checks, and tool monitoring.
What it does
| Event | Handler | Behavior |
|---|---|---|
Stop | AutoFormatHandler | At the end of each turn, formats every changed or untracked file in the git working tree under the session directory, including edits Claude did not make (your own edits, other sessions). Runs before lint. Formats nothing outside a git repository. Never blocks. |
Stop | LintCheckHandler | Runs linters/type-checkers on the same set of changed and untracked git files and reports errors back so Claude can fix them. Checks nothing outside a git repository. Has a retry guard to avoid infinite stop loops. |
PreToolUse (WebFetch) | GitHubUrlHandler | When Claude WebFetches a github.com repo page, injects a soft hint (via additionalContext, no block) suggesting the equivalent gh CLI commands. The fetch still proceeds, so reserved site routes (features, marketplace, โฆ) and raw URLs are never stranded. |
Environment Variables
| Variable | Effect | Notes |
|---|---|---|
RUBY_CLAUDE_HOOKS_DEBUG | Print full error backtraces from hook entrypoints when a hook raises. | Debugging aid, not a feature flag. Any set value enables it. |
Transient (one Claude session):
RUBY_CLAUDE_HOOKS_DEBUG=1 claude
Persistent (every shell):
# In ~/.zshrc, ~/.bashrc, or your direnv .envrc
export RUBY_CLAUDE_HOOKS_DEBUG=1
Changelog
All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
[1.1.1] - 2026-01-24
Changed
- Applied RuboCop autocorrections across entire codebase
- Added
.rubocop.ymlwith sane defaults (disabled useless metrics cops) - Fixed line length violations in gemspec and example code
- Renamed
get_transcript_sizetotranscript_size(accessor naming convention)
Notes
- Style-only release, no functional changes
- All 48 Ruby files now pass RuboCop with zero offenses
[1.1.0] - 2026-01-04
Added
-
New PermissionRequest hook type - Handles permission request events from Claude Code
- New
ClaudeHooks::PermissionRequesthook class - New
ClaudeHooks::Output::PermissionRequestoutput class - Methods:
allow_permission!,deny_permission!,update_input_and_allow! - Semantic helpers:
allowed?,denied?,input_updated? - Exit code 0 with stdout (JSON API pattern)
- Merge logic: deny > allow (most restrictive wins)
- New
-
permission_mode field - Added to all hooks as common input field
- Values:
default,plan,acceptEdits,dontAsk,bypassPermissions - Accessible via
permission_modemethod on all hook instances - Defaults to
'default'when not provided - Supports both snake_case (
permission_mode) and camelCase (permissionMode)
- Values:
-
tool_use_id field - Added to PreToolUse and PostToolUse hooks
- Unique identifier for each tool use event (e.g.,
"toolu_01ABC123...") - Accessible via
tool_use_idmethod - Supports both snake_case and camelCase input
- Unique identifier for each tool use event (e.g.,
-
notification_type field - Added to Notification hook
- Values:
permission_prompt,idle_prompt,auth_success,elicitation_dialog - Accessible via
notification_typemethod - Enables filtering notifications by type using matchers
- Values:
-
updatedInput support - Added to PreToolUse hook
- New method:
update_tool_input!(hash)for modifying tool input before execution - Output helpers:
input_updated?,updated_input - Automatically sets
permissionDecisionto'allow' - Merge logic: last updatedInput wins (most recent transformation)
- Works seamlessly with existing approval/denial methods
- New method:
Changed
- Updated all hook classes to include new input fields where applicable
- Enhanced PreToolUse output class with updatedInput merge logic
- Updated main module to require PermissionRequest classes
- Updated output factory to support PermissionRequest hook type
Notes
- All changes are backward compatible - Existing hooks continue to work without modification
- New fields are optional with sensible defaults
- No breaking changes to existing APIs
- Aligns with Anthropic's Claude Code Hooks documentation as of January 2026
- Total hook types: 10 (added PermissionRequest)
[1.0.2] - 2026-01-04
Fixed
- JSON API contract compliance - All decision-making hooks now correctly use exit 0 + stdout for the advanced JSON API
Stop- Changed from exit 2 to exit 0 when usingdecision: "block"SubagentStop- Inherits fix from StopPostToolUse- Changed from exit 2 to exit 0 when usingdecision: "block"UserPromptSubmit- Changed from exit 2 to exit 0 when usingdecision: "block"PreToolUse- Changed from exit 1/2 to exit 0 for allpermissionDecisionvalues
Notes
- Per Claude Code docs: "JSON output is only processed when the hook exits with code 0"
- Previous behavior caused JSON responses to be ignored, falling back to stderr text
- Reference: https://github.com/anthropics/claude-code/issues/10875
[1.0.1] - 2025-10-13
Documentation
- Added comprehensive plugin hooks documentation - Full guide on using the Claude Hooks DSL with Claude Code plugins
- New "Plugin Hooks Support" section in README with working examples
- Created
example_dotclaude/plugins/README.mdwith complete plugin development guide - Example plugin formatter implementation using the DSL
- Environment variables documentation for plugin development
- Best practices and testing instructions for plugin hooks
- Updated SessionStart hook documentation - Added the new
compactmatcher introduced in official Claude Hooks documentation- Updated
docs/API/SESSION_START.mdto include'compact'as a valid source value - Updated SessionStart hook type description to mention compact functionality
- Updated
- Synchronized with official documentation - All documentation now matches the official Claude Hooks reference as of 2025-10-13
- Plugin hooks feature (Issue #9)
- SessionStart
compactmatcher (Issue #2)
Notes
- No code changes required - the implementation already supports all documented features
- The DSL's dynamic implementation handles the new
compactsource automatically - Plugin environment variables (
CLAUDE_PLUGIN_ROOT) work seamlessly with existing configuration system
[1.0.0] - 2025-08-27
[!WARNING] These changes are not backward compatible (hence the version bump to 1.0.0), the API has changed too much.
Follow the migration guide to migrate to the new API.
Changed
Revamped documentation
- New documentation structure:
- API Reference: Comprehensive API reference for all hook types
- Common Helpers: Shared helpers for all hook types
- Output Helpers: Helpers for working with the output state
- Hook Exit Codes: Exit codes for each hook type
- Hook Types: Overview of all hook types and their purpose
Added support for SessionEnd
Handles the new SessionEnd hook type.
Handles new field for PostToolUse
additionalContext field is now available in the hookSpecificOutput field.
Output Objects System
New output handling with intelligent exit code management.
- Automatic Exit Code Selection: Output objects automatically choose the correct exit code (0, 1, 2) based on hook type and the state of the hook
-
- Enhanced Base Class: All hook instances now automatically get an
@outputattribute with aoutputaccessor. They can still access rawoutput_data
- Enhanced Base Class: All hook instances now automatically get an
- Helper Methods: Access to hook-specific data via methods like
output.blocked?,output.allowed?,output.should_ask_permission? - Automatic Stream Selection: Output objects automatically route to
STDOUTorSTDERRbased on exit code and hook type - One-Line Output Execution: New
output_and_exitmethod handles JSON serialization, stream selection, and exit code in one call - Object-Based Merging: New
ClaudeHooks::Output::*.merge()methods for cleaner multi-hook merging - Comprehensive Output Classes: Full coverage for all 8 hook types:
ClaudeHooks::Output::UserPromptSubmit- Providesblocked?,reason,additional_contextClaudeHooks::Output::PreToolUse- Providesallowed?,denied?,should_ask_permission?ClaudeHooks::Output::PostToolUse- Providesblocked?,reasonClaudeHooks::Output::Stop- Providesshould_continue?,continue_instructions(inverted logic)ClaudeHooks::Output::SubagentStop- Inherits Stop behaviorClaudeHooks::Output::Notification- Basic output handlingClaudeHooks::Output::SessionStart- Providesadditional_contextClaudeHooks::Output::PreCompact- Basic output handling
Migration Guide
Before (Old Pattern):
#!/usr/bin/env ruby
require 'claude_hooks'
begin
input_data = JSON.parse(STDIN.read)
hook = MyHook.new(input_data)
result = hook.call
# Manual stream and exit code selection
if result['continue'] != false
if result.dig('hookSpecificOutput', 'permissionDecision') == 'deny'
STDERR.puts hook.stringify_output
exit 1
elsif result.dig('hookSpecificOutput', 'permissionDecision') == 'ask'
STDERR.puts hook.stringify_output
exit 2
else
puts hook.stringify_output
exit 0
end
else # Continue == false
STDERR.puts hook.stringify_output
exit 2
end
rescue StandardError => e
# Error handling...
end
After (New Pattern):
#!/usr/bin/env ruby
require 'claude_hooks'
# Just 3 lines for most cases!
begin
input_data = JSON.parse(STDIN.read)
hook = MyHook.new(input_data)
hook.call
# Handles everything automatically!
hook.output_and_exit
rescue StandardError => e
# Error handling...
end
[0.2.1] - 2025-08-21
Fixed
- Fixed name of environment variable for the merge strategy
[0.2.0] - 2025-08-21
Added
- Dual Configuration System: Support for both home-level (
$HOME/.claude) and project-level ($CLAUDE_PROJECT_DIR/.claude) configurations - Configuration Merging: Intelligent merging of home and project configs with configurable precedence
- New environment variable
RUBY_CLAUDE_HOOKS_CONFIG_MERGE_STRATEGYto control merge behavior ("project" or "home") - New directory access methods:
home_claude_dir,project_claude_dir - New path utility methods:
home_path_for(path),project_path_for(path) - Enhanced
path_for(path, base_dir=nil)method with optional base directory parameter - Comprehensive test suite for configuration functionality (
test/directory) - Configuration validation and edge case handling for missing
CLAUDE_PROJECT_DIR
Changed
- Logs Location: Logs now always go to
$HOME/.claude/{logDirectory}regardless of active configuration - Configuration loading now supports dual config file locations with intelligent merging
- Enhanced documentation with comprehensive dual configuration examples
- Updated API reference with new directory and path methods
Deprecated
base_dirmethod (still functional for backward compatibility)RUBY_CLAUDE_HOOKS_BASE_DIRenvironment variable (still supported as fallback)
Fixed
- Graceful handling of undefined
CLAUDE_PROJECT_DIRenvironment variable - Proper path resolution when project directory is not available
- Backward compatibility maintained for all existing hook scripts
Migration Notes
- Existing configurations continue to work without changes
- New projects can leverage dual configuration system
base_dirand legacypath_formethods remain functional- Environment variables maintain same precedence over config files
[0.1.0] - 2025-08-17
Added
- Initial release of claude_hooks gem
- Ruby DSL framework for creating Claude Code hooks
- Support for all 8 hook types: UserPromptSubmit, PreToolUse, PostToolUse, Notification, Stop, SubagentStop, PreCompact, SessionStart
- Environment-based configuration with
RUBY_CLAUDE_HOOKS_prefix - Session-based logging system
- Intelligent output merging for multiple hook scripts
- Comprehensive API for each hook type
- Examples directory with working hook scripts
- Zero-configuration setup with smart defaults
Changed
- Migrated from local file-based configuration to gem-based distribution
- Updated all hook classes to use
ClaudeHooks::namespace - Replaced
ClaudeConfig::ConfigLoaderwithClaudeHooks::Configuration - Moved
SessionLoggertoClaudeHooks::Logger
Migration Notes
- Update
require_relativestatements torequire 'claude_hooks' - Change hook class inheritance from
HookTypes::BasetoClaudeHooks::Base - Replace specific hook classes:
UserPromptSubmitHookโClaudeHooks::UserPromptSubmit, etc. - Set environment variables with
RUBY_CLAUDE_HOOKS_prefix instead of relying on config file
Ruby DSL for Claude Code hooks
[!NOTE] This is a fork of gabriel-dehan/claude_hooks with fixes for Claude Code's JSON API contract. See CHANGELOG for details.
[!IMPORTANT] v1.0.0 just released and is introducing breaking changes. Please read the CHANGELOG for more information.
A Ruby DSL (Domain Specific Language) for creating Claude Code hooks. This will hopefully make creating and configuring new hooks way easier.
Why use this instead of writing bash, or simple ruby scripts?
You might also be interested in my other project, a Claude Code statusline that shows your Claude usage in realtime, inside Claude Code โจ.
๐ Table of Contents
- Ruby DSL for Claude Code hooks
- ๐ Table of Contents
- ๐ Quick Start
- ๐ฆ Installation
- ๐๏ธ Architecture
- ๐ช Hook Types
- ๐ Claude Hook Flow
- ๐ API Reference
- ๐ Example: Tool usage monitor
- ๐ Hook Output
- ๐ Plugin Hooks Support
- ๐จ Advices
- โ ๏ธ Troubleshooting
- ๐งช CLI Debugging
- ๐ Debugging
- ๐งช Development & Contributing
๐ Quick Start
[!TIP] Examples are available in
example_dotclaude/hooks/. The GithubGuard in particular is a good example of a solid hook. You can also check SimpleClaude's hooks for some great examples
Here's how to create a simple hook:
- Install the gem:
gem install claude_hooks
- Create a simple hook script
#!/usr/bin/env ruby
require 'json'
require 'claude_hooks'
# Inherit from the right hook type class to get access to helper methods
class AddContextAfterPrompt < ClaudeHooks::UserPromptSubmit
def call
log "User asked: #{prompt}"
add_context!("Remember to be extra helpful!")
output
end
end
# Run the hook
if __FILE__ == $0
# Read Claude Code's input data from STDIN
input_data = JSON.parse(STDIN.read)
hook = AddContextAfterPrompt.new(input_data)
hook.call
# Handles output and exit code depending on the hook state.
# In this case, uses exit code 0 (success) and prints output to STDOUT
hook.output_and_exit
end
- โ ๏ธ Make it executable
chmod +x add_context_after_prompt.rb
# Test it
echo '{"session_id":"test","prompt":"Hello!"}' | ./add_context_after_prompt.rb
- Register it in your
.claude/settings.json
{
"hooks": {
"UserPromptSubmit": [{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "path/to/your/hook.rb"
}
]
}]
}
}
That's it! Your hook will now add context to every user prompt. ๐
[!TIP] This was a very simple example but we recommend using the entrypoints/handlers architecture described below to create more complex hook systems.
๐ฆ Installation
Install it globally (simpler):
$ gem install claude_hooks
Using a Gemfile
[!WARNING] Unless you use
bundle execin the command in your.claude/settings.json, Claude Code will use the system-installed gem, not the bundled version.
Add it to your Gemfile (you can add a Gemfile in your .claude directory if needed):
# .claude/Gemfile
source 'https://rubygems.org'
gem 'claude_hooks'
And then run:
$ bundle install
๐ง Configuration
Claude Hooks supports both home-level ($HOME/.claude) and project-level ($CLAUDE_PROJECT_DIR/.claude) directories. Claude Hooks specific config files (config/config.json) found in either directory will be merged together.
| Directory | Description | Purpose |
|---|---|---|
$HOME/.claude | Home Claude directory | Global user settings and logs |
$CLAUDE_PROJECT_DIR/.claude | Project Claude directory | Project-specific settings |
[!NOTE] Logs always go to
$HOME/.claude/{logDirectory}
Environment Variables
You can configure Claude Hooks through environment variables with the RUBY_CLAUDE_HOOKS_ prefix:
# Existing configuration options
export RUBY_CLAUDE_HOOKS_LOG_DIR="logs" # Default: logs (relative to $HOME/.claude)
export RUBY_CLAUDE_HOOKS_CONFIG_MERGE_STRATEGY="project" # Config merge strategy: "project" or "home", default: "project"
export RUBY_CLAUDE_HOOKS_BASE_DIR="~/.claude" # DEPRECATED: fallback base directory
# Any variable prefixed with RUBY_CLAUDE_HOOKS_
# will also be available through the config object
export RUBY_CLAUDE_HOOKS_API_KEY="your-api-key"
export RUBY_CLAUDE_HOOKS_DEBUG_MODE="true"
export RUBY_CLAUDE_HOOKS_USER_NAME="Gabriel"
Configuration Files
You can also use configuration files in any of the two locations:
Home config ($HOME/.claude/config/config.json):
{
// Existing configuration option
"logDirectory": "logs",
// Custom configuration options
"apiKey": "your-global-api-key",
"userName": "Gabriel"
}
Project config ($CLAUDE_PROJECT_DIR/.claude/config/config.json):
{
// Custom configuration option
"projectSpecificConfig": "someValue",
}
Configuration Merging
When both config files exist, they will be merged with configurable precedence:
- Default (
project): Project config values override home config values - Home precedence (
home): Home config values override project config values
Set merge strategy: export RUBY_CLAUDE_HOOKS_CONFIG_MERGE_STRATEGY="home" | "project" (default: "project")
[!WARNING] Environment Variables > Merged Config Files
Accessing Configuration Variables
You can access any configuration value in your handlers:
class MyHandler < ClaudeHooks::UserPromptSubmit
def call
# Access directory paths
log "Home Claude dir: #{home_claude_dir}"
log "Project Claude dir: #{project_claude_dir}" # nil if CLAUDE_PROJECT_DIR not set
log "Base dir (deprecated): #{base_dir}"
log "Logs dir: #{config.logs_directory}"
# Path utilities
log "Home config path: #{home_path_for('config')}"
log "Project hooks path: #{project_path_for('hooks')}" # nil if no project dir
# Access custom config via method calls
log "API Key: #{config.api_key}"
log "Debug mode: #{config.debug_mode}"
log "User: #{config.user_name}"
# Or use get_config_value for more control
user_name = config.get_config_value('USER_NAME', 'userName')
log "Username: #{user_name}"
output
end
end
๐๏ธ Architecture
Core Components
ClaudeHooks::Base- Base class with common functionality (logging, config, validation)- Hook Handler Classes - Self-contained classes (
ClaudeHooks::UserPromptSubmit,ClaudeHooks::PreToolUse, etc.) - Output Classes -
ClaudeHooks::Output::UserPromptSubmit, etc... are output objects that handle intelligent merging of multiple outputs, as well as using the right exit codes and outputting to the proper stream (STDINorSTDERR) depending on the the hook state. - Configuration - Shared configuration management via
ClaudeHooks::Configuration - Logger - Dedicated logging class with multiline block support
Recommended structure for your .claude/hooks/ directory
.claude/hooks/
โโโ entrypoints/ # Main entry points
โย ย โโโ notification.rb
โย ย โโโ pre_tool_use.rb
โย ย โโโ post_tool_use.rb
โย ย โโโ pre_compact.rb
โย ย โโโ session_start.rb
โย ย โโโ stop.rb
โย ย โโโ subagent_stop.rb
|
โโโ handlers/ # Hook handlers for specific hook type
โโโ user_prompt_submit/
โ โโโ append_rules.rb
โ โโโ log_user_prompt.rb
โโโ pre_tool_use/
โ โโโ github_guard.rb
โ โโโ tool_monitor.rb
โโโ ...
๐ช Hook Types
The framework supports the following hook types:
| Hook Type | Class | Description |
|---|---|---|
| SessionStart | ClaudeHooks::SessionStart | Hooks that run when Claude Code starts a new session, resumes, or compacts |
| UserPromptSubmit | ClaudeHooks::UserPromptSubmit | Hooks that run before the user's prompt is processed |
| Notification | ClaudeHooks::Notification | Hooks that run when Claude Code sends notifications |
| PreToolUse | ClaudeHooks::PreToolUse | Hooks that run before a tool is used |
| PermissionRequest | ClaudeHooks::PermissionRequest | Hooks that run when Claude requests permission |
| PostToolUse | ClaudeHooks::PostToolUse | Hooks that run after a tool is used |
| Stop | ClaudeHooks::Stop | Hooks that run when Claude Code finishes responding |
| SubagentStop | ClaudeHooks::SubagentStop | Hooks that run when subagent tasks complete |
| SessionEnd | ClaudeHooks::SessionEnd | Hooks that run when Claude Code sessions end |
| PreCompact | ClaudeHooks::PreCompact | Hooks that run before transcript compaction |
๐ Claude Hook Flow
A very simplified view of how a hook works in Claude Code
Claude Code hooks in essence work in a very simple way:
- Claude Code passes data to the hook script through
STDIN - The hook uses the data to do its thing
- The hook outputs data to
STDOUTorSTDERRand thenexits with the proper code:exit 0for successexit 1for a non-blocking errorexit 2for a blocking error (prevent Claude from continuing)
graph LR
A[Hook triggers] --> B[JSON from STDIN] --> C[Hook does its thing] --> D[JSON to STDOUT or STDERR<br />Exit Code] --> E[Yields back to Claude Code] --> A
The main issue is that there are many different types of hooks and they each have different expectations regarding the data outputted to STDIN or STDERR and Claude Code will react differently for each specific exit code used depending on the hook type.
๐ Proposal: a more robust Claude Hook execution flow
- An entrypoint for a hook is set in
~/.claude/settings.json - Claude Code calls the entrypoint script (e.g.,
hooks/entrypoints/pre_tool_use.rb) - The entrypoint script reads STDIN and coordinates multiple hook handlers
- Each hook handler executes and returns its output data
- The entrypoint script combines/processes outputs from multiple hook handlers
- And then returns final response to Claude Code with the correct exit code
graph TD
A[๐ง Hook Configuration<br/>settings.json] --> B
B[๐ค Claude Code<br/><em>User submits prompt</em>] --> C[๐ Entrypoint<br />entrypoints/user_prompt_submit.rb]
C --> D[๐ Entrypoint<br />Parses JSON from STDIN]
D --> E[๐ Entrypoint<br />Calls hook handlers]
E --> F[๐ Handler<br />AppendContextRules.call<br/><em>Returns output</em>]
E --> G[๐ Handler<br />PromptGuard.call<br/><em>Returns output</em>]
F --> J[๐ Entrypoint<br />Calls _ClaudeHooks::Output::UserPromptSubmit.merge_ to ๐ merge outputs]
G --> J
J --> K[๐ Entrypoint<br />- Writes output to STDOUT or STDERR<br />- Uses correct exit code]
K --> L[๐ค Yields back to Claude Code]
L --> B
Basic Hook Handler Structure
#!/usr/bin/env ruby
require 'claude_hooks'
class AddContextAfterPrompt < ClaudeHooks::UserPromptSubmit
def call
# Access input data
log do
"--- INPUT DATA ---"
"session_id: #{session_id}"
"cwd: #{cwd}"
"hook_event_name: #{hook_event_name}"
"prompt: #{current_prompt}"
"---"
end
log "Full conversation transcript: #{read_transcript}"
# Use a Hook state method to modify what's sent back to Claude Code
add_additional_context!("Some custom context")
# Control execution, for instance: block the prompt
if current_prompt.include?("bad word")
block_prompt!("Hmm no no no!")
log "Prompt blocked: #{current_prompt} because of bad word"
end
# Return output if you need it
output
end
end
# Use your handler (usually from an entrypoint file, but this is an example)
if __FILE__ == $0
# Read Claude Code's input data from STDIN
input_data = JSON.parse(STDIN.read)
hook = AddContextAfterPrompt.new(input_data)
# Call the hook
hook.call
# Uses exit code 0 (success) and outputs to STDIN if the prompt wasn't blocked
# Uses exit code 2 (blocking error) and outputs to STDERR if the prompt was blocked
hook.output_and_exit
end
๐ API Reference
The goal of those APIs is to simplify reading from STDIN and writing to STDOUT or STDERR as well as exiting with the right exit codes: the way Claude Code expects you to.
Each hook provides the following capabilities:
| Category | Description |
|---|---|
| Configuration & Utility | Access config, logging, and file path helpers |
| Input Helpers | Access data parsed from STDIN (session_id, transcript_path, etc.) |
| Hook State Helpers | Modify the hook's internal state (adding additional context, blocking a tool call, etc...) before yielding back to Claude Code |
| Output Helpers | Access output data, merge results, and yield back to Claude with the proper exit codes |
Input Fields
The framework supports all existing hook types with their respective input fields:
| Hook Type | Input Fields |
|---|---|
| Common | session_id, transcript_path, cwd, hook_event_name, permission_mode |
| UserPromptSubmit | prompt |
| PreToolUse | tool_name, tool_input, tool_use_id |
| PermissionRequest | tool_name, tool_input, tool_use_id |
| PostToolUse | tool_name, tool_input, tool_response, tool_use_id |
| Notification | message, notification_type |
| Stop | stop_hook_active |
| SubagentStop | stop_hook_active |
| PreCompact | trigger, custom_instructions |
| SessionStart | source |
| SessionEnd | reason |
Hooks API
All hook types inherit from ClaudeHooks::Base and share a common API, as well as hook specific APIs.
- ๐ Common API Methods
- ๐ Notification Hooks
- ๐ Session Start Hooks
- ๐๏ธ User Prompt Submit Hooks
- ๐ ๏ธ Pre-Tool Use Hooks
- ๐ Permission Request Hooks
- ๐ง Post-Tool Use Hooks
- ๐ Pre-Compact Hooks
- โน๏ธ Stop Hooks
- โน๏ธ Subagent Stop Hooks
- ๐ Session End Hooks
๐ Logging
ClaudeHooks::Base provides a session logger to all its subclasses that you can use to write logs to session-specific files.
log "Simple message"
log "Error occurred", level: :error
log "Warning about something", level: :warn
log <<~TEXT
Configuration loaded successfully
Database connection established
System ready
TEXT
You can also use the logger from an entrypoint script:
require 'claude_hooks'
input_data = JSON.parse(STDIN.read)
logger = ClaudeHooks::Logger.new(input_data["session_id"], 'entrypoint')
logger.log "Simple message"
Log File Location
Logs are written to session-specific files in the configured log directory:
- Defaults to:
~/.claude/logs/hooks/session-{session_id}.log - Configurable path: Set via
config.jsonโlogDirectoryor viaRUBY_CLAUDE_HOOKS_LOG_DIRenvironment variable
Log Output Format
[2025-08-16 03:45:28] [INFO] [MyHookHandler] Starting execution
[2025-08-16 03:45:28] [ERROR] [MyHookHandler] Connection timeout
...
๐ Example: Tool usage monitor
Let's create a hook that will monitor tool usage and ask for permission before using dangerous tools.
First, register an entrypoint in ~/.claude/settings.json:
"hooks": {
"PreToolUse": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/entrypoints/pre_tool_use.rb"
}
]
}
],
}
Then, create your main entrypoint script and don't forget to make it executable:
touch ~/.claude/hooks/entrypoints/pre_tool_use.rb
chmod +x ~/.claude/hooks/entrypoints/pre_tool_use.rb
#!/usr/bin/env ruby
require 'json'
require_relative '../handlers/pre_tool_use/tool_monitor'
begin
# Read input from stdin
input_data = JSON.parse(STDIN.read)
tool_monitor = ToolMonitor.new(input_data)
tool_monitor.call
# You could also call any other handler here and then merge the outputs
tool_monitor.output_and_exit
rescue StandardError => e
STDERR.puts JSON.generate({
continue: false,
stopReason: "Hook execution error: #{e.message}",
suppressOutput: false
})
# Non-blocking error
exit 1
end
Finally, create the handler that will be used to monitor tool usage.
touch ~/.claude/hooks/handlers/pre_tool_use/tool_monitor.rb
#!/usr/bin/env ruby
require 'claude_hooks'
class ToolMonitor < ClaudeHooks::PreToolUse
DANGEROUS_TOOLS = %w[curl wget rm].freeze
def call
log "Monitoring tool usage: #{tool_name}"
if DANGEROUS_TOOLS.include?(tool_name)
log "Dangerous tool detected: #{tool_name}", level: :warn
# Use one of the ClaudeHooks::PreToolUse methods to modify the hook state and block the tool
ask_for_permission!("The tool '#{tool_name}' can impact your system. Allow?")
else
# Use one of the ClaudeHooks::PreToolUse methods to modify the hook state and allow the tool
approve_tool!("Safe tool usage")
end
# Accessor provided by ClaudeHooks::PreToolUse
output
end
end
๐ Hook Output
Hooks provide access to their output (which acts as the "state" of a hook) through the output method.
This method will return an output object based on the hook's type class (e.g: ClaudeHooks::Output::UserPromptSubmit) that provides helper methods:
- to access output data
- for merging multiple outputs
- for sending the right exit codes and output data back to Claude Code through the proper stream.
[!TIP] You can also always access the raw output data hash instead of the output object using
hook.output_data.
๐ Hook Output Merging
Often, you will want to call multiple hooks from a same entrypoint.
Each hook type's output provides a merge method that will try to intelligently merge multiple hook results.
Merged outputs always inherit the most restrictive behavior.
require 'json'
require_relative '../handlers/user_prompt_submit/hook1'
require_relative '../handlers/user_prompt_submit/hook2'
require_relative '../handlers/user_prompt_submit/hook3'
begin
# Read input from stdin
input_data = JSON.parse(STDIN.read)
hook1 = Hook1.new(input_data)
hook2 = Hook1.new(input_data)
hook3 = Hook1.new(input_data)
# Execute the multiple hooks
hook1.call
hook2.call
hook3.call
# Merge the outputs
# In this case, ClaudeHooks::Output::UserPromptSubmit.merge follows the following merge logic:
# - continue: false wins (any hook script can stop execution)
# - suppressOutput: true wins (any hook script can suppress output)
# - decision: "block" wins (any hook script can block)
# - stopReason/reason: concatenated
# - additionalContext: concatenated
merged_output = ClaudeHooks::Output::UserPromptSubmit.merge(
hook1.output,
hook2.output,
hook3.output
)
# Automatically handles outputting to the right stream (STDOUT or STDERR) and uses the right exit code depending on hook state
merged_output.output_and_exit
end
๐ช Hook Exit Codes
[!NOTE] Hooks and output objects handle exit codes automatically. The information below is for reference and understanding. When using
hook.output_and_exitormerged_output.output_and_exit, you don't need to memorize these rules - the method chooses the correct exit code based on the hook type and the hook's state.
Claude Code hooks support multiple exit codes with different behaviors depending on the hook type.
exit 0: Success, allows the operation to continue, for most hooks,STDOUTwill be fed back to the user.- Claude Code does not see stdout if the exit code is 0, except for hooks where
STDOUTis injected as context.
- Claude Code does not see stdout if the exit code is 0, except for hooks where
exit 1: Non-blocking error,STDERRwill be fed back to the user.exit 2: Blocking error, in most casesSTDERRwill be fed back to Claude.- Other exit codes: Treated as non-blocking errors -
STDERRfed back to the user, execution continues.
[!WARNING] Some exit codes have different meanings depending on the hook type, here is a table to help summarize this.
| Hook Event | Exit 0 (Success) | Exit 1 (Non-blocking Error) | Exit Code 2 (Blocking Error) |
|---|---|---|---|
| UserPromptSubmit | Operation continuesSTDOUT added as context to Claude | Non-blocking errorSTDERR shown to user | Blocks prompt processing Erases prompt STDERR shown to user only |
| PreToolUse | Operation continuesSTDOUT shown to user in transcript mode | Non-blocking errorSTDERR shown to user | Blocks the tool callSTDERR shown to Claude |
| PostToolUse | Operation continuesSTDOUT shown to user in transcript mode | Non-blocking errorSTDERR shown to user | N/ASTDERR shown to Claude (tool already ran) |
| Notification | Operation continues Logged to debug only ( --debug) | Non-blocking error Logged to debug only ( --debug) | N/A Logged to debug only ( --debug) |
| Stop | Agent will stopSTDOUT shown to user in transcript mode | Agent will stopSTDERR shown to user | Blocks stoppageSTDERR shown to Claude |
| SubagentStop | Subagent will stopSTDOUT shown to user in transcript mode | Subagent will stopSTDERR shown to user | Blocks stoppageSTDERR shown to Claude subagent |
| PreCompact | Operation continuesSTDOUT shown to user in transcript mode | Non-blocking errorSTDERR shown to user | N/ASTDERR shown to user only |
| SessionStart | Operation continuesSTDOUT added as context to Claude | Non-blocking errorSTDERR shown to user | N/ASTDERR shown to user only |
| SessionEnd | Operation continues Logged to debug only ( --debug) | Non-blocking error Logged to debug only ( --debug) | N/A Logged to debug only ( --debug) |
Manually outputing and exiting example with success
For the operation to continue for a UserPromptSubmit hook, you would STDOUT.puts structured JSON data followed by exit 0:
puts JSON.generate({
continue: true,
stopReason: "",
suppressOutput: false,
hookSpecificOutput: {
hookEventName: "UserPromptSubmit",
additionalContext: "context here"
}
})
exit 0
Manually outputing and exiting example with error
For the operation to stop for a UserPromptSubmit hook, you would STDERR.puts structured JSON data followed by exit 2:
STDERR.puts JSON.generate({
continue: false,
stopReason: "JSON parsing error: #{e.message}",
suppressOutput: false
})
exit 2
[!WARNING] You don't have to manually do this, just use
output_and_exitto automatically handle this.
๐ Plugin Hooks Support
This DSL works seamlessly with Claude Code plugins! When creating plugin hooks, you can use the exact same Ruby DSL and enjoy all the same benefits.
How plugin hooks work:
- Plugin hooks are defined in the plugin's
hooks/hooks.jsonfile - They use the
${CLAUDE_PLUGIN_ROOT}environment variable to reference plugin files - Plugin hooks are automatically merged with user and project hooks when plugins are enabled
- Multiple hooks from different sources can respond to the same event
Example plugin hook configuration (hooks/hooks.json):
{
"description": "Automatic code formatting",
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/scripts/formatter.rb",
"timeout": 30
}
]
}
]
}
}
Using this DSL in your plugin hooks (hooks/scripts/formatter.rb):
#!/usr/bin/env ruby
require 'claude_hooks'
class PluginFormatter < ClaudeHooks::PostToolUse
def call
log "Plugin executing from: #{ENV['CLAUDE_PLUGIN_ROOT']}"
if tool_name.match?(/Write|Edit/)
file_path = tool_input['file_path']
log "Formatting file: #{file_path}"
# Your formatting logic here
# Can use all the DSL helper methods!
end
output
end
end
if __FILE__ == $0
input_data = JSON.parse(STDIN.read)
hook = PluginFormatter.new(input_data)
hook.call
hook.output_and_exit
end
Environment variables available in plugins:
${CLAUDE_PLUGIN_ROOT}: Absolute path to the plugin directory${CLAUDE_PROJECT_DIR}: Project root directory (same as for project hooks)- All standard environment variables and configuration options work the same way
See the plugin components reference for more details on creating plugin hooks.
๐จ Advices
- Logging: Use
log()method instead ofputsto avoid interfering with Claude Code's expected output. - Error Handling: Hooks should handle their own errors and use the
logmethod for debugging. For errors, don't forget to exit with the right exit code (1, 2) and output the JSON indicating the error to STDERR usingSTDERR.puts. - Path Management: Use
path_for()for all file operations relative to the Claude base directory.
โ ๏ธ Troubleshooting
Make your entrypoint scripts executable
Don't forget to make the scripts called from settings.json executable:
chmod +x ~/.claude/hooks/entrypoints/user_prompt_submit.rb
๐งช CLI Debugging
The ClaudeHooks::CLI module provides utilities to simplify testing hooks in isolation. Instead of writing repetitive JSON parsing and error handling code, you can use the CLI test runner.
Basic Usage
Replace the traditional testing boilerplate:
# Old way (15+ lines of repetitive code)
if __FILE__ == $0
begin
require 'json'
input_data = JSON.parse(STDIN.read)
hook = MyHook.new(input_data)
result = hook.call
puts JSON.generate(result)
rescue StandardError => e
STDERR.puts "Error: #{e.message}"
puts JSON.generate({
continue: false,
stopReason: "Error: #{e.message}",
suppressOutput: false
})
exit 1
end
end
With the simple CLI test runner:
# New way (1 line!)
if __FILE__ == $0
ClaudeHooks::CLI.test_runner(MyHook)
end
Customization with Blocks
You can customize the input data for testing using blocks:
if __FILE__ == $0
ClaudeHooks::CLI.test_runner(MyHook) do |input_data|
input_data['debug_mode'] = true
input_data['custom_field'] = 'test_value'
input_data['user_name'] = 'TestUser'
end
end
Testing Methods
1. Test with STDIN (default)
ClaudeHooks::CLI.test_runner(MyHook)
# Usage: echo '{"session_id":"test","prompt":"Hello"}' | ruby my_hook.rb
2. Test with default sample data instead of STDIN
ClaudeHooks::CLI.run_with_sample_data(MyHook, { 'prompt' => 'test prompt' })
# Provides default values, no STDIN needed
3. Test with Sample Data + Customization
ClaudeHooks::CLI.run_with_sample_data(MyHook) do |input_data|
input_data['prompt'] = 'Custom test prompt'
input_data['debug'] = true
end
Example Hook with CLI Testing
#!/usr/bin/env ruby
require 'claude_hooks'
class MyTestHook < ClaudeHooks::UserPromptSubmit
def call
log "Debug mode: #{input_data['debug_mode']}"
log "Processing: #{prompt}"
if input_data['debug_mode']
log "All input keys: #{input_data.keys.join(', ')}"
end
output
end
end
# Test runner with customization
if __FILE__ == $0
ClaudeHooks::CLI.test_runner(MyTestHook) do |input_data|
input_data['debug_mode'] = true
end
end
๐ Debugging
Test an individual entrypoint
# Test with sample data
echo '{"session_id": "test", "transcript_path": "/tmp/transcript", "cwd": "/tmp", "hook_event_name": "UserPromptSubmit", "user_prompt": "Hello Claude"}' | CLAUDE_PROJECT_DIR=$(pwd) ruby ~/.claude/hooks/entrypoints/user_prompt_submit.rb
๐งช Development & Contributing
Running Tests
This project uses Minitest for testing. To run the complete test suite:
# Run all tests
ruby test/run_all_tests.rb
# Run a specific test file
ruby test/test_output_classes.rb
Hooks 2
Sponsors
Details
- Marketplace
- kylesnowschwartz/SimpleClaude
- Source
- plugins/sc-hooks
- Author
- Kyle Snow Schwartz
- Category
- Automation
- License
- MIT
- Keywords
- hooks, automation, formatting, linting, claude-code