Claude Code Perplexity Guard
kirillbarinov/claude-code-perplexity-guard
Force buscas web pelo Perplexity no Claude Code, mantendo subagentes intactos
Ver no GitHubMCP server que força o Claude Code a rotear todas as buscas na web através do Perplexity, usando hooks PreToolUse para enforcement sem quebrar subagents. Detecta o agente principal versus subagentes através do campo `agent_id` oficial e bloqueia WebSearch/WebFetch/curl para URLs públicas apenas no contexto principal.
Instalação
npx convez-ai kirillbarinov/claude-code-perplexity-guard1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.
Métricas
Casos de uso
- Centralizar todas as buscas web em um único engine economicamente eficiente
- Reduzir custos de API usando Perplexity sonar em vez de tokens Opus para web search
- Proteger pesquisa de qualidade em projetos que exigem fonte de verdade única
Veredito

Solução técnica bem pensada que explora limites oficiais da API (agent_id) para enforcement verdadeiro. Benchmarks justificam a abordagem; implementação via hook é limpa e não quebra a arquitetura de subagentes do Claude Code. Recomendado para quem quer controle real sobre routing de pesquisa.
README
A tradução para o português deste README ainda está na fila.
claude-code-perplexity-guard
Force Claude Code's main agent to route all web search through the Perplexity MCP — without breaking subagents.
A PreToolUse hook hard-blocks the built-in WebSearch/WebFetch and direct
curl/wget to public URLs for the main agent, and tells the model to use
Perplexity instead. Subagents (Explore, research agents, your custom agents) are
detected and passed through, so their own research tools keep working. Other MCP
servers are left untouched.
⚡ Quick start — let Claude Code set it up for you
You don't need to follow the steps manually. Just paste this into Claude Code and it will clone, install, and walk you through the whole configuration:
Clone https://github.com/kirillbarinov/claude-code-perplexity-guard, read its
README, and set it up for me end to end:
1. copy hooks/perplexity-guard.sh into ~/.claude/hooks and chmod +x it;
2. append BOTH PreToolUse objects from settings.snippet.json (WebSearch|WebFetch
and Bash) to my ~/.claude/settings.json WITHOUT breaking the existing hooks array;
3. append CLAUDE.snippet.md to my ~/.claude/CLAUDE.md;
4. walk me through configuring a `perplexity-mcp` MCP server — ask me for my
Perplexity API key, don't hardcode it;
5. run the verify commands from the README and show me the output;
6. remind me to restart Claude Code so the hook loads.
Ask me before editing any of my existing config files.
Prefer to do it by hand? Follow Install below.
Why
- One search engine, by force. A
CLAUDE.mdrule asking "please use Perplexity" is a suggestion the model can skip. A hook is enforcement — the built-in search literally returnsdeny. - Cheaper, fresher answers. Perplexity
sonaris cheap and current; reservesonar-profor research that needs citations. - Subagents stay intact. A blanket
permissions.denyonWebSearchwould also kill every research subagent (most have no Perplexity access). This hook only hits the main thread.
See BENCHMARKS.md for a measured head-to-head (Perplexity vs
built-in WebSearch) on tokens, cost, quality, and latency — short version: for
simple facts sonar is ~2× faster, ~3× cheaper, and more precise; for research the
cost edge holds because synthesis runs on a cheap model instead of burning Opus
output tokens.
How it works
Claude Code's PreToolUse hook input includes an official agent_id field that is
present only when the hook fires inside a subagent call
(hooks reference). The guard parses it with
jq (the top-level field — not a text grep, so a query that merely contains the
string agent_id can't bypass it):
| Where the call comes from | agent_id | Action |
|---|---|---|
| Main agent (you) | absent | deny + redirect to Perplexity |
| Any subagent | present | pass through (untouched) |
The same script is registered on two matchers and branches on tool_name:
WebSearch/WebFetch→ deny for the main agent.Bash→ deny onlycurl/wgetto a public http(s) URL (closes the bypass).ezycopyand local/private hosts (localhost, 127.x, 10.x, 192.168.x, 172.16–31.x) pass. Other tools and other MCP servers are not touched.
WebSearch / WebFetch / Bash(curl|wget public URL)
│
PreToolUse hook ── agent_id present? ──► yes ──► allow (subagent research)
│ │
│ fallback flag fresh? ──► yes ──► allow (Perplexity down)
│ │ no
└──────────────────────────────── no ───► deny → "use Perplexity MCP"
Every decision is appended to ~/.claude/perplexity-guard.log. If Perplexity is
down or your key expired, touch ~/.claude/perplexity-guard.disabled opens a
10-minute window where the built-in path is temporarily allowed.
Install
1. Configure a Perplexity MCP server named perplexity-mcp
This exposes the perplexity_search_web tool as mcp__perplexity-mcp__perplexity_search_web,
which is what the hook redirects to. Add to your ~/.claude.json / .mcp.json:
{
"mcpServers": {
"perplexity-mcp": {
"command": "npx",
"args": ["-y", "@jschuller/perplexity-mcp"],
"env": {
"PERPLEXITY_API_KEY": "your_perplexity_api_key_here"
}
}
}
}
Get an API key at https://www.perplexity.ai/settings/api. Other Perplexity MCP packages work too — just make sure the server name is
perplexity-mcpand it exposesperplexity_search_web, so the tool id matches the hook's redirect.
2. Install the hook
git clone https://github.com/kirillbarinov/claude-code-perplexity-guard.git
cd claude-code-perplexity-guard
./install.sh
install.sh copies the hook to ~/.claude/hooks/ and prints the two manual steps
below (it does not edit your settings.json/CLAUDE.md for you — on purpose).
3. Register the hook in ~/.claude/settings.json
Merge settings.snippet.json — append both objects to
your existing hooks.PreToolUse array (don't replace it). The same script handles
both matchers; the Bash entry closes the curl/wget bypass. If you already have
other Bash PreToolUse hooks, just add this as another entry — multiple hooks per
matcher all run.
[
{
"matcher": "WebSearch|WebFetch",
"hooks": [
{ "type": "command", "command": "bash \"$HOME/.claude/hooks/perplexity-guard.sh\"", "timeout": 5 }
]
},
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "bash \"$HOME/.claude/hooks/perplexity-guard.sh\"", "timeout": 5 }
]
}
]
4. (Recommended) Add the routing rule to CLAUDE.md
Append CLAUDE.snippet.md to your ~/.claude/CLAUDE.md. The hook
enforces that search goes through Perplexity; the rule tells the model how
(which model, process the result, don't answer from memory).
5. Restart Claude Code
Hooks load at session start — restart or /clear for it to take effect.
Model guidance — default to sonar, escalate only for research
Model choice is a judgment call, so it lives in the CLAUDE.md rule (not the hook).
The hook only enforces that search goes through Perplexity.
| Use case | Model | max_tokens | Notes |
|---|---|---|---|
| Direct fact / single question | sonar | 1500 | cheap, fast, current |
| 2–3 angles / follow-ups | several sonar | 1500 each | still cheaper than one pro |
| Research: many sources + synthesis | one sonar-pro | 1500–1800 | temperature=0; ~3–6× a sonar call |
| Citation harvesting only | sonar-pro | 400 | temperature=0 |
Freshness — pass recency (default month): day/week for news, prices,
releases, "right now"; default month for stable facts and docs; year for
historical/archival lookups.
Cost rules
sonar-prooutput is ~15× pricier thansonar($15 vs $1 per 1M tokens) — don't use it without a reason.- Don't spray 5+
sonarcalls on one question; at that point onesonar-prois cheaper and cleaner. max_tokensis a cap (a guard against truncation/runaway), not a requested length — you pay for what's actually generated. Keep it generous on cheapsonar(~1500), moderate on priceysonar-pro. The models' technical max is 8192; our hard cap ismax_tokens=2000— never exceed it. Context windows:sonar128K,sonar-pro200K (input + output).
Verify
# main agent, built-in search → deny
echo '{"tool_name":"WebSearch"}' \
| bash ~/.claude/hooks/perplexity-guard.sh
# → {"hookSpecificOutput":{ ... "permissionDecision":"deny" ... }}
# main agent, curl to a public URL → deny (closes the bypass)
echo '{"tool_name":"Bash","tool_input":{"command":"curl https://example.com"}}' \
| bash ~/.claude/hooks/perplexity-guard.sh
# → {"hookSpecificOutput":{ ... "permissionDecision":"deny" ... }}
# ezycopy and local/private hosts → pass through (empty output)
echo '{"tool_name":"Bash","tool_input":{"command":"ezycopy https://example.com"}}' \
| bash ~/.claude/hooks/perplexity-guard.sh
echo '{"tool_name":"Bash","tool_input":{"command":"curl http://localhost:3000"}}' \
| bash ~/.claude/hooks/perplexity-guard.sh
# → (no output)
# subagent → pass through (empty output)
echo '{"agent_id":"agent-x","tool_name":"WebSearch"}' \
| bash ~/.claude/hooks/perplexity-guard.sh
# → (no output)
# bypass attempt: "agent_id" only inside the query text → still deny
# (jq reads the top-level field, not a text grep)
echo '{"tool_name":"WebSearch","tool_input":{"query":"what is agent_id"}}' \
| bash ~/.claude/hooks/perplexity-guard.sh
# → {"hookSpecificOutput":{ ... "permissionDecision":"deny" ... }}