Claude.Hooks.Hook.Behaviour behaviour (claude v0.2.3)

View Source

Behaviour for implementing Claude Code hooks.

Hooks must implement:

  • config/0 to return their hook configuration as a %Claude.Hooks.Hook{} struct
  • config/1 to return their hook configuration with user-provided config
  • run/1 to execute the hook logic with JSON input
  • run/2 to execute the hook logic with JSON input and user config
  • description/0 to provide a human-readable description

Using the macro

You can use the use Claude.Hooks.Hook.Behaviour macro to reduce boilerplate:

defmodule MyHook do
  use Claude.Hooks.Hook.Behaviour,
    event: :post_tool_use,
    matcher: "Write|Edit",
    description: "My custom hook"

  def run(input) do
    # Your hook logic here
    :ok
  end

  # Override to handle user config
  def run(input, user_config) do
    # Your hook logic with user config
    :ok
  end
end

The macro automatically:

  • Implements the behaviour callbacks
  • Generates the config/0 and config/1 functions
  • Provides helper functions for common patterns

Summary

Callbacks

Returns the hook configuration as a %Claude.Hook{} struct.

Returns the hook configuration with user-provided config.

Returns a human-readable description of what this hook does.

Executes the hook logic with stdin JSON input.

Executes the hook logic with stdin JSON input and user configuration.

Callbacks

config()

@callback config() :: Claude.Hooks.Hook.t()

Returns the hook configuration as a %Claude.Hook{} struct.

This configuration will be automatically encoded to JSON and written to the settings.json file during installation.

config(user_config)

@callback config(user_config :: map()) :: Claude.Hooks.Hook.t()

Returns the hook configuration with user-provided config.

description()

@callback description() :: String.t()

Returns a human-readable description of what this hook does.

run(json_input)

@callback run(json_input :: String.t()) :: :ok | {:error, term()}

Executes the hook logic with stdin JSON input.

Parameters

  • json_input - The raw JSON string from stdin containing the full hook data

Return values

  • :ok - Hook executed successfully
  • {:error, reason} - Hook execution failed

run(json_input, user_config)

@callback run(json_input :: String.t(), user_config :: map()) :: :ok | {:error, term()}

Executes the hook logic with stdin JSON input and user configuration.

Parameters

  • json_input - The raw JSON string from stdin containing the full hook data
  • user_config - The user configuration from .claude.exs

Return values

  • :ok - Hook executed successfully
  • {:error, reason} - Hook execution failed