Hook Development for Claude Code Plugins
anthropics/claude-plugins-official
Explains how to write Claude Code plugin hooks, both prompt-based checks and bash commands, for events such as PreToolUse, Stop and SessionStart.
How to write Claude Code hooks: events, matchers, blocking vs advisory, paths.
$ npx skills add xiaolai/nlpm --skill writing-hooks -a claude-codeProject install by default; add -g for ~/.claude/skills/.
$ gh skill install xiaolai/nlpm writing-hooks --agent claude-codeProject scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).
$ git clone --depth 1 https://github.com/xiaolai/nlpm.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/nlpm/writing-hooks .claude/skills/writing-hooks && rm -rf skills-srcUse ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.
Claude Code skills documentation · loads skills from .claude/skills/
Install the "writing-hooks" agent skill from https://github.com/xiaolai/nlpm/tree/main/skills/nlpm/writing-hooks into .claude/skills/writing-hooks/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "writing-hooks", then confirm the skill loads.Claude Code copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$skill-installer install https://github.com/xiaolai/nlpm/tree/main/skills/nlpm/writing-hooksType this inside Codex. $skill-installer <name> installs a curated skill from openai/skills. The installer writes to $CODEX_HOME/skills (default ~/.codex/skills). Restart Codex if the skill does not show up.
$ npx skills add xiaolai/nlpm --skill writing-hooks -a codexProject install goes to .agents/skills/; add -g for ~/.codex/skills/.
$ gh skill install xiaolai/nlpm writing-hooks --agent codexProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/xiaolai/nlpm.git skills-src && mkdir -p .agents/skills && cp -r skills-src/skills/nlpm/writing-hooks .agents/skills/writing-hooks && rm -rf skills-srcUse ~/.agents/skills/ instead of .agents/skills for a personal install.
Codex skills documentation · loads skills from .agents/skills/
Install the "writing-hooks" agent skill from https://github.com/xiaolai/nlpm/tree/main/skills/nlpm/writing-hooks into .agents/skills/writing-hooks/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "writing-hooks", then confirm the skill loads.Codex copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add xiaolai/nlpm --skill writing-hooks -a cursorProject install goes to .agents/skills/; add -g for ~/.cursor/skills/.
$ gh skill install xiaolai/nlpm writing-hooks --agent cursorProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/xiaolai/nlpm.git skills-src && mkdir -p .cursor/skills && cp -r skills-src/skills/nlpm/writing-hooks .cursor/skills/writing-hooks && rm -rf skills-srcUse ~/.cursor/skills/ instead of .cursor/skills for a personal install.
Cursor skills documentation · loads skills from .cursor/skills/, .agents/skills/, .claude/skills/, .codex/skills/
Install the "writing-hooks" agent skill from https://github.com/xiaolai/nlpm/tree/main/skills/nlpm/writing-hooks into .cursor/skills/writing-hooks/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "writing-hooks", then confirm the skill loads.Cursor copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gemini skills install https://github.com/xiaolai/nlpm.git --path skills/nlpm/writing-hooks--scope user (default) or --scope workspace; --path is the subfolder of the repo that holds the skill; --consent skips the security confirmation prompt.
$ npx skills add xiaolai/nlpm --skill writing-hooks -a gemini-cliProject install goes to .agents/skills/; add -g for ~/.gemini/skills/.
$ gh skill install xiaolai/nlpm writing-hooks --agent gemini-cliProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/xiaolai/nlpm.git skills-src && mkdir -p .gemini/skills && cp -r skills-src/skills/nlpm/writing-hooks .gemini/skills/writing-hooks && rm -rf skills-srcUse ~/.gemini/skills/ instead of .gemini/skills for a personal install, then run /skills reload.
Gemini CLI skills documentation · loads skills from .gemini/skills/, .agents/skills/
Install the "writing-hooks" agent skill from https://github.com/xiaolai/nlpm/tree/main/skills/nlpm/writing-hooks into .gemini/skills/writing-hooks/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "writing-hooks", then confirm the skill loads.Gemini CLI copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gh skill install xiaolai/nlpm writing-hooksInstalls for Copilot at project scope by default; add --scope user for a personal install. Preview a skill first with gh skill preview. Needs GitHub CLI 2.90.0 or later (public preview).
$ npx skills add xiaolai/nlpm --skill writing-hooks -a github-copilotProject install goes to .agents/skills/; add -g for ~/.copilot/skills/.
$ git clone --depth 1 https://github.com/xiaolai/nlpm.git skills-src && mkdir -p .github/skills && cp -r skills-src/skills/nlpm/writing-hooks .github/skills/writing-hooks && rm -rf skills-srcUse ~/.copilot/skills/ instead of .github/skills for a personal install. Commit .github/skills so cloud agent and code review can use it.
GitHub Copilot skills documentation · loads skills from .github/skills/, .claude/skills/, .agents/skills/
Install the "writing-hooks" agent skill from https://github.com/xiaolai/nlpm/tree/main/skills/nlpm/writing-hooks into .github/skills/writing-hooks/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "writing-hooks", then confirm the skill loads.GitHub Copilot copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add xiaolai/nlpm --skill writing-hooks -a opencodeOpenCode documents no install command of its own. Project install goes to .agents/skills/; add -g for ~/.config/opencode/skills/.
$ gh skill install xiaolai/nlpm writing-hooks --agent opencodeProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/xiaolai/nlpm.git skills-src && mkdir -p .opencode/skills && cp -r skills-src/skills/nlpm/writing-hooks .opencode/skills/writing-hooks && rm -rf skills-srcUse ~/.config/opencode/skills/ instead of .opencode/skills for a personal install.
OpenCode skills documentation · loads skills from .opencode/skills/, .claude/skills/, .agents/skills/
Install the "writing-hooks" agent skill from https://github.com/xiaolai/nlpm/tree/main/skills/nlpm/writing-hooks into .opencode/skills/writing-hooks/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "writing-hooks", then confirm the skill loads.OpenCode copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
writing-hooksHow to write Claude Code hooks: events, matchers, blocking vs advisory, paths.
Writing Hooks is an agent skill from xiaolai/nlpm. How to write Claude Code hooks: events, matchers, blocking vs advisory, paths.
Its SKILL.md is about 2.9k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.
It sits in Agent Workflows, covering Hooks and plugins. The repository describes itself as: Natural-Language Programming Manager — scan, lint, and score NL artifacts with Claude-native quality scoring. The licence is ISC.
8 steps, taken from the step headings in SKILL.md.
Read from SKILL.md and the folder at commit 6fdbd05. It shows what the files ask for, not the result of running them.
Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.
From allowed-tools in the SKILL.md frontmatter.
Shell commands in SKILL.md call:
jqFrom the folder's file list and the shell code blocks in SKILL.md.
No URLs in SKILL.md.
From URLs in SKILL.md, links to its own repository left out.
Names no API keys, tokens, secrets or passwords.
From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.
Writing Hooks loads about 2.9k tokens when it runs. Until then it costs about 23 tokens; SKILL.md has 1,019 words of instructions outside code blocks.
Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.
The automated check found no risky patterns in SKILL.md.
Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.
The full file from xiaolai/nlpm at commit 6fdbd05, republished under its ISC licence (© xiaolai). 1,019 words, ~2,933 tokens.
.claude/skills/writing-hooks/SKILL.md (or your agent's skills folder).Scope: covers Claude Code
hooks.jsonauthoring and hook script design. Hook event vocabularies are per-tool and NOT 1:1 mappable (nlpm design decision #4): Claude usesPreToolUse/PostToolUse/Stop/etc.; Codex overlaps with Claude plusPostCompact/SubagentStart; Antigravity/Gemini uses a differentBefore*/After* Agent/Model/Tooldecomposition. The hook-script design principles here (idempotency, fail-open, exit codes, portable paths) transfer across tools; the event names and config locations do not. For the authoritative per-tool event tables see [[nlpm:conventions-claude]] §7, [[nlpm:conventions-codex]] §6, [[nlpm:conventions-antigravity]] §5. For plugin architecture, see [[writing-plugins]]. For rules (which are simpler but static), see [[writing-rules]].
Notation: $+{CLAUDE_PLUGIN_ROOT} in this file is Claude Code's plugin-root variable, split by a + so Claude Code does not replace it with a path when it loads this skill; the real token has no + (nlpm:conventions-claude §2.4).
| Type | What it does | When to use | Complexity |
|---|---|---|---|
command | Runs a shell script, reads JSON from stdin | Deterministic checks: file existence, JSON validation, regex matching | Medium |
prompt | Injects text into Claude's context | Advisory: reminders, context injection, style guidance | Low |
agent | Spawns a verification agent | Complex verification: code quality, semantic analysis, multi-file checks | High |
Is the check deterministic (regex, file exists, JSON schema)?
YES --> command hook (shell script)
NO --> Does it need AI judgment?
YES --> agent hook
NO --> prompt hook (context injection){
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "$+{CLAUDE_PLUGIN_ROOT}/scripts/check-loc.sh",
"timeout": 10000
}
]
}
]
}
}Hook script receives JSON on stdin with tool name and parameters. It outputs JSON to stdout.
{
"hooks": {
"UserPromptSubmit": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Remember: this project uses Result<T, E> for error handling. Never use try/catch directly."
}
]
}
]
}
}{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "agent",
"agent": "Verify the written file follows project conventions. Check: import order, export style, naming conventions. Report any violations."
}
]
}
]
}
}The hook prevents the tool from executing. Use for hard quality gates.
Script output for blocking:
{
"hookSpecificOutput": {
"permissionDecision": "deny",
"permissionDecisionReason": "File exceeds 300 LOC limit (current: 342). Extract logic before writing."
}
}When to block:
The hook adds a message to Claude's context after the action completes. Use for suggestions and reminders.
Script output for advisory:
{
"hookSpecificOutput": {
"message": "The file you just edited has no tests. Consider adding tests in __tests__/."
}
}When to advise:
| Situation | Block or Advise? | Rationale |
|---|---|---|
| Test failure on commit | Block | Broken tests should never be committed |
| File over LOC limit | Block | Enforce hard limit |
| Missing JSDoc on export | Advise | Nice to have, not a hard requirement |
| No tests for new file | Advise | Reminder, not a gate |
| Force push to main | Block | Destructive, irreversible |
| Large file creation (>500 lines) | Advise | Might be intentional (generated code) |
Rule of thumb: block only what you would reject in a code review. Advise on everything else.
| Event | When it fires | Common use cases |
|---|---|---|
PreToolUse | Before a tool executes | Block dangerous operations, validate inputs, check preconditions |
PostToolUse | After a tool succeeds | Trigger follow-up actions, lint changed files, update state |
PostToolUseFailure | After a tool fails | Error recovery, suggest alternatives, log failures |
UserPromptSubmit | When user sends a message | Context injection, session setup, mode activation |
Stop | When Claude stops responding | Cleanup, summary generation, state persistence |
SessionStart | Session begins | Environment validation, context loading, config checks |
| Goal | Event | Hook type |
|---|---|---|
| Prevent bad writes | PreToolUse + matcher Write|Edit | command |
| Lint after edit | PostToolUse + matcher Write|Edit | command |
| Inject project context | UserPromptSubmit | prompt |
| Validate environment on start | SessionStart | command |
| Save session summary on exit | Stop | agent |
| Recover from failed bash commands | PostToolUseFailure + matcher Bash | prompt |
The matcher field uses regex to match tool names. It applies only to PreToolUse, PostToolUse, and PostToolUseFailure events.
| Pattern | Matches | Use case |
|---|---|---|
"Bash" | Bash tool only | Guard shell commands |
"Write|Edit" | Write or Edit | Guard file modifications |
"Write" | Write only | Guard new file creation |
"Edit" | Edit only | Guard file edits (not creation) |
"Read" | Read tool | Track what files Claude reads |
"mcp__.*" | All MCP tool calls | Guard external integrations |
"mcp__github__.*" | GitHub MCP tools | Guard GitHub operations |
"Task" | Task tool (agent dispatch) | Monitor agent dispatching |
".*" | Everything | Use carefully -- fires on every tool call |
Before deploying, verify your matcher with test cases:
| Matcher | Should match | Should NOT match |
|---|---|---|
"Write|Edit" | Write, Edit | Bash, Read, WriteFile |
"Bash" | Bash | BashScript, mcp__bash |
"mcp__github__.*" | mcp__github__create_pr | mcp__slack__send |
Always use $+{CLAUDE_PLUGIN_ROOT} for script paths in hooks.json. This variable resolves to the plugin's installation directory at runtime.
{
"command": "$+{CLAUDE_PLUGIN_ROOT}/scripts/check-loc.sh"
}{
"command": "/Users/joker/.claude/plugins/cache/xiaolai/my-plugin/0.1.0/scripts/check-loc.sh"
}my-plugin/
hooks/
hooks.json # hook definitions
scripts/
check-loc.sh # hook scripts
validate-config.sh
lint-output.shEvery hook script must have:
#!/bin/bash or #!/usr/bin/env nodechmod +x scripts/*.sh#!/bin/bash
# Read input from stdin
input=$(cat)
# Debug logging goes to stderr
echo "Hook triggered: $(date)" >&2
# Business logic
file_path=$(echo "$input" | jq -r '.toolInput.file_path // empty')
if [ -z "$file_path" ]; then
# Allow if we can't determine the file
echo '{"hookSpecificOutput":{"decision":"allow"}}'
exit 0
fi
loc=$(wc -l < "$file_path" 2>/dev/null || echo "0")
if [ "$loc" -gt 300 ]; then
echo "{\"hookSpecificOutput\":{\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"File has $loc lines, exceeds 300 LOC limit\"}}"
else
echo '{"hookSpecificOutput":{"decision":"allow"}}'
fiWhat happens when your hook script crashes?
If the script crashes, allow the action. Safer for advisory hooks and non-critical checks.
#!/bin/bash
# Fail-open wrapper
set +e # Don't exit on error
result=$(your_check_logic 2>/dev/null)
exit_code=$?
if [ $exit_code -ne 0 ]; then
# Script failed -- allow the action (fail-open)
echo '{"hookSpecificOutput":{"decision":"allow"}}'
exit 0
fi
# Normal processing...
echo "$result"If the script crashes, deny the action. Use only for critical security gates.
#!/bin/bash
# Fail-closed wrapper
set +e
result=$(your_check_logic 2>/dev/null)
exit_code=$?
if [ $exit_code -ne 0 ]; then
# Script failed -- deny the action (fail-closed)
echo '{"hookSpecificOutput":{"permissionDecision":"deny","permissionDecisionReason":"Safety check script failed -- blocking action as precaution"}}'
exit 0
fi
# Normal processing...
echo "$result"| Hook purpose | Fail mode | Rationale |
|---|---|---|
| LOC limit enforcement | Fail-open | Better to allow a large file than block all writes |
| Style reminder | Fail-open | Non-critical advisory |
| Prevent force push to main | Fail-closed | Destructive action, err on side of caution |
| Secret detection | Fail-closed | Security-critical, must not leak |
| Test runner | Fail-open | Test infra failures shouldn't block development |
| Mistake | Why it's wrong | Fix |
|---|---|---|
Blocking on PostToolUse | Action already happened -- too late to block | Use PreToolUse for blocking |
| Wrong event case | pretooluse instead of PreToolUse -- case-sensitive | Use exact case: PreToolUse, PostToolUse, etc. |
| Script not executable | Hook fails silently | Run chmod +x scripts/*.sh |
| Missing shebang | Script may run with wrong interpreter | Add #!/bin/bash or #!/usr/bin/env node |
| Hardcoded paths | Breaks on other machines | Use $+{CLAUDE_PLUGIN_ROOT} |
| stdout pollution | Debug output mixed into JSON response | Use stderr for logging: echo "debug" >&2 |
| No timeout | Slow script blocks Claude indefinitely | Set "timeout": 10000 (10 seconds) |
Matcher too broad (".*") | Fires on every tool call, performance impact | Narrow to specific tools |
| No fail-open wrapper | Script crash = broken hook = frustrated user | Wrap in fail-open try/catch |
Before deploying hooks, verify:
PreToolUse, not PostToolUse$+{CLAUDE_PLUGIN_ROOT}© xiaolai, ISC. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file
Just SKILL.md in skills/nlpm/writing-hooks of xiaolai/nlpm.
Open the folder on GitHubat commit 6fdbd05
Writing Hooks next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.
| Skill | Stars | Used in | Tokens | Auto-check | Licence | Repo updated |
|---|---|---|---|---|---|---|
| Writing Hooks this skillxiaolai/nlpm | 146 | — | ~2.9k | Automated safety check: Pass | ISC | |
| Hook Development for Claude Code Pluginsanthropics/claude-plugins-official | 38k | 11 repos | ~4.1k | Automated safety check: Notes | Apache-2.0 | |
| Claude Code Agent Developmentanthropics/claude-plugins-official | 38k | 8 repos | ~2.8k | Automated safety check: Pass | Apache-2.0 | |
| Claude Code Skill Developer Guidediet103/claude-code-infrastructure-showcase | 10k | 11 repos | ~3.5k | Automated safety check: Pass | MIT | |
| Plugin Settings Patternanthropics/claude-plugins-official | 38k | 7 repos | ~3k | Automated safety check: Pass | Apache-2.0 | |
| MCP Integration for Pluginsanthropics/claude-plugins-official | 38k | 11 repos | ~3.1k | Automated safety check: Pass | Apache-2.0 |
anthropics/claude-plugins-official
Explains how to write Claude Code plugin hooks, both prompt-based checks and bash commands, for events such as PreToolUse, Stop and SessionStart.
anthropics/claude-plugins-official
Explains how to write agents for Claude Code plugins: the markdown file with YAML frontmatter, trigger descriptions, model and color settings, and system prompt design.
diet103/claude-code-infrastructure-showcase
A guide to creating and managing Claude Code skills with auto-activation: skill-rules.json triggers, hooks, enforcement levels, YAML frontmatter and progressive disclosure.
anthropics/claude-plugins-official
Shows how Claude Code plugins keep per-project settings and state in .claude/plugin-name.local.md files with YAML frontmatter and a markdown body.
anthropics/claude-plugins-official
Explains how to bundle Model Context Protocol servers in a Claude Code plugin, covering config files, stdio, SSE, HTTP and WebSocket server types, and authentication.
anthropics/claude-plugins-official
Explains how to write Claude Code slash commands: Markdown files with YAML frontmatter, arguments, file references, bash context and interactive prompts.
xiaolai/nlpm
Universal NL conventions: SKILL.md open spec, AGENTS.md, vague quantifiers, naming.
xiaolai/nlpm
Antigravity and Gemini CLI artifact schemas: .gemini/ paths, extensions, hooks.
xiaolai/nlpm
Codex CLI artifact schemas: config.toml, .codex-plugin, skills, hooks, AGENTS.md.
xiaolai/nlpm
Multi-agent workflow patterns: parallel dispatch, pipelines, QC gates, retries.
xiaolai/nlpm
NL artifact anti-patterns: vague quantifiers, bare prohibitions, oversized skills.
xiaolai/nlpm
100-point NL artifact rubric: penalty tables per artifact type, calibration cases.
Categories
How to write Claude Code hooks: events, matchers, blocking vs advisory, paths. Writing Hooks is an agent skill from xiaolai/nlpm. How to write Claude Code hooks: events, matchers, blocking vs advisory, paths.
Writing Hooks fits situations like: tasks that involve Hooks and plugins.
Run `npx skills add xiaolai/nlpm --skill writing-hooks -a claude-code`. Or copy the skill folder (skills/nlpm/writing-hooks in xiaolai/nlpm) into .claude/skills/writing-hooks in your project. Claude Code loads it when a task matches its description.
Run `npx skills add xiaolai/nlpm --skill writing-hooks -a codex`. Or copy the skill folder (skills/nlpm/writing-hooks in xiaolai/nlpm) into .agents/skills/writing-hooks in your project. Codex loads it when a task matches its description.
Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add xiaolai/nlpm --skill writing-hooks -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/writing-hooks, .gemini/skills/writing-hooks, .github/skills/writing-hooks and .opencode/skills/writing-hooks in your project.
Going by SKILL.md and its folder, Writing Hooks needs the command-line tools its instructions call (jq).
SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.
Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.
Writing Hooks is published under the ISC licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.
About 2.9k tokens (SKILL.md is roughly 12k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.
Skills that share tags, products or a category with Writing Hooks: Hook Development for Claude Code Plugins (anthropics/claude-plugins-official, 38k stars), Claude Code Agent Development (anthropics/claude-plugins-official, 38k stars), Claude Code Skill Developer Guide (diet103/claude-code-infrastructure-showcase, 10k stars) and Plugin Settings Pattern (anthropics/claude-plugins-official, 38k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.
xiaolai (a GitHub user) maintains it in xiaolai/nlpm, which has 146 GitHub stars. The repository holds 15 skills in this directory. The repository was last updated on October 8, 2026.
Source: xiaolai/nlpm on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.