ThisCalculator

Everyday

Claude Code Hooks & Telemetry: Events, Signals, Handlers

Updated · Standard formula, shown below

Claude Code hooks and telemetry let you intercept lifecycle events (like tool calls or session start) with custom handlers and send structured usage data to your own backend. You choose which events to handle, what signals to send, and how to wire handlers via configuration or command-line flags. This article explains the event model, how to set up handlers, and how telemetry differs from hooks.

Background: Why Hooks and Telemetry Exist

Claude Code is an agentic coding tool that runs in your terminal. As it works, it performs many actions: reading files, running commands, editing code, and asking for user input. For teams and individual developers, it’s often important to know what the agent is doing, enforce policies (like blocking dangerous commands), or gather metrics for improving workflows. Hooks and telemetry are the two official mechanisms for this.

Hooks are synchronous callbacks that run at specific points in the agent’s lifecycle. They let you run your own script or command before or after certain events, and can even block or modify the agent’s behavior. Telemetry, on the other hand, is a separate system that sends structured JSON events to an HTTP endpoint you control, allowing you to collect data for analytics or auditing without affecting the agent’s execution.

How Hooks Work: Events and Handlers

Hooks are defined in a JSON configuration file (usually .claude/hooks.json in your project root) or passed via the --hook command-line flag. Each hook is associated with an event name, and the handler is a command that runs in your shell. For example:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "node ./scripts/check-command.js" }
        ]
      }
    ]
  }
}

When the agent is about to run a Bash tool, it executes your command. The handler receives JSON input on stdin containing details like the tool name, input arguments, and session ID. The handler’s output (JSON on stdout) can control behavior: setting "decision": "block" stops the tool, "decision": "allow" lets it proceed, and "decision": "ask" prompts the user for confirmation.

Common hook events include:

  • PreToolUse – runs before a tool is executed
  • PostToolUse – runs after a tool finishes
  • Notification – runs when the agent sends a notification
  • UserPromptSubmit – runs when you submit a prompt
  • Stop – runs when the agent finishes responding
  • SubagentStop – runs when a subagent finishes
  • PreCompact – runs before context compaction
  • SessionStart – runs when a session begins

Choosing Handlers: What to Run and When

Choosing the right handler depends on what you want to achieve. For safety, you might want a PreToolUse handler that scans Bash commands for dangerous patterns (like rm -rf) and blocks them. For logging, a PostToolUse handler that records every file read could be useful. For debugging, a Notification handler that sends alerts to a chat channel might help.

Each handler is a shell command, so you can use any language or tool. Keep in mind that the handler runs synchronously and blocks the agent until it finishes. If your handler is slow, it will slow down the whole session. For long-running tasks, consider spawning background processes or using telemetry instead.

Telemetry: Sending Events to Your Backend

Telemetry in Claude Code is configured separately from hooks. You set an HTTP endpoint via the --telemetry-endpoint flag or environment variable, and the agent sends JSON events to that URL. Each event contains a timestamp, session ID, event type, and event-specific data (like tool name or input).

For example, to enable telemetry, you might run:

claude --telemetry-endpoint https://your-server.com/telemetry

Then every event (tool use, prompt, error, etc.) is POSTed to that endpoint. The data is structured and can be stored in a database or sent to an analytics platform. Unlike hooks, telemetry does not affect the agent’s behavior – it is purely observational.

Common Problems and Misconceptions

One common mistake is confusing hooks with telemetry. Hooks are for controlling behavior; telemetry is for collecting data. Another is assuming hooks receive all data in environment variables – they don’t, they receive JSON on stdin. Also, handlers that output invalid JSON will cause errors, so always validate your output.

Another misconception is that hooks can be used to modify the agent’s response. In most cases, hooks can only block or allow actions, not change the text the agent produces. For that, you’d need to modify the prompt or use a different mechanism.

Comparison: Hooks vs. Telemetry vs. Logging

Hooks and telemetry serve different purposes, and both are distinct from built-in logging (the --log flag). Here’s a quick comparison:

  • Hooks – synchronous, can block/modify behavior, run locally, per-project config
  • Telemetry – asynchronous, observational, sends data to a remote server, global config
  • Logging – writes to a local file, includes full conversation and tool outputs, for debugging

You can use all three simultaneously. For example, use hooks to enforce a security policy, telemetry to track usage metrics across your team, and logging to debug a specific issue.

Safety and Best Practices

When writing handlers, be careful with the commands you run. A handler that executes arbitrary shell commands could introduce security risks if it doesn’t validate input. Always sanitize any data from the JSON input before using it in a shell command to avoid injection attacks.

Also, be mindful of infinite loops: if a hook triggers another tool call that triggers the same hook, you could get stuck. Test your hooks in a sandbox environment first. For telemetry, ensure your endpoint is secure and that you’re not sending sensitive data (like file contents) unless you intend to.

Frequently Asked Questions

Can I use hooks to stop Claude from running a specific command?

Yes. In a PreToolUse hook for the Bash tool, you can inspect the command and return {"decision": "block"} to prevent it. You can also return an override to replace the command, or ask to prompt the user.

How do I see what data telemetry sends?

You can set up a simple HTTP server (like using nc -l or a small Node.js server) as your telemetry endpoint and inspect the JSON payloads. The exact structure depends on the event type, but generally includes a timestamp, session ID, and event-specific fields.

Do hooks work in headless or CI environments?

Yes, hooks work in any environment where Claude Code runs, including CI. However, note that in non-interactive mode, hooks that return ask may default to block or allow depending on your settings. Test in your CI environment to ensure expected behavior.

Can I have multiple handlers for the same event?

Yes, you can define multiple handlers for the same event. They run in the order specified in the configuration. Each handler receives the same input, but you can use the hookSpecificOutput field to pass data between handlers.

Is there a way to disable hooks temporarily?

Yes, you can remove the hooks configuration file or use the --no-hooks flag (if available in your version). Alternatively, you can set an environment variable like CLAUDE_CODE_DISABLE_HOOKS=1 (check the official docs for your version).

What’s the difference between a hook and a plugin?

Plugins are a newer feature that can add tools, commands, and agents to Claude Code. Hooks are simpler: they only run scripts at specific events. Plugins can also define hooks, but they offer more extensive customization.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.