本文へ移動
cccskills
無料GitHub で公開

hooks-core-reference

Hook system fundamentals — all events, configuration structure, matchers per event type, environment variables, execution behavior, security, and debugging. Use when creating hooks, understanding hook events, matchers, configuration locations, environment variables, or troubleshooting hook issues.

インストール方法を見る

含まれるファイル(1)

  • SKILL.md15.4 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

Claude Code Hooks — Core Reference (May 2026)

Hooks execute custom commands, HTTP calls, MCP tool calls, LLM prompts, or agent verifiers in response to Claude Code events. Use for automation, validation, formatting, and security.

For JSON input/output schemas, activate /plugin-creator:hooks-io-api. For working examples and patterns, activate /plugin-creator:hooks-patterns.


All Hook Events

EventWhen FiredMatcher FieldCommon Uses
PreToolUseBefore tool executiontool nameValidation, blocking
PermissionRequestWhen user shown permission dialogtool nameAuto-approval policies
PermissionDeniedAuto mode classifier denies a tool calltool nameLog denials, allow retry
PostToolUseAfter successful tool executiontool nameFormatting, linting
PostToolUseFailureAfter tool failstool nameError handling
PostToolBatchAfter all tools in a parallel batch resolve, before next model callno matcherBatch-level context injection
NotificationWhen Claude wants attentionnotification typeCustom notifications
UserPromptSubmitUser submits promptno matcherInput validation
UserPromptExpansionSlash command expands into a promptcommand nameBlock expansions, inject context
StopClaude finishes a turnno matcherCleanup, final checks
StopFailureTurn ends due to API errorerror typeLogging, alerts
SubagentStartWhen spawning a subagentagent type nameSubagent initialization
SubagentStopSubagent (Agent tool) completes — fires in parent sessionagent type nameResult validation
TeammateIdleAgent team teammate about to go idleno matcherQuality gates
TaskCreatedTask being created via TaskCreateno matcherNaming enforcement
TaskCompletedTask being marked as completedno matcherCompletion enforcement
InstructionsLoadedCLAUDE.md or rules file loadedload reasonObservability
ConfigChangeConfiguration file changes during sessionconfig sourceSettings auditing
WorktreeCreateWorktree being createdno matcherCustom VCS integration
WorktreeRemoveWorktree being removedno matcherCustom VCS cleanup
PreCompactBefore context compactionmanual or autoState backup
PostCompactAfter context compaction completesmanual or autoReact to new state
ElicitationMCP server requests user input mid-taskMCP server nameProgrammatic responses
ElicitationResultUser responds to MCP elicitationMCP server nameObserve/modify response
SetupRepository setup/maintenance flagsinit or maintenanceOne-time operations
CwdChangedWorking directory changes during sessionno matcherReload env, activate toolchains
FileChangedWatched file changes on diskliteral filename patternMonitor .env, direnv integration
SessionStartSession begins or resumesstartup, resume, clear, compactEnvironment setup
SessionEndSession endsexit reasonCleanup, persistence

Stop vs SubagentStop — scope distinction

Stop fires in every session — the main orchestrator session and inside embedded subagents (Agent-tool spawned). When firing inside a subagent, the input includes agent_id and agent_type fields. Use these to guard hooks that should only run in the main session:

// Only run in the main orchestrator, not inside embedded subagents
if (data.agent_id || data.agent_type) {
    process.stdout.write(JSON.stringify({}));
    process.exit(0);
}

SubagentStop fires only in the parent session when an Agent-tool call completes.

Frontmatter exception: Stop hooks defined in skill/agent frontmatter are automatically converted to SubagentStop for that component's lifecycle. This only applies to frontmatter-defined hooks, not plugin or settings hooks.


Configuration

Configuration Locations

LocationScopeShareable
~/.claude/settings.jsonAll your projectsNo
.claude/settings.jsonSingle projectYes, via git
.claude/settings.local.jsonSingle projectNo, gitignored
Managed policy settingsOrganization-wideYes, admin-controlled
Plugin hooks/hooks.jsonWhen plugin is enabledYes, bundled with plugin
Skill or agent frontmatterWhile component is activeYes, in component file

Enterprise administrators can use allowManagedHooksOnly to block user, project, and plugin hooks. Hooks from plugins force-enabled in managed enabledPlugins are exempt.

Structure

