C.W.K.
Stream
Lesson 06 of 08 · published

Hooks: pre·post tool use

~16 min · hooks, PreToolUse, PostToolUse

Level 0Observer
0 XP0/64 lessons0/13 achievements
0/150 XP to next level150 XP to go0% complete

Hooks가 코드의 정책

Hooks가 도구 이벤트에 fire하는 user-defined callback — PreToolUse(도구 run 전), PostToolUse(후), UserPromptSubmit, Stop 등. 모델 행동 변경 없이 정책 강제, 활동 로그, args redact, 또는 호출 통째로 veto.

왜 in-prompt 룰을 이김

시스템 프롬프트에 'never run rm -rf' 모델한테 묻고 대부분 따라. 어떤 rm -rf invocation에 거부 반환하는 hook은 hard 보장. 가이드는 프롬프트 사용; invariant은 hooks.

시작할 패턴 셋

(1) Logging hook — 매 도구 호출을 structured 로그에 기록. (2) Redaction hook — 도구 hit 전 args에서 시크릿 scrub. (3) Veto hook — deny 패턴 매치 호출 거부. cwkPippa의 hooks가 다른 concern에 셋 다 포함.

원칙: Hooks가 정책이 프롬프트 변경 살아남게 하는 법. 모델은 drift 가능; hooks는 X.

Code

위험 명령 veto하는 PreToolUse hook·python
from claude_agent_sdk import ClaudeAgentOptions, HookContext, HookOutput

async def block_destructive_bash(context: HookContext) -> HookOutput:
    if context.tool_name != "Bash":
        return HookOutput(allow=True)
    cmd = context.tool_input.get("command", "")
    if "rm -rf" in cmd or "dd if=" in cmd:
        return HookOutput(allow=False, reason="refused: matches destructive command pattern")
    return HookOutput(allow=True)

options = ClaudeAgentOptions(
    cwd="/srv",
    hooks={"PreToolUse": [block_destructive_bash]},
)
Telemetry용 PostToolUse hook·python
import time, json

async def log_tool_use(context):
    line = {
        "ts": time.time(),
        "tool": context.tool_name,
        "input_hash": hash(json.dumps(context.tool_input, sort_keys=True)),
        "duration_ms": context.duration_ms,
        "is_error": context.is_error,
    }
    with open("/var/log/agent.jsonl", "a") as f:
        f.write(json.dumps(line) + "\n")

options = ClaudeAgentOptions(
    cwd="/srv",
    hooks={"PostToolUse": [log_tool_use]},
)

External links

Exercise

매 Bash 명령 로그하는 PreToolUse hook 추가(read-only, no veto). 세션 run, 로그 inspect. 진짜 prevent하고 싶은 명령 패턴 하나에 veto 룰 추가. 테스트.
Hint
Veto 룰이 안 trigger하면 모델한테 매치된 명령 run하라고 simulate. Hook이 거부하고 모델이 조정해야.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.