- name
SKILL.md
El archivo de la skill permanece en el repositorio del publicador.
Pega el comando copiado en una terminal. Instala este SKILL.md en ese agente.
npx skills add athola/claude-night-market --skill hook-authoring -a cursor -yPega el comando copiado en una terminal. Instala este SKILL.md en ese agente.
npx skills add athola/claude-night-market --skill hook-authoring -a claude-code -yPega el comando copiado en una terminal. Instala este SKILL.md en ese agente.
npx skills add athola/claude-night-market --skill hook-authoring -a codex -yPega el comando copiado en una terminal. Instala este SKILL.md en ese agente.
npx skills add athola/claude-night-market --skill hook-authoring -a grok -yEnvía el mensaje copiado en un chat de Grok Bot. El Bot obtiene este SKILL.md de GitHub y lo añade a las skills que comparten todos tus Bots.
Install this skill: https://github.com/athola/claude-night-market/tree/HEAD/plugins/abstract/skills/hook-authoringDel publicador
abstract:hooks-eval)abstract:hook-scope-guide)abstract:skill-authoring)Hooks are event interceptors that allow you to extend Claude Code and Claude Agent SDK behavior by executing custom logic at specific points in the agent lifecycle. They enable validation before tool use, logging after actions, context injection, workflow automation, and security enforcement.
This skill teaches you how to write effective, secure, and performant hooks for both declarative JSON (Claude Code) and programmatic Python (Claude Agent SDK) use cases.
New in 2.1.9: PreToolUse hooks can now return
additionalContextto inject information before a tool executes. This enables patterns like cache hints, security warnings, or relevant context injection.
Create a simple logging hook in .claude/settings.json:
{
"PostToolUse": [
{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "echo \"$(date): Executed $(jq -r '.tool_name')\" >> ~/.claude/audit.log"
}]
}
]
}
Note: Use string matchers ("Bash") not object matchers ({"toolName": "Bash"}).
This logs every Bash command execution with a timestamp.
Create a validation hook using the SDK:
from claude_agent_sdk import AgentHooks
class ValidationHooks(AgentHooks):
async def on_pre_tool_use(self, tool_name: str, tool_input: dict) -> dict | None:
"""Validate tool inputs before execution."""
if tool_name == "Bash":
command = tool_input.get("command", "")
if "rm -rf /" in command:
raise ValueError("Dangerous command blocked by hook")
# Return None to proceed unchanged, or modified dict to transform
return None
Quick reference for the events most plugins use. Every event also
receives the common fields (session_id, transcript_path, cwd,
hook_event_name, and permission_mode where it applies). The full
roster of 33 events is plugins/abstract/src/abstract/hook_events.py,
and each event's input is in code.claude.com/docs/en/hooks.
The SessionStart hook receives JSON input via stdin with these fields:
{
"session_id": "abc123",
"source": "startup",
"agent_type": "my-agent"
}
Fields: source is one of "startup", "resume", "clear", or "compact". agent_type is populated when the --agent flag is used.
agent_type field: When Claude Code is launched with --agent my-agent, this field contains the agent name. Use it for agent-specific initialization:
# Python example: Agent-aware SessionStart hook
input_data = json.loads(sys.stdin.read())
agent_type = input_data.get("agent_type", "")
if agent_type in ["code-reviewer", "quick-query"]:
# Skip heavy context injection for lightweight agents
print(json.dumps({"hookSpecificOutput": {"additionalContext": "Minimal context"}}))
else:
# Full initialization for implementation agents
print(json.dumps({"hookSpecificOutput": {"additionalContext": full_context}}))
# Bash example: Agent-aware SessionStart hook
HOOK_INPUT=$(cat)
AGENT_TYPE=$(echo "$HOOK_INPUT" | jq -r '.agent_type // empty')
case "$AGENT_TYPE" in
code-reviewer|quick-query)
echo '{"hookSpecificOutput": {"additionalContext": "Minimal context"}}'
;;
*)
echo '{"hookSpecificOutput": {"additionalContext": "Full context"}}'
;;
esac
New in 2.1.0: Define hooks directly in skill, command, or agent frontmatter. These hooks are scoped to the component's lifecycle.
---
name: validated-skill
description: Skill with lifecycle hooks
hooks:
PreToolUse:
- matcher: "Bash"
command: "./validate-command.sh"
once: true # NEW: Run only once per session
- matcher: "Write|Edit"
command: "./pre-edit-check.sh"
PostToolUse:
- matcher: "Write|Edit"
command: "./format-on-save.sh"
Stop:
- command: "./cleanup-and-report.sh"
---
once: true ConfigurationNew in 2.1.0: Use once: true to execute a hook only once per session, ideal for:
hooks:
PreToolUse:
- matcher: "Bash"
command: "./setup-environment.sh"
once: true # Runs only on first Bash call
SessionStart:
- command: "./initialize-session.sh"
once: true # Runs only once at session start
PreToolUse hooks can now return updatedInput when returning ask permission decision. A hook can then act as middleware while still requesting user consent:
{
"decision": "ask",
"updatedInput": {
"command": "modified-command --safe-flag"
}
}
Declarative configuration in .claude/settings.json, project .claude/settings.json, or plugin hooks/hooks.json:
{
"PreToolUse": [
{
"matcher": "Edit",
"hooks": [{
"type": "command",
"command": "echo 'WARNING: Editing production file' >&2"
}]
}
]
}
Important: Use string matchers (regex patterns), not object matchers. The object format {"toolName": "Edit"} is deprecated.
Matcher patterns:
"Edit" - Match single tool"Read|Write|Edit" - Match multiple tools (regex OR)".*" - Match all toolsPros: Simple, no code required, easy to version control Cons: Limited logic capabilities, shell command only
New in 2.1.63: Hooks can POST JSON to a URL and receive JSON responses instead of running shell commands. Use "type": "http" with a "url" field:
{
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [{
"type": "http",
"url": "https://my-service.example.com/hooks/validate-bash"
}]
}
]
}
The hook POSTs the standard hook input as JSON and expects a standard hook response JSON body.
When to use HTTP hooks over command hooks:
Pros: No local scripts needed, centralized logic, works in sandboxed environments Cons: Network latency, requires running HTTP service, external dependency
Programmatic callbacks using the AgentHooks base class, for logic
that needs full Python, complex validation or state. The base class,
callback signatures and implementation patterns are in
modules/sdk-callbacks.md.
Permission rules now correctly match commands prefixed with environment variable assignments. Before 2.1.38, NODE_ENV=production npm test would not match a rule for Bash(npm *).
# These now all match `Bash(npm *)`:
npm test
NODE_ENV=production npm test
FORCE_COLOR=1 CI=true npm test
When writing PreToolUse hooks that inspect bash commands, be aware that the permission system strips env var prefixes for matching, but your hook receives the full command string including prefixes.
Claude Code now validates heredoc delimiters to prevent command smuggling. The recommended pattern <<'EOF' (single-quoted) remains the safest approach. Always use single-quoted delimiters in heredoc patterns to prevent variable expansion.
Validate tool input, never log secrets, respect sandbox boundaries,
fail safe, rate-limit and sanitize logged content. The six rules and a
secret-redacting logging hook are in modules/security-essentials.md.
Keep hooks non-blocking and fail fast. The hook timeout is 10 minutes
(increased from 60s in 2.1.3), and most hooks should finish in under
30s. Budgets, async I/O, batching, bounded state and profiling are in
modules/performance-guidelines.md.
Plugin hooks are in hooks/hooks.json, which auto-loads when the
plugin is enabled. Listing it again in plugin.json causes duplicate
load errors. Project hooks are in .claude/settings.json and
global hooks in ~/.claude/settings.json. The decision framework is
modules/scope-selection.md, also served as abstract:hook-scope-guide.
Validation, logging, context injection and PreToolUse
additionalContext injection (2.1.9+) are written out in
modules/common-patterns.md.
Unit-test each callback directly: assert a dangerous input raises and a
safe input returns None. Test categories, fixtures and the security
test checklist are in modules/testing-hooks.md.
Hooks communicate decisions to Claude Code via exit codes:
Use exit code 2 to block an action and display a message to the user:
#!/bin/bash
# Example: Block force pushes with user-facing message
command=$(echo "$1" | jq -r '.tool_input.command // empty')
if echo "$command" | grep -q 'push.*--force'; then
echo "Force push blocked: use --force-with-lease instead" >&2
exit 2
fi
exit 0
Important: Before Claude Code 2.1.39, stderr from exit code 2 was silently swallowed (#10964). Users would see a generic "hook error" instead of the custom message. This is now fixed: stderr is properly displayed to the user.
Plugin hooks: Before 2.1.39, plugin-installed hooks had a separate code path that also failed to show stderr for exit code 2 (#10412). Both plugin and project hooks now work correctly.
FORCE_AUTOUPDATE_PLUGINSForces plugin auto-update even when the main Claude Code auto-updater is disabled.
Use cases:
# Enable forced plugin updates
export FORCE_AUTOUPDATE_PLUGINS=1
claude
# Or inline
FORCE_AUTOUPDATE_PLUGINS=1 claude --agent my-agent
Note: This only affects plugin updates, not Claude Code core updates.
Hook not firing Verify hook pattern matches the event. Check hook logs for errors
Syntax errors Validate JSON/Python syntax before deployment
Permission denied Check hook file permissions and ownership
Hook blocking message not shown (pre-2.1.39) If using exit code 2 to block with a user-facing message and the message is not appearing, upgrade to Claude Code 2.1.39+. In older versions, use exit 0 with stdout as a workaround.
For detailed guidance on specific topics:
modules/hook-types.md - Detailed event signatures and parametersmodules/sdk-callbacks.md - Python SDK implementation patternsmodules/security-essentials.md - security
rules and a secret-redacting hookmodules/common-patterns.md - validation, logging
and context injection hooksmodules/performance-guidelines.md - Optimization techniquesmodules/scope-selection.md - Choosing plugin/project/globalmodules/testing-hooks.md - Testing strategies and fixturesmodules/observability-warnings.md - Copy-pasteable resolution pattern for binary-actionable drift hooksplugins/abstract/scripts/hook_validator.py)hook_validator.py before deploymenthooks/hooks.json,
.claude/settings.json, or ~/.claude/settings.json) with correct JSON or Python syntax.api[_-]?key, password,
token, secret, or credential appear in log output paths.abstract:validate-hook is available, it exits 0 on the authored hook file.Guide creating Claude Code hooks with security-first design. Use for validation and enforcement.
---name: hook-authoringdescription: Guide creating Claude Code hooks with security-first design. Use for validation and enforcement.---# plugins/abstract/skills/hook-authoring/SKILL.mdPreguntas frecuentes
Descarga plugins/abstract/skills/hook-authoring/SKILL.md desde el publicador, o copia la ruta y abre el repositorio. PlugMCP lista la skill y no aloja el archivo.
El publicador lo mantiene en https://github.com/athola/claude-night-market.
Claude, Cursor, Codex y Grok Build pueden leer un SKILL.md que añadas desde el repositorio del publicador. Grok Bot lo instala cuando envías en un chat el enlace a la carpeta de la skill en GitHub.
| Task marked complete |
task_id, task_subject, task_description |
| Coordination, chaining, reporting |
| PreCompact | Before context compact | trigger, custom_instructions | State preservation, checkpointing |
| SessionStart | Session starts/resumes | source, model, agent_type | Initialization, context loading |
| SessionEnd | Session terminates | reason | Cleanup, final logging |
| WorktreeCreate | Agent worktree created | name | Custom VCS setup, symlink .venv, pre-populate caches |
| WorktreeRemove | Agent worktree removed | worktree_path | Cleanup temp files, teardown worktree-scoped resources |