Cc hooks creator

From frank-luongt/faos-skills-marketplace · View interactive version

Cc hooks creator is an AI agent skill from the GitHub repository frank-luongt/faos-skills-marketplace. Create, configure, and debug Claude Code hooks -- shell commands that execute at lifecycle events (PreToolUse, PostToolUse, Stop, SessionStart, etc.). Use when building file protection, code formatting, notifications, context loading, or any automation triggered by Claude Code events. Covers inline

How to use this skill

Skill file

<!-- AUTO-GENERATED by export-skills.py — DO NOT EDIT -->


name: cc-hooks-creator

description: Create, configure, and debug Claude Code hooks -- shell commands that execute at lifecycle events (PreToolUse, PostToolUse, Stop, SessionStart, etc.). Use when building file protection, code formatting, notifications, context loading, or any automation triggered by Claude Code events. Covers inline commands, Python scripts, JSON output, state management, and security.


Platform Note: This skill was designed for multi-agent execution. In Codex, treat sub-agent instructions as sequential steps to complete thoroughly within a single agent context.

Claude Code Hooks Creator

Create effective Claude Code hooks -- shell commands that execute automatically at specific lifecycle points, enabling deterministic control over Claude's behavior.

When to Use

Hook Events

| Event | When It Runs | Common Use Cases |

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

| PreToolUse | Before tool executes | Block operations, validate inputs, auto-approve |

| PostToolUse | After tool completes | Format files, log operations, validate output |

| Stop | When Claude finishes | Remind to store learnings, validate completion |

| SubagentStop | When subagent completes | Validate subagent output |

| UserPromptSubmit | When user submits prompt | Add context, validate prompts |

| SessionStart | Session begins | Load context, set environment |

| SessionEnd | Session ends | Cleanup, logging |

| PreCompact | Before context compact | Save important context |

Hook Creation Workflow

1. Understand Requirements

2. Input/Output Format

Input (JSON via stdin):

{
  "session_id": "abc123",
  "transcript_path": "/path/to/transcript.jsonl",
  "cwd": "/current/directory",
  "hook_event_name": "EventName",
  "tool_name": "Write",
  "tool_input": {"file_path": "/path/to/file"}
}

Output (exit codes):

Advanced JSON output (exit 0):

{
  "decision": "block",
  "reason": "Explanation for Claude",
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "allow|deny|ask"
  }
}

3. Implementation

Inline command (simple):

{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Bash",
      "hooks": [{
        "type": "command",
        "command": "jq -r '.tool_input.command' >> ~/.claude/bash-log.txt"
      }]
    }]
  }
}

Python script (complex):

#!/usr/bin/env python3
import json, sys

def main():
    input_data = json.load(sys.stdin)
    tool_name = input_data.get("tool_name", "")
    tool_input = input_data.get("tool_input", {})

    # Your logic here...
    sys.exit(0)  # Allow
    # print("Error message", file=sys.stderr); sys.exit(2)  # Block

if __name__ == "__main__":
    main()

4. Configure in Settings

Add to ~/.claude/settings.json (user) or .claude/settings.json (project):

{
  "hooks": {
    "EventName": [{
      "matcher": "ToolPattern",
      "hooks": [{
        "type": "command",
        "command": "/path/to/hook-script.py",
        "timeout": 30
      }]
    }]
  }
}

Matcher patterns: Exact ("Write"), Regex ("Edit|Write"), All ("*" or "")

Common Hook Patterns

File Protection (PreToolUse)

#!/usr/bin/env python3
import json, sys

PROTECTED = ['.env', 'package-lock.json', '.git/', 'credentials']
input_data = json.load(sys.stdin)
file_path = input_data.get('tool_input', {}).get('file_path', '')

if any(p in file_path for p in PROTECTED):
    print(f"Protected file: {file_path}", file=sys.stderr)
    sys.exit(2)
sys.exit(0)

Code Formatter (PostToolUse)

#!/usr/bin/env python3
import json, sys, subprocess

input_data = json.load(sys.stdin)
file_path = input_data.get('tool_input', {}).get('file_path', '')

if file_path.endswith('.py'):
    subprocess.run(['black', file_path], capture_output=True)
elif file_path.endswith(('.ts', '.tsx', '.js', '.jsx')):
    subprocess.run(['npx', 'prettier', '--write', file_path], capture_output=True)
sys.exit(0)

Context Loader (SessionStart)

#!/usr/bin/env python3
import json, sys, os

result = os.popen('git log --oneline -5 2>/dev/null').read()
output = {
    "hookSpecificOutput": {
        "hookEventName": "SessionStart",
        "additionalContext": f"Recent commits:\n{result}"
    }
}
print(json.dumps(output))
sys.exit(0)

State Management

For hooks tracking state across invocations:

import json, os
from datetime import datetime

STATE_FILE = os.path.expanduser("~/.claude/hook_state.json")

def load_state():
    if os.path.exists(STATE_FILE):
        with open(STATE_FILE) as f:
            return json.load(f)
    return {"invocations": 0, "last_run": None}

def save_state(state):
    with open(STATE_FILE, 'w') as f:
        json.dump(state, f)

Testing and Debugging

  1. Make script executable: chmod +x /path/to/hook.py
  2. Test manually: echo '{"tool_name":"Write"}' | /path/to/hook.py
  3. Run with debug: claude --debug
  4. Check verbose output: Ctrl+O in Claude Code

Security

Anti-Patterns

| Avoid | Why | Instead |

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

| Inline commands for complex logic | Hard to debug, no error handling | Use Python/Bash scripts |

| Missing timeout | Hook can hang indefinitely | Set "timeout": 30 |

| No exit code handling | Unclear success/failure | Use 0 (allow), 2 (block) |

| Modifying tool input without reason | Confuses Claude | Only modify when necessary, document why |

| Missing try/except | JSON parse errors crash hook | Wrap in try/except |

References

<!-- Source: .faos/custom/skills/tools/cc-hooks-creator/SKILL.md -->

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.