今日已更新 411 条资讯 | 累计 30455 条内容
关于我们

Stop your coding agent from cat-ing .env: a Claude Code hooks cookbook

Otto 2026年08月11日 20:50 0 次阅读 来源:Dev.to

Your coding agent is a process that reads your filesystem and runs shell commands with your credentials. Most of the time that is exactly what you want. Occasionally it is cat .env while debugging - and now your production keys live in a transcript forever - or a confident rm -rf on a path that resolved differently than expected. Everyone's first fix is to add rules to CLAUDE.md: "never read .env, never force push". Those are suggestions to a language model. They work until they don't, and you will not be watching when they don't. Claude Code has a mechanism that is not a suggestion: hooks. A hook is a program you register for specific events - before a tool call, after it, when the session tries to end. It runs outside the model, sees the exact tool call as JSON on stdin, and its verdict is enforced by the harness itself. The model cannot talk its way past it, but it CAN read a structured denial and route around it productively. This is a cookbook for writing them. Everything below is plain Python stdlib and works on current Claude Code as of August 2026. The mechanics in ninety seconds Hooks are registered in settings ( .claude/settings.json in a project, ~/.claude/settings.json globally): { "hooks" : { "PreToolUse" : [ { "matcher" : "Read|Grep|Bash" , "hooks" : [ { "type" : "command" , "command" : "python3 \" ${CLAUDE_PROJECT_DIR}/.claude/hooks/secret-guard.py \" " , "timeout" : 10 } ] } ] } } The matcher filters by tool name. Your command receives a JSON object on stdin describing the event; for PreToolUse it includes tool_name and tool_input (the exact arguments about to run). You respond on stdout with JSON. Three responses cover almost everything: Deny a tool call, with a reason the model will read: { "hookSpecificOutput" : { "hookEventName" : "PreToolUse" , "permissionDecision" : "deny" , "permissionDecisionReason" : "why, and what to do instead" } } Block a session from ending (Stop event), sending work back: { "decision" : "block" , "reason" : "lint failed

本文内容来源于互联网,版权归原作者所有
查看原文