お雑煮研究会

好きな焼肉は魚

Claude Code Hooks を使って Gemini CLI 経由での検索を義務付ける

日夜 Claude Code と開発する中で、やはり Web 検索の精度は Gemini ないし Google のほうが強いという気持ちになっている。

このような記事もあるほどなので、おそらくこれは共通認識だろう。

zenn.dev

とはいえ、Claude Code が Web 検索をするたびに介入して Gemini を使え!と書くのは面倒だしいちいち CLAUDE.md に書いたところで守ってくれるとは限らない。

だが Hooks ならできる

先日追加された Hooks なら、必ず Gemini 経由で検索させることが可能だ。

docs.anthropic.com

実は Hook Output という概念があり、特定の JSON 文字列を出力することで Claude に明確に構造化された人間の判断結果を渡せるようになっている。

ということでこの機能を使って、こういうことを伝えてあげれば良い。

  • PreToolUse Hook で WebSearch tool の呼び出しに介入し
  • WebSearch tool の呼び出しは block する。かわりに Bash(gemini --prompt "WebSearch: <query") を使ってくれ

これに対応する Hook の設定はこうなる。

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "WebSearch",
        "hooks": [
          {
            "type": "command",
            "command": "jq -n --arg reason 'Use Bash(gemini --prompt \"WebSearch: <query>\") instead.' '{decision: \"block\", reason: $reason}'"
          }
        ]
      }
    ]
  }
}

実際に動かす

こうなった。CLAUDE.md では何も言っていないが、勝手に Gemini を使った検索に切り替えてくれる。

Hook で Claude の行動に介入することで、機械的に規約を守らせることができるようになったのは結構良いことだと思っている。

> WebSearch "東京の天気"

✻ Thinking…

  The user is asking me to do a web search for "東京の天気" which means "Tokyo weather" in Japanese. 
  This is a straightforward request for current weather information. I should use the WebSearch tool to 
  search for this information.

  Based on the system prompt, I should respond in Japanese with a concise response. The user is asking 
  for weather information, so I should provide what I find from the search results.

⏺ Web Search("東京の天気")
  ⎿  Error: WebSearch operation blocked by hook:
     - Use Bash(gemini --prompt "WebSearch: <query>") instead.

✻ Thinking…

  The WebSearch was blocked by a hook, and I'm being told to use Bash with gemini CLI instead. I should 
  use the suggested command format.

⏺ Bash(gemini --prompt "WebSearch: 東京の天気")
  ⎿  Data collection is disabled.                                                     
     MCP STDERR (sequential-thinking): Sequential Thinking MCP Server running on stdio

     … +14 lines (ctrl+r to expand)

✻ Thinking…

  The gemini command worked and provided weather information for Tokyo. The response shows:
  - Current weather: Cloudy, 27°C
  - Today: Sunny then cloudy, high 37°C, low 26°C, 30% chance of rain
  - Monday: Sunny then cloudy, high 38°C, low 28°C
  - Tuesday: Sunny then cloudy, high 35°C, low 26°C
  - Air pollution levels are high, so people with respiratory sensitivity should limit outdoor 
  activities

  I should provide this information to the user in Japanese as requested.

⏺ 現在の東京の天気は曇り、気温は27℃です。

  今後の予報:
  - 今日(日曜日): 晴れのち曇り、最高気温37℃、最低気温26℃、降水確率30%
  - 月曜日: 晴れのち曇り、最高気温38℃、最低気温28℃
  - 火曜日: 晴れのち曇り、最高気温35℃、最低気温26℃

  大気汚染のレベルが高いため、呼吸器系の敏感な方は屋外での活動を控えることが推奨されています。

おわり

おわり