Skip to main content
commandsSource-backedReview first Safety Privacy

Configure Claude Code Hooks with /hooks

Use the built-in /hooks menu to inspect Claude Code hooks and configure them in settings.json so shell commands run deterministically at lifecycle events like PreToolUse, PostToolUse, and Stop.

by JSONbored·added 2025-10-25·
HarnessClaude Code
Invocation:/hooks
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://code.claude.com/docs/en/hooks, https://github.com/JSONbored/awesome-claude/blob/main/content/commands/hooks-generator.mdx
Safety notes
Hooks execute shell commands automatically with your user permissions whenever their event fires. A misconfigured or malicious hook can run destructive commands (file deletion, network calls, credential access) without further confirmation., PreToolUse hooks can allow or deny tool calls and PostToolUse hooks run after tools succeed; review hook commands before committing them to a shared .claude/settings.json so teammates do not inherit unexpected execution., Prefer `.claude/settings.json` for reviewed, team-shared hooks and `.claude/settings.local.json` for personal, gitignored hooks; use `disableAllHooks` to turn off user/project hooks when running untrusted code.
Privacy notes
Command and HTTP hooks receive event JSON on stdin including `session_id`, `transcript_path`, `cwd`, and tool input (such as file paths and Bash commands); a hook that forwards this data over the network can expose local file contents, paths, or command arguments to third parties., HTTP hooks can include headers with interpolated environment variables (restricted by `allowedEnvVars`); avoid embedding secrets in hook configuration that is committed to a repository.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-10-25

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

Copy & paste

Copy-ready — paste the snippet to get started.

Install command

Not provided

Config snippet

Not provided

Copy snippet

Provided

Prerequisites

None

Platforms

1 listed

Difficulty

100/100

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Safety & privacy surface

Safety & privacy surface

3 safety and 2 privacy notes across 2 risk areas. Review closely: credentials & tokens.

2 areas
  • SafetyCredentials & tokensHooks execute shell commands automatically with your user permissions whenever their event fires. A misconfigured or malicious hook can run destructive commands (file deletion, network calls, credential access) without further confirmation.
  • SafetyExecution & processesPreToolUse hooks can allow or deny tool calls and PostToolUse hooks run after tools succeed; review hook commands before committing them to a shared .claude/settings.json so teammates do not inherit unexpected execution.
  • SafetyExecution & processesPrefer `.claude/settings.json` for reviewed, team-shared hooks and `.claude/settings.local.json` for personal, gitignored hooks; use `disableAllHooks` to turn off user/project hooks when running untrusted code.
  • PrivacyCredentials & tokensCommand and HTTP hooks receive event JSON on stdin including `session_id`, `transcript_path`, `cwd`, and tool input (such as file paths and Bash commands); a hook that forwards this data over the network can expose local file contents, paths, or command arguments to third parties.
  • PrivacyCredentials & tokensHTTP hooks can include headers with interpolated environment variables (restricted by `allowedEnvVars`); avoid embedding secrets in hook configuration that is committed to a repository.

Safety notes

  • Hooks execute shell commands automatically with your user permissions whenever their event fires. A misconfigured or malicious hook can run destructive commands (file deletion, network calls, credential access) without further confirmation.
  • PreToolUse hooks can allow or deny tool calls and PostToolUse hooks run after tools succeed; review hook commands before committing them to a shared .claude/settings.json so teammates do not inherit unexpected execution.
  • Prefer `.claude/settings.json` for reviewed, team-shared hooks and `.claude/settings.local.json` for personal, gitignored hooks; use `disableAllHooks` to turn off user/project hooks when running untrusted code.

Privacy notes

  • Command and HTTP hooks receive event JSON on stdin including `session_id`, `transcript_path`, `cwd`, and tool input (such as file paths and Bash commands); a hook that forwards this data over the network can expose local file contents, paths, or command arguments to third parties.
  • HTTP hooks can include headers with interpolated environment variables (restricted by `allowedEnvVars`); avoid embedding secrets in hook configuration that is committed to a repository.

Schema details

Install type
copy
Reading time
8 min
Difficulty score
100
Troubleshooting
Yes
Breaking changes
No
Skill and platform metadata
Retrieval sources
https://code.claude.com/docs/en/hookshttps://code.claude.com/docs/en/hooks-guidehttps://code.claude.com/docs/en/settingshttps://code.claude.com/docs/en/slash-commands
Runtime and command metadata
Command syntax
/hooks
Script body
`/hooks` is a built-in Claude Code slash command that opens an interactive menu for reviewing your configured hooks. Hooks let you run your own shell commands (or HTTP calls, prompts, agents, and MCP tools) automatically at defined points in Claude Code's lifecycle, giving you deterministic control over formatting, linting, testing, notifications, and guardrails instead of relying on the model to choose to run them.

> Note: There is no `/hooks-generator` command and no `--auto-format`, `--auto-test`, `--post-edit`, or similar flags. The real workflow is: run `/hooks` to inspect what is configured, then edit your `settings.json` to add or change hooks. This page documents that real, documented behavior.

## The `/hooks` command

Type `/hooks` in an interactive Claude Code session to open a menu that shows:

- Every configured hook event and how many hooks are attached to it
- The matcher groups under each event
- Full handler details (the command, URL, or prompt that runs)
- The source of each hook (User, Project, Local, Plugin, Session, or Built-in)

The `/hooks` menu is a read-only browser. To add, change, or remove hooks, edit the JSON settings files directly (see below).

## Where hooks are configured

Hooks are defined under a top-level `hooks` key in a settings file. Locations, in order of precedence:

| Location | Scope | Shareable |
| --- | --- | --- |
| `~/.claude/settings.json` | All your projects | No |
| `.claude/settings.json` | One project | Yes (commit to repo) |
| `.claude/settings.local.json` | One project | No (gitignored) |
| Managed policy settings | Organization-wide | Yes |

## Configuration structure

The `hooks` object nests three levels: event name, a list of matcher groups, and a list of handlers per group.

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh"
          }
        ]
      }
    ]
  }
}
```

### Hook events

Documented lifecycle events include (non-exhaustive):

- Session: `SessionStart`, `SessionEnd`, `Setup`
- Per turn: `UserPromptSubmit`, `Stop`, `Notification`
- Per tool call: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`
- Other: `SubagentStart`, `SubagentStop`, `PreCompact`, `PostCompact`

### Matchers

The `matcher` field filters when a hook fires. For tool events it matches the tool name:

- `"*"`, `""`, or omitted: match everything
- `Edit|Write`: a `|`-separated list of tool names
- `mcp__memory__.*`: a JavaScript regex (used here to match all tools from an MCP server)

For `SessionStart` the matcher is the session source (`startup`, `resume`, `clear`, `compact`); other events match against their own values (see the reference).

### Handler fields

A `command` handler runs a shell command. Common fields:

- `type` (required): `"command"`, `"http"`, `"mcp_tool"`, `"prompt"`, or `"agent"`
- `command`: the shell command or executable path
- `timeout`: seconds before the hook is canceled
- `async`: run in the background without blocking

## How a command hook receives data

Command hooks receive a JSON object on **stdin** describing the event. They do not use `$FILE_PATH`-style substitution variables. Available top-level input fields include `session_id`, `transcript_path`, `cwd`, `permission_mode`, and `hook_event_name`, plus event-specific fields such as the tool input. Parse stdin (for example with `jq`) to read the file path or command being acted on.

The hook's behavior is driven by its **exit code**:

- Exit `0`: success; JSON on stdout (if any) is parsed for a decision
- Exit `2`: blocking error; stderr is shown and the action is blocked
- Other codes: non-blocking error; stderr is shown and execution continues

## Example: format files after edits

A `PostToolUse` hook that runs your formatter after Claude edits or writes a file. The hook script reads the edited file path from the JSON on stdin.

`.claude/settings.json`:

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/format.sh"
          }
        ]
      }
    ]
  }
}
```

`.claude/hooks/format.sh`:

```bash
#!/bin/bash
FILE=$(jq -r '.tool_input.file_path')
[ -n "$FILE" ] && npx prettier --write "$FILE"
```

## Example: block a destructive Bash command

A `PreToolUse` hook can deny a tool call before it runs by returning a permission decision on stdout (with exit `0`):

`.claude/hooks/block-rm.sh`:

```bash
#!/bin/bash
CMD=$(jq -r '.tool_input.command')
if echo "$CMD" | grep -q 'rm -rf'; then
  jq -n '{
    hookSpecificOutput: {
      hookEventName: "PreToolUse",
      permissionDecision: "deny",
      permissionDecisionReason: "Destructive command blocked"
    }
  }'
else
  exit 0
fi
```

## Example: notify when a turn finishes

A `Stop` hook that fires when Claude finishes responding:

```json
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "osascript -e 'display notification \"Done\" with title \"Claude Code\"'",
            "async": true
          }
        ]
      }
    ]
  }
}
```

## When to use hooks

- Run formatters, linters, or type-checks deterministically after every edit
- Enforce guardrails (block dangerous commands) at `PreToolUse`
- Set up or tear down environment state at `SessionStart` / `SessionEnd`
- Send notifications at `Stop` or `Notification`

## Disabling hooks

To turn off all user and project hooks (managed-policy hooks are unaffected), set in settings:

```json
{
  "disableAllHooks": true
}
```

## Related custom commands

Because hooks are configured by editing settings files, you can wrap your own workflow in a **custom slash command** (a user-created Markdown file in `.claude/commands/`). For example, create `.claude/commands/add-format-hook.md` describing the change you want, then invoke it with `/add-format-hook`. That is a custom recipe you author, not a built-in feature, and it still results in edits to `settings.json` using the structure above.
Full copyable content
/hooks

About this resource

/hooks is a built-in Claude Code slash command that opens an interactive menu for reviewing your configured hooks. Hooks let you run your own shell commands (or HTTP calls, prompts, agents, and MCP tools) automatically at defined points in Claude Code's lifecycle, giving you deterministic control over formatting, linting, testing, notifications, and guardrails instead of relying on the model to choose to run them.

Note: There is no /hooks-generator command and no --auto-format, --auto-test, --post-edit, or similar flags. The real workflow is: run /hooks to inspect what is configured, then edit your settings.json to add or change hooks. This page documents that real, documented behavior.

The /hooks command

Type /hooks in an interactive Claude Code session to open a menu that shows:

  • Every configured hook event and how many hooks are attached to it
  • The matcher groups under each event
  • Full handler details (the command, URL, or prompt that runs)
  • The source of each hook (User, Project, Local, Plugin, Session, or Built-in)

The /hooks menu is a read-only browser. To add, change, or remove hooks, edit the JSON settings files directly (see below).

Where hooks are configured

Hooks are defined under a top-level hooks key in a settings file. Locations, in order of precedence:

Location Scope Shareable
~/.claude/settings.json All your projects No
.claude/settings.json One project Yes (commit to repo)
.claude/settings.local.json One project No (gitignored)
Managed policy settings Organization-wide Yes

Configuration structure

The hooks object nests three levels: event name, a list of matcher groups, and a list of handlers per group.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh"
          }
        ]
      }
    ]
  }
}

Hook events

Documented lifecycle events include (non-exhaustive):

  • Session: SessionStart, SessionEnd, Setup
  • Per turn: UserPromptSubmit, Stop, Notification
  • Per tool call: PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest
  • Other: SubagentStart, SubagentStop, PreCompact, PostCompact

Matchers

The matcher field filters when a hook fires. For tool events it matches the tool name:

  • "*", "", or omitted: match everything
  • Edit|Write: a |-separated list of tool names
  • mcp__memory__.*: a JavaScript regex (used here to match all tools from an MCP server)

For SessionStart the matcher is the session source (startup, resume, clear, compact); other events match against their own values (see the reference).

Handler fields

A command handler runs a shell command. Common fields:

  • type (required): "command", "http", "mcp_tool", "prompt", or "agent"
  • command: the shell command or executable path
  • timeout: seconds before the hook is canceled
  • async: run in the background without blocking

How a command hook receives data

Command hooks receive a JSON object on stdin describing the event. They do not use $FILE_PATH-style substitution variables. Available top-level input fields include session_id, transcript_path, cwd, permission_mode, and hook_event_name, plus event-specific fields such as the tool input. Parse stdin (for example with jq) to read the file path or command being acted on.

The hook's behavior is driven by its exit code:

  • Exit 0: success; JSON on stdout (if any) is parsed for a decision
  • Exit 2: blocking error; stderr is shown and the action is blocked
  • Other codes: non-blocking error; stderr is shown and execution continues

Example: format files after edits

A PostToolUse hook that runs your formatter after Claude edits or writes a file. The hook script reads the edited file path from the JSON on stdin.

.claude/settings.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/format.sh"
          }
        ]
      }
    ]
  }
}

.claude/hooks/format.sh:

#!/bin/bash
FILE=$(jq -r '.tool_input.file_path')
[ -n "$FILE" ] && npx prettier --write "$FILE"

Example: block a destructive Bash command

A PreToolUse hook can deny a tool call before it runs by returning a permission decision on stdout (with exit 0):

.claude/hooks/block-rm.sh:

#!/bin/bash
CMD=$(jq -r '.tool_input.command')
if echo "$CMD" | grep -q 'rm -rf'; then
  jq -n '{
    hookSpecificOutput: {
      hookEventName: "PreToolUse",
      permissionDecision: "deny",
      permissionDecisionReason: "Destructive command blocked"
    }
  }'
else
  exit 0
fi

Example: notify when a turn finishes

A Stop hook that fires when Claude finishes responding:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "osascript -e 'display notification \"Done\" with title \"Claude Code\"'",
            "async": true
          }
        ]
      }
    ]
  }
}

When to use hooks

  • Run formatters, linters, or type-checks deterministically after every edit
  • Enforce guardrails (block dangerous commands) at PreToolUse
  • Set up or tear down environment state at SessionStart / SessionEnd
  • Send notifications at Stop or Notification

Disabling hooks

To turn off all user and project hooks (managed-policy hooks are unaffected), set in settings:

{
  "disableAllHooks": true
}

Related custom commands

Because hooks are configured by editing settings files, you can wrap your own workflow in a custom slash command (a user-created Markdown file in .claude/commands/). For example, create .claude/commands/add-format-hook.md describing the change you want, then invoke it with /add-format-hook. That is a custom recipe you author, not a built-in feature, and it still results in edits to settings.json using the structure above.

Source citations

Add this badge to your README

Show that Configure Claude Code Hooks with /hooks is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/commands/hooks-generator.svg)](https://heyclau.de/entry/commands/hooks-generator)

How it compares

Configure Claude Code Hooks with /hooks side by side with its closest alternative on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

Next steps differ across entries — use the actions in the table below to copy install commands and source links per resource.

Field

Use the built-in /hooks menu to inspect Claude Code hooks and configure them in settings.json so shell commands run deterministically at lifecycle events like PreToolUse, PostToolUse, and Stop.

Open dossier

Claude Code slash command that generates a new .claude/commands/*.md file from a template, with optional arguments, frontmatter, and team-sharing support.

Open dossier
Next stepsDiffers
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backed
Submitter
Install riskReview firstReview first
Notes Safety Privacy Safety Privacy
Brand
Categorycommandscommands
Sourcesource-backedsource-backed
AuthorJSONboredJSONbored
Added2025-10-252025-10-25
Platforms
Claude Code
Claude Code
Source repo
Safety notesHooks execute shell commands automatically with your user permissions whenever their event fires. A misconfigured or malicious hook can run destructive commands (file deletion, network calls, credential access) without further confirmation. PreToolUse hooks can allow or deny tool calls and PostToolUse hooks run after tools succeed; review hook commands before committing them to a shared .claude/settings.json so teammates do not inherit unexpected execution. Prefer `.claude/settings.json` for reviewed, team-shared hooks and `.claude/settings.local.json` for personal, gitignored hooks; use `disableAllHooks` to turn off user/project hooks when running untrusted code.Creates .md files in .claude/commands/ in the current project directory; review generated content before committing.
Privacy notesCommand and HTTP hooks receive event JSON on stdin including `session_id`, `transcript_path`, `cwd`, and tool input (such as file paths and Bash commands); a hook that forwards this data over the network can expose local file contents, paths, or command arguments to third parties. HTTP hooks can include headers with interpolated environment variables (restricted by `allowedEnvVars`); avoid embedding secrets in hook configuration that is committed to a repository.Creates .md files in your local .claude/commands/ directory; no content is sent externally.
Prerequisites— none listed— none listed
Install
/slash-command-gen [command-name] [options]
Config
Citations
ClaimUnclaimedUnclaimed
Open in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.