Hook authoring

From athola/claude-night-market · View interactive version

Hook authoring is an AI agent skill from the GitHub repository athola/claude-night-market. Guide creating Claude Code hooks with security-first design. Use for validation and enforcement.

How to use this skill

Skill file

When NOT To Use

Hook Authoring Guide

Overview

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.

Key Capabilities

New in 2.1.9: PreToolUse hooks can now return additionalContext to inject information before a tool executes. This enables patterns like cache hints, security warnings, or relevant context injection.

Quick Start

Your First Hook (JSON - Claude Code)

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.

Your First Hook (Python - Claude Agent SDK)

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

Hook Event Types

Every event, its matcher and its input fields, including the

SessionStart input schema, are in modules/hook-types.md.

Hooks in Frontmatter (Claude Code 2.1.0+)

New in 2.1.0: Define hooks directly in skill, command, or agent frontmatter. These hooks are scoped to the component's lifecycle.

Skill/Command/Agent Frontmatter Hooks

---
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"
---

The `once: true` Configuration

New 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

Frontmatter vs Settings Hooks

| Aspect | Frontmatter Hooks | Settings Hooks |

|--------|-------------------|----------------|

| Scope | Component lifecycle | Global/project |

| Location | In skill/agent/command | settings.json |

| Persistence | Active only when component runs | Always active |

| Use case | Component-specific validation | Cross-cutting concerns |

PreToolUse updatedInput (2.1.0 Fix)

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"
  }
}

Since 2.1.300 the harness validates updatedInput the way it validates

Claude's own input. Unknown keys are dropped and invalid input denies

the call. Return only the tool's real parameters.

Failing Closed (2.1.295)

A command or HTTP hook that fails to start, times out, or exits

unexpectedly lets the action through by default. Set

"onFailure": "block" on the hook entry, beside command, to block

the action instead. Use it for guards whose silence would be unsafe.

On the matcher group the key is ignored and the hook fails open.

Claude Code vs SDK

JSON Hooks (Claude Code)

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:

Pros: Simple, no code required, easy to version control

Cons: Limited logic capabilities, shell command only

HTTP Hooks (Claude Code 2.1.63+)

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

Python SDK Hooks

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.

Bash Permission Matching Notes

Environment Variable Wrappers (2.1.38+)

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.

Heredoc Delimiter Security (2.1.38+)

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.

Security Essentials

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.

Performance Guidelines

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.

Scope Selection

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.

Common Patterns

Validation, logging, context injection and PreToolUse

additionalContext injection (2.1.9+) are written out in

modules/common-patterns.md.

Testing Hooks

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.

Hook Exit Codes

Hooks communicate decisions to Claude Code via exit codes:

| Exit Code | Meaning | stdout | stderr |

|-----------|---------|--------|--------|

| 0 | Success/allow | Shown to Claude as system context | Ignored |

| 2 | Block/deny | Ignored | Shown to user as explanation (2.1.39+ fix) |

| Other | Error | Ignored | Shown to user as error message |

Blocking with Exit Code 2 (2.1.39+)

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.

Environment Variables (Claude Code 2.1.2+)

`FORCE_AUTOUPDATE_PLUGINS`

Forces 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.

Troubleshooting

Common Issues

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.

Module References

For detailed guidance on specific topics:

rules and a secret-redacting hook

and context injection hooks

Tools

plugins/abstract/scripts/hook_validator.py)

Related Skills

Next Steps

  1. Choose your hook type (JSON vs SDK) based on complexity needs
  2. Select the appropriate scope (plugin/project/global)
  3. Implement following security and performance best practices
  4. Test thoroughly with unit and integration tests
  5. Validate using hook_validator.py before deployment

References

Exit Criteria

.claude/settings.json, or ~/.claude/settings.json) with correct JSON or Python syntax.

the hook command or callback without error.

token, secret, or credential appear in log output paths.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.