codesearch publishes usage instructions to every MCP client via the
initialize handshake (see main README § Agent Guidance).
OpenCode and Cursor surface these automatically and the model follows them
reasonably well.
Claude Code is different in two ways that combine to defeat the advisory instructions:
- MCP tool schemas are deferred. Claude Code doesn't load full parameter
schemas for MCP tools (codesearch included) up front — only tool names
appear in context. To actually call
mcp__codesearch__search, the model must first callToolSearchto pull in the schema. That's an extra step with no obvious payoff, so under any time pressure the model skips it. GrepandGlobare always fully loaded, schema and all, and require zero extra steps. They're the path of least resistance.
Net effect: advisory instructions ("prefer codesearch") lose to structural
convenience ("Grep just works") more often than on other clients. This shows
up as codesearch sitting there indexed and unused while the model greps the
working tree — including in spawned subagents, which don't even inherit the
parent's AGENTS.md or the MCP initialize instructions at all.
Four Claude Code hooks that make the preference structural instead of advisory:
-
grep-guard— aPreToolUsehook onGrepandBash. Blocks everyGrepcall against an indexed repo for as long as the codesearch serve hub is reachable, with a message telling the model exactly how to load and call codesearch instead. TheBashmatcher closes the shell escape hatch: a Bash tool command that greps FILES inside an indexed repo is guarded identically (quoted mentions likeecho "grep"are not invocations, and a pure stream filter such asfind . | grep -v '^./.git/'reads no files, so it is not guarded). The guarded repo is resolved from the grep target itself — the git root of the path being searched, not the hook's working directory — so an absolute-path Grep into a different indexed repo is guarded too (a cwd-based check used to let those through, and until #199 the absolute-path test itself only recognized Windows-style roots, so POSIX absolute paths were still resolved against the cwd). For a Bash grep the target is the command's own operand (absolute, relative to the shell cwd, or after a leadingcd DIR &&), so a grep aimed at/tmpor at an unregistered clone is allowed; that fixed the reported misfire where a session inside an indexed repo denied greps that never touched it. Coverage is decided by registration: the target's git root must be one of the repos in the hub's~/.codesearch/repos.json(honoringCODESEARCH_REPOS_CONFIG;CODESEARCH_HOMErelocates the root), which also carves out nested repos for free — an unregistered clone inside a registered repo resolves to its own git root and is treated as uncovered. Grep is auto-allowed only when codesearch is genuinely down: the hook probes the unauthenticated/healthzliveness endpoint and lets Grep through only when that probe fails. A low-confidence or empty codesearch result is a successful call ("reformulate"), not a dead server, so it does not unblock Grep. One exception: when the target repo is live but mid-reindex (the serve watcher's full refresh, e.g. right after a branch switch), the hook waits the rebuild out itself — pollingGET /indexing?path=<repo root>every few seconds for up toCODESEARCH_GREP_GUARD_WAIT_MS(default 120s;0restores the legacy instant wait-and-retry instruction) — and denies Grep with a retry-codesearch instruction once the rebuild lands, so the denial only fires when codesearch will actually answer. Past the cap Grep opens: a big-repo rebuild outlasts any polite wait message, and denying Grep while every codesearch call times out deadlocks the session. The freshness probe (GET /indexing?path=<repo root>, bearer key forwarded whenCODESEARCH_API_KEYis set) is skipped silently on serves that predate the endpoint, so root>`) is skipped silently on serves that predate the endpoint, so hook and server versions can be mixed freely. Grep against paths outside any git repo, or against repos codesearch does not cover, is never blocked; grep is right there in those cases. -
subagent-preamble— aPreToolUsehook onAgent(the subagent-spawn tool). Prepends a short preamble to every subagent prompt explaining that codesearch exists, that its tools are deferred and needToolSearchfirst, and when to prefer it over Grep/Glob. This is the only way to reach subagents at all, since they don't inheritAGENTS.mdor MCP instructions. -
edit-guard— aPreToolUsehook onEdit/Write/MultiEdit. Blocks an edit to a code file in a codesearch-registered repo until codesearch was consulted for that file within the last 5 minutes:mcp__codesearch__find_impactfor SCIP-backed languages (.cs .ts .tsx .mts .cts),mcp__codesearch__find(kind="usages")for other source code. Docs, markup and config files (.md,.json, ...) are never gated — a usages lookup answers nothing there. Making the caller-aware-editing protocol structural. Coverage uses the same registration model as grep-guard (sharedcodesearch-commonhelpers): the file's git root must be listed in~/.codesearch/repos.json(relocatable viaCODESEARCH_HOME; orCODESEARCH_SERVERis set); unregistered repos and non-git paths are never blocked. -
edit-guard-post— aPostToolUsehook onmcp__codesearch__find_impactandmcp__codesearch__find, recording the "consulted" markersedit-guardreads into a state file ($TMPDIR/.codesearch-edit-guard-state.jsonon bash,%TEMP%\.codesearch-edit-guard-state.jsonon PowerShell). It fires on everyfind_impactcall and everyfind(kind="usages")(the kind check is done script-side — matchers only see tool names). Markers are attributed from all available sources, written when they apply: a file-ish input field (file/path/file_path—find_impact's schema names its targetsymbol_nameand carries no path, so this serves older schemas); a path-likesymbolinput — the exactfind(symbol=<path>, kind="usages")calledit-guarddemands for non-SCIP code marks the path it names (bare code symbols never mark); every path the response mentions (path/file/file_pathat any depth, including inside the JSON-stringified text payload MCP wraps results in — values must look like file paths, so a bare symbol string writes no junk key; paths join onto the registered root of the call'sprojectalias, or of thecwdrepo for serve-mode agents that scope withcwdinstead, where both shape candidates are marked), so one consultation marks every file it listed; and a repo-level marker on theproject's registered root, else thecwdrepo's root, when nothing yielded a path (empty result, or a "no SCIP backend" error), whichedit-guardaccepts for any file in that repo. Any outcome counts; without the response-path and repo-level attribution a missing C# symbol index wrote no marker at all and every.csedit in a registered repo stayed denied — a permanent wedge. PostToolUse hooks cannot block anything; this one never emits a decision and always exits 0.
All hooks fail open: if they can't parse their input, or codesearch isn't running/indexed, they get out of the way and let the tool call proceed untouched. They never block targets outside any git repo, or repos codesearch does not cover.
# Windows / PowerShell — user-level (~/.claude), applies to all projects
pwsh -File integrations/claude-code/install.ps1
# Windows / PowerShell — project-level (./.claude), this repo only
pwsh -File integrations/claude-code/install.ps1 -Scope project
# macOS / Linux — user-level (~/.claude)
bash integrations/claude-code/install.sh
# macOS / Linux — project-level (./.claude)
bash integrations/claude-code/install.sh --projectThe installer:
- copies the guard scripts, the PostToolUse companion and the shared
codesearch-commonhelpers into<claude-dir>/hooks/codesearch/ - merges the
PreToolUseregistrations (one per guard) and thePostToolUseregistration (the companion) into<claude-dir>/settings.json(backing up the existing file first) - is idempotent — re-running it skips hooks already registered and never duplicates or clobbers unrelated settings
Restart Claude Code (or start a new session) after installing.
If you'd rather wire it up by hand, or already have hooks on these events and
want to merge manually, add to ~/.claude/settings.json (or
.claude/settings.json for project scope):
{
"hooks": {
"PreToolUse": [
{
"matcher": "Grep|Bash",
"hooks": [
{ "type": "command", "command": "pwsh -NoProfile -NonInteractive -File \"<path>/grep-guard.ps1\"" }
]
},
{
"matcher": "Agent",
"hooks": [
{ "type": "command", "command": "pwsh -NoProfile -NonInteractive -File \"<path>/subagent-preamble.ps1\"" }
]
},
{
"matcher": "Edit|Write|MultiEdit",
"hooks": [
{ "type": "command", "command": "pwsh -NoProfile -NonInteractive -File \"<path>/edit-guard.ps1\"" }
]
}
],
"PostToolUse": [
{
"matcher": "mcp__codesearch__find_impact|mcp__codesearch__find",
"hooks": [
{ "type": "command", "command": "pwsh -NoProfile -NonInteractive -File \"<path>/edit-guard-post.ps1\"" }
]
}
]
}
}Use the .sh scripts with a bash "<path>/..." command instead on
macOS/Linux. Point <path> at wherever you copy hooks/*.ps1 / hooks/*.sh.
The guard scripts source codesearch-common.ps1 / codesearch-common.sh
from their own directory, so that file must be copied alongside them.
Remove the guard entries (matchers Grep|Bash, Agent, WebSearch|WebFetch and
Edit|Write|MultiEdit under PreToolUse, and
mcp__codesearch__find_impact|mcp__codesearch__find under PostToolUse,
whose commands point at hooks/codesearch/) from settings.json, and delete
<claude-dir>/hooks/codesearch/.
grep-guardresolves the guarded repo from the grep target, never from its own cwd: empty/relative paths resolve against the cwd repo (they are relative to it by definition), absolute paths resolve against the git root of the path being searched. Coverage is then decided by registration with the serve hub: the target's git root must be one of the repos listed in~/.codesearch/repos.json(the same registration list the hub itself resolves queries by, honoring theCODESEARCH_REPOS_CONFIG/CODESEARCH_HOMEoverrides), or an explicitCODESEARCH_SERVERenv var for pure remote-serve setups with no local registration. A local.codesearch.dbdirectory is deliberately not a coverage signal anymore (#199): a stale db from a since-unregistered repo used to deny Grep even though the hub could not answer for that repo (unknown alias), and a registered repo whose db directory was gone slipped through uncovered. Because the git root must equal a registration, nested repos are carved out correctly: an unregistered clone inside a registered repo resolves to its own root and is treated as uncovered. Missing, unreadable or malformedrepos.json(or a missingjq) fails open — a guard that cannot resolve coverage must allow, never deny. It deliberately does not treat "acodesearchprocess is running" as sufficient —codesearch servecommonly runs as a persistent background hub covering many registered repos (codesearch index list), so that process is alive on a dev machine almost all the time regardless of whether the searched repo is one of the repos it actually indexes. Checking process presence alone made the hook fire in every directory on the machine, including unindexed ones — this was found and fixed after exactly that false-positive showed up in real use. (The older cwd-based resolution had the mirror-image defect: an absolute-path Grep into a different indexed repo looked "external" and slipped the guard — also fixed, same release. Until #199 the absolute-path test itself only matched Windows-style roots —C:\,C:/, MSYS/c/, UNC//server— so POSIX absolute paths like/home/...were still resolved against the cwd; with a session cwd that is a plain parent directory the guard silently allowed everything.) If your setup connects to a remotecodesearch serveinstance with no localrepos.jsonregistration, setCODESEARCH_SERVERto opt back into enforcement for that repo. Both the bash and the PowerShell twin now resolve coverage through the sharedcodesearch-commonhelpers, so the two shells behave identically (the PowerShell twin used to lag behind on the.codesearch.db/Windows-only-path signals — closed with the edit-guard work, #199).edit-guardis per-file, not per-repo: a marker for one file never unblocks an edit to another file — except the repo-level markeredit-guard-postwrites when a consultation returned no attributable path (empty result / "no SCIP backend"), which unblocks every file in that repo for the window. The marker state lives in a temp-dir JSON file ($TMPDIR/.codesearch-edit-guard-state.json/%TEMP%\.codesearch-edit-guard-state.json), entries expire after 5 minutes and are pruned on write; missing or corrupt state counts as "not consulted" (deny on covered repos, allow everywhere else). Like the other guards it is per-machine, not per-repo: it only ever fires on files whose git root is registered with the serve hub. The gate keys on extension: docs/markup/config (.md,.json, ...) pass without any marker; filename-mapped code files (Dockerfile,Makefile) pass too — rare refactor targets. Scope your consultation with theprojectalias: response paths resolve against that project's registered root, and the repo-level fallback needs it — a projectlessfind_impactthat returns no paths writes no marker at all. Known limit: in aCODESEARCH_SERVERpure-remote setup there is no local registry, so neither the response-path resolution nor the repo fallback can attribute a marker — there the guard demands a file-ish input field and nothing else satisfies it.- Both hooks are per-machine, not per-repo: install once at user scope and every project benefits, including ones not registered with the serve hub (the guard simply won't block Grep there, since coverage fails open).
grep-guarddecides "is codesearch down?" by probing the serve hub's unauthenticated/healthzendpoint (base URL fromCODESEARCH_SERVER, elsehttp://127.0.0.1:$CODESEARCH_SERVE_PORT, else the compiled defaulthttp://127.0.0.1:39725). Any HTTP response counts as up and keeps Grep blocked; only a connection-level failure (refused / timeout) counts as down and lets Grep through. The probe has a 2-second timeout, so a wedged server eventually fails open rather than stalling every Grep. The PowerShell hook needs no extra tools; the bash hook additionally requirescurl.