ClaudeCode.ToolCallback (ClaudeCode v0.16.0)

View Source

Handles post-execution tool callbacks for logging and auditing.

This module correlates tool use requests (from Assistant messages) with their results (from User messages) and invokes callbacks asynchronously when results are received.

Usage

Configure a callback when starting a session:

callback = fn event ->
  Logger.info("Tool #{event.name} executed: #{inspect(event.result)}")
end

{:ok, session} = ClaudeCode.start_link(
  api_key: "sk-ant-...",
  tool_callback: callback
)

Event Structure

The callback receives a map with the following keys:

  • :name - Tool name (e.g., "Read", "Write", "Bash")
  • :input - Tool input parameters (map)
  • :result - Tool execution result (string)
  • :is_error - Whether the tool execution failed (boolean)
  • :tool_use_id - Unique identifier for correlation (string)
  • :timestamp - When the result was received (DateTime)

Summary

Functions

Processes a message and invokes callback when tool results are detected.

Types

pending_tools()

@type pending_tools() :: %{
  required(String.t()) => %{
    name: String.t(),
    input: map(),
    started_at: DateTime.t()
  }
}

tool_event()

@type tool_event() :: %{
  name: String.t(),
  input: map(),
  result: String.t(),
  is_error: boolean(),
  tool_use_id: String.t(),
  timestamp: DateTime.t()
}

Functions

process_message(message, pending_tools, callback)

@spec process_message(
  message :: struct(),
  pending_tools :: pending_tools(),
  callback :: (tool_event() -> any()) | nil
) :: {pending_tools(), [tool_event()]}

Processes a message and invokes callback when tool results are detected.

For Assistant messages with ToolUse blocks, stores tool info in pending_tools map. For User messages with ToolResult blocks, correlates with pending tools and invokes callback.

Returns {updated_pending_tools, events} where events is a list of tool events that were processed (for testing/debugging purposes).