{
  "hooks": {
    "EventName": [
      {
        "matcher": "ToolPattern",
        "hooks": [
          {
            "type": "command",
            "command": "your-command-here",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

Hook Handler Fields

Common fields (all hook types):

FieldRequiredDescription
typeyes"command", "http", "mcp_tool", "prompt", or "agent"
ifnoPermission rule syntax to filter when this handler spawns (e.g. "Bash(git *)", "Edit(*.ts)"). Only evaluated on tool events.
timeoutnoSeconds before canceling. Defaults: 600 for command/http/mcp_tool; 30 for prompt; 60 for agent. UserPromptSubmit lowers command/http/mcp_tool default to 30.
statusMessagenoCustom spinner message displayed while hook runs
oncenoIf true, runs once per session then removed. Only honored in skill frontmatter.

Command hook fields (in addition to common):

FieldDescription
commandShell command string (shell form) or executable path (exec form when args is set)
argsArgument list. When present, command is the executable; spawned directly with no shell
asyncIf true, runs in background without blocking Claude
asyncRewakeIf true, runs in background and wakes Claude when it exits with code 2
shellShell to use: "bash" (default) or "powershell" (Windows only)

HTTP hook fields:

FieldDescription
urlURL to POST event data to
headersKey-value pairs. Values support $VAR_NAME interpolation
allowedEnvVarsWhich env vars may be interpolated into headers

Prompt/agent hook fields:

FieldDescription
promptPrompt text. Use $ARGUMENTS as placeholder for hook input JSON
modelModel override. Defaults to a fast model

Event-Specific Matchers

PreToolUse / PermissionRequest / PostToolUse / PostToolUseFailure / PermissionDenied

Matched against tool_name. Matcher rules:

  • Plain name: Write matches only Write tool
  • Pipe list: Edit|Write matches either
  • Regex (contains non-alphanumeric chars): ^Notebook or mcp__memory__.*
  • mcp__<server>__.* matches all tools from a server (.* required — bare mcp__server is exact match, finds nothing)
MatcherDescription
AgentSubagent operations
BashShell commands
GlobFile pattern matching
GrepContent search
ReadFile reading
EditFile editing
WriteFile writing
WebFetchWeb fetching
WebSearchWeb search
mcp__<server>__.*All tools from MCP server

SubagentStart / SubagentStop

Matched against agent_type. For custom subagents, agent_type is the name field from the agent's frontmatter, not the filename.

Matcher valueFires for
general-purposeBuilt-in general-purpose agent
ExploreBuilt-in Explore agent
PlanBuilt-in Plan agent
^my-agent-name$Custom agent with name: my-agent-name in frontmatter
(regex supported)^docs-review- matches all agents starting with that prefix

SessionStart

MatcherWhen
startupNew session started
resume--resume, --continue, or /resume
clear/clear command
compactAuto or manual compact

SessionEnd

MatcherWhen
clearSession cleared with /clear
resumeSession switched via interactive /resume
logoutUser logged out
prompt_input_exitUser exited while prompt input was visible
bypass_permissions_disabledBypass permissions mode was disabled
otherOther exit reasons

Notification

MatcherFires when
permission_promptPermission requests from Claude
idle_promptClaude waiting for input
auth_successAuthentication success
elicitation_dialogMCP tool elicitation dialog
elicitation_completeMCP elicitation submitted or dismissed
elicitation_responseMCP elicitation response sent to server

InstructionsLoaded

MatcherFires when
session_startFile loaded at session start
nested_traversalFile loaded when Claude accesses a subdirectory
path_glob_matchFile loaded via paths: frontmatter match
includeFile loaded via include directive
compactFile re-loaded after compaction

ConfigChange

MatcherWhen
user_settings~/.claude/settings.json changes
project_settings.claude/settings.json changes
local_settings.claude/settings.local.json changes
policy_settingsManaged policy settings (non-blockable)
skillsSkill file changes

PreCompact / PostCompact

MatcherTrigger
manual/compact command
autoAuto-compact when context window fills

Setup

MatcherTrigger
init--init or --init-only flags
maintenance--maintenance flag

StopFailure

MatcherError type
rate_limitRate limit
authentication_failedAuth failure
billing_errorBilling error
server_errorAPI server error
max_output_tokensOutput token limit
unknownUnknown error

Elicitation / ElicitationResult

Matched against the MCP server name.

UserPromptExpansion

Matched against command_name (the slash command name).

FileChanged

Matcher value is split on | and registered as literal filenames to watch (e.g. .envrc|.env). Same value also filters which hook groups run when a file changes.

No-matcher events

UserPromptSubmit, PostToolBatch, Stop, TeammateIdle, TaskCreated, TaskCompleted, WorktreeCreate, WorktreeRemove, CwdChanged — matchers are silently ignored on these events. They always fire on every occurrence.


Path Placeholders

Use in command and args fields to reference scripts at stable paths:

PlaceholderValue
${CLAUDE_PROJECT_DIR}Project root (where Claude Code was started)
${CLAUDE_PLUGIN_ROOT}Plugin installation directory. Changes on plugin update
${CLAUDE_PLUGIN_DATA}Plugin persistent data directory (~/.claude/plugins/data/{id}/). Survives plugin updates

Exec form (when args is set): Claude Code spawns the executable directly. Each args element is one argument with no shell tokenization. Use for paths that may contain spaces.

Shell form (when args is absent): command string passed to sh -c. Wrap placeholders in double-quotes.

{
  "type": "command",
  "command": "node",
  "args": ["${CLAUDE_PLUGIN_ROOT}/hooks/my-hook.cjs"]
}

Environment Variables

VariableDescriptionAvailable In
CLAUDE_PROJECT_DIRProject root (absolute path)All hooks
CLAUDE_CODE_REMOTE"true" if remote web, absent if local CLIAll hooks
CLAUDE_ENV_FILEPath for persisting env vars into Bash commandsSessionStart, Setup, CwdChanged, FileChanged
CLAUDE_PLUGIN_ROOTPlugin directory (absolute)Plugin hooks
CLAUDE_PLUGIN_DATAPlugin persistent data directoryPlugin hooks
CLAUDE_EFFORTActive effort level (low/medium/high/xhigh/max)Tool-use context events

CLAUDE_ENV_FILE — Persisting Environment Variables

Variables written to CLAUDE_ENV_FILE are sourced before each Bash command. Append (>>) to preserve variables set by other hooks.

#!/bin/bash
if [ -n "$CLAUDE_ENV_FILE" ]; then
  echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"
  echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"
fi

Execution Details

AspectBehavior
ParallelismAll matching hooks in a group run in parallel
DeduplicationIdentical commands/URLs deduplicated automatically
EnvironmentRuns in cwd with Claude Code's environment
TerminalNo controlling terminal (macOS/Linux v2.1.139+). Cannot open /dev/tty. Use terminalSequence JSON output for bell/notification
Block capStop/SubagentStop hooks blocked 8 consecutive times triggers override — subagent is forced to stop

Security Considerations

Command hooks run with your system user's full permissions and can modify, delete, or access any files your account can access.

Best practices:

  1. Validate and sanitize inputs — never trust stdin data blindly
  2. Quote shell variables — use "$VAR" not $VAR
  3. Block path traversal — check for .. in file paths
  4. Use ${CLAUDE_PROJECT_DIR} for absolute paths — never relative
  5. Skip sensitive files — avoid .env, .git/, keys, etc.

Debugging

# Write debug log to file
claude --debug-file /tmp/claude.log

# Enable verbose mode mid-session
ctrl+O

Debug output shows which hooks matched, exit codes, and full stdout/stderr.

For more granular matcher details: CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose.

Troubleshooting

ProblemCauseFix
Hook not runningWrong matcher patternCheck case-sensitivity; run /hooks to confirm registration
Command not foundRelative path in commandUse ${CLAUDE_PROJECT_DIR} or exec form with args
JSON not processedNon-zero exit codeExit 0 for JSON output; use exit 2 only for blocking
Hook times outScript too slowOptimize or increase timeout field
Stop hook loopsMissing stop_hook_active checkCheck stop_hook_active in Stop input; exit 0 when true
Stop hook runs inside subagents unexpectedlyMissing agent_id guardCheck data.agent_id in Stop hooks; exit 0 when present
JSON parse errorShell profile printing textWrap profile echo in if [[ $- == *i* ]] guard
Plugin hook not loadingInvalid hooks.jsonRun claude plugin validate .

Test Commands Manually

echo '{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"npm test"}}' | ./your-hook.sh

Sources

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

Add automated documentation updater to any Claude skill. Creates a Python sync script that downloads upstream docs, processes markdown for AI consumption, and maintains local cache with configurable refresh. Collects template variables, then delegates implementation through 5-phase workflow. Use when adding auto-updating reference documentation to plugins or skills.

日本語の概要は準備中です。原文の説明を表示しています。

Jamie-BitFlight/claude_skills672026年10月9日 更新

SAM-style feature initiation workflow — discovery through codebase analysis, architecture spec, task decomposition, validation, and context manifest. Use when a user asks to add a feature, plan a feature, or convert an idea into an executable SAM plan.

日本語の概要は準備中です。原文の説明を表示しています。

Jamie-BitFlight/claude_skills672026年10月9日 更新

Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to "open a website", "fill out a form", "click a button", "take a screenshot", "scrape data from a page", "test this web app", "login to a site", "automate browser actions", or any task requiring programmatic web interaction.

日本語の概要は準備中です。原文の説明を表示しています。

Jamie-BitFlight/claude_skills672026年10月9日 更新

Browser automation for AI agents using the agent-browser CLI and Playwright. Use when navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, logging into sites, or automating any browser task. Triggers on "open a website", "fill out a form", "click a button", "scrape data", "test this web app", "automate browser actions", or any programmatic web interaction request.

日本語の概要は準備中です。原文の説明を表示しています。

Jamie-BitFlight/claude_skills672026年10月9日 更新

Runs the description-drift experiment — spawns all Claude Code agents simultaneously to collect self-reported capabilities, then compares them against static frontmatter descriptions to reveal how reliable orchestrator routing based on descriptions actually is. Use when measuring description drift across the agent fleet, re-running the capability collection experiment, analyzing a specific agent's self-reported capabilities, or auditing whether frontmatter descriptions accurately reflect agent behavior.

日本語の概要は準備中です。原文の説明を表示しています。

Jamie-BitFlight/claude_skills672026年10月9日 更新

Create or adapt Claude Code agent definitions. Use when creating an agent, changing subagent configuration, selecting agent scope, or designing a specialized delegation role.

日本語の概要は準備中です。原文の説明を表示しています。

Jamie-BitFlight/claude_skills672026年10月9日 更新

Jamie-BitFlight のスキルをすべて見る

このスキルの問題を報告する