Claude Code の PreToolUse Hook で誤ったパッケージマネージャーの利用を止める

🚨
note

Claude Code に追加された Hook 機能を使って「bun を利用しているのに npm を使おうとする」というような動作を防止することが出来そうだったので試した。

PreToolUse では設定されたコマンドが exit code 2 を返すと、実行しようとしていたツール利用をブロックすることができる。さらに JSON で詳しい情報を伝えることで Claude Code が必要なリカバリを行うため、これに合わせて次の設定を試した:

{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Bash",
      "hooks": [{
        "type": "command",
        "command": "jq -r '.tool_input.command // \"\"' | grep -qE \"^(npm|npx)\\s\" && echo '{\"decision\":\"block\",\"reason\":\"Consider using bun instead of npm/npx for better performance. Examples: npm install → bun install, npm run → bun run, npx → bun x\"}' && exit 2 || true"
      }]
    }]
  }
}

少し読みやすくするとこんな感じ:

jq -r '.tool_input.command // \"\"' | grep -qE \"^(npm|npx)\\s\" &&
    echo '{
         \"decision\":\"block\",
         \"reason\":\"Consider using bun instead of npm/npx for better performance. Examples: npm install → bun install, npm run → bun run, npx → bun x\"
    }' && exit 2
|| true

雑ではあるが、これで誤った npm の実行をブロックすることができた。

Image
yaakai.to