Permettez aux agents IA d'effectuer des recherches de code hybrides, sémantiques et lexicales, à travers plusieurs dépôts indexés, avec navigation par symboles et découpage par AST.
Aussi connu sous flupkede/codesearch
- Étoiles
- 104
- Outils
- 20
- Téléchargements, 30 jours
- —
- Dernière version
- —
- Dernier commit
- 14 nov. 2026
- Licence
- Apache-2.0
Qu'est-ce que codesearch MCP ?
codesearch est un serveur MCP. Permettez aux agents IA d'effectuer des recherches de code hybrides, sémantiques et lexicales, à travers plusieurs dépôts indexés, avec navigation par symboles et découpage par AST. Il expose 20 outils, comme query, mode, filter_path.
Résumé généré à partir du README du projet
À propos du MCP server codesearch
codesearch permet aux agents IA de parcourir plusieurs bases de code en utilisant des méthodes sémantiques et lexicales. Ce MCP server basé sur Rust permet aux développeurs d'effectuer de la recherche hybride en combinant des embeddings vectoriels et la recherche plein texte BM25, via un mécanisme de Reciprocal Rank Fusion. Il est conçu pour s'exécuter localement sur un CPU sans nécessiter Docker ou un GPU, ce qui le rend adapté aux environnements d'entreprise devant rester hors ligne.
Les utilisateurs peuvent exploiter le serveur de deux manières : un mode local pour travailler sur un dépôt unique via stdio, ou un mode serveur pour l'orchestration multi-dépôts via HTTP. Le serveur propose cinq outils unifiés, notamment search, find, explore, get_chunk et find_impact. Il utilise tree-sitter pour un découpage (chunking) sensible à l'AST sur 17 langages, garantissant que les extraits de code correspondent à des fonctions ou des classes plutôt qu'à des lignes arbitraires. Cette approche aide les agents à naviguer entre les symboles, à tracer les imports et à trouver des définitions efficacement à travers différents projets.
Extrait du README du projet. Chaque cas d'utilisation est vérifié par rapport à une citation du document.
Outils MCP codesearch 20
Détectés depuis le READMEquerymodefilter_pathfile_globlanguageregexphrasecompactlimitprojectgroupsymbol
| query | — | |
| mode | — | |
| filter_path | — | |
| file_glob | — | |
| language | — | |
| regex | — | |
| phrase | — | |
| compact | — | |
| limit | — | |
| project | — | |
| group | — | |
| symbol | — |
Afficher les 20 outilsAfficher moins d'outils
kinddefinition_kindtargetchunk_idcontext_linessymbol_namefileline
| kind | — | |
| definition_kind | — | |
| target | — | |
| chunk_id | — | |
| context_lines | — | |
| symbol_name | — | |
| file | — | |
| line | — |
Vérifications automatisées
Exécuté le 13 nov. 2026Rapport complet →A passé nos vérifications automatisées. Il ne s'agit pas d'un audit de sécurité : lisez le code et donnez au serveur l'accès le plus restreint dont il a besoin. Fonctionnement des vérifications
- Dépôt source lié et accessibleRéussi
- Licence open source (OSI)Réussi
- Commit ou version publiée au cours de l'année écouléeRéussi
- Nom du package non proche d'un package populaireNon vérifié
- L'endpoint distant utilise HTTPSNon vérifié
- Les outils destructifs sont étiquetésRéussi
- Aucune instruction cachée destinée au modèleRéussi
- Aucun avis critique dans le package ou ses dépendancesNon vérifié
README
Voir sur GitHubcodesearch
Multi-repo semantic code search for AI agents — a Rust MCP server with vector + BM25 hybrid retrieval, symbol navigation, and cross-repository orchestration. Fully local, fully offline, no GPU, no Docker.
codesearch gives AI agents (OpenCode, Claude Code, Cursor, and any MCP client) deep codebase understanding through 5 unified MCP tools. Index once, search semantically across multiple repositories simultaneously.
Why codesearch?
- Multi-repo serve mode: Fan-out queries across repository groups with cross-repo RRF ranking
- Hybrid retrieval: Vector embeddings + BM25 full-text search fused with Reciprocal Rank Fusion
- Symbol navigation: Jump to definitions, find usages, trace imports and dependents — in the same tool
- AST-aware chunking: Tree-sitter parsing for 17 languages — chunks align to functions/classes (and Markdown sections), not arbitrary line ranges
- Token-efficient: Returns metadata by default; agents fetch full code only when needed via
get_chunk - Lightweight footprint: Hundreds of MB on disk, runs on CPU only, no runtime model downloads (works behind enterprise proxies)
- Zero config for single repos:
codesearch index && codesearch mcp— done
How does this compare?
The MCP code-search ecosystem grew rapidly in late 2025 / early 2026 and many projects share the same baseline stack (Rust + tree-sitter + BM25 + embeddings + MCP). codesearch's deliberate focus is:
| Focus area | codesearch | Typical alternative |
|---|---|---|
| Repository scope | Multi-repo serve with cross-repo RRF | Usually single repo at a time |
| Footprint | ~hundreds of MB, CPU-only, no Docker | GB-scale, GPU, Docker, or cloud |
| Enterprise / offline | No runtime fetches; static binary | Often pulls models at first run |
| Symbol navigation | find (def/usages/imports/dependents) co-located with semantic search |
Often a separate code-graph tool |
| Token cost per call | compact=true by default; chunks fetched on demand |
Frequently dumps full snippets |
codesearch is intentionally narrower than full code-graph or knowledge-graph tools — it picks "lightweight, multi-repo, MCP-native, fully offline" and stays on that lane.
Architecture
graph TB
Agent[AI Agent / MCP Client] -->|MCP stdio or HTTP| Router{MCP Router}
Router --> Search[search tool]
Router --> Find[find tool]
Router --> Explore[explore tool]
Router --> GetChunk[get_chunk tool]
Router --> FindImpact[find_impact tool]
Router --> Status[status tool]
Search -->|mode=semantic| Semantic[Vector ANN + BM25 + RRF Fusion]
Search -->|mode=literal| Literal[Tantivy FTS / Regex]
Find -->|definition/usages| SymbolIndex[Symbol Index]
Find -->|imports/dependents| DepGraph[Dependency Graph]
Explore -->|outline| TreeSitter[Tree-sitter AST]
Explore -->|similar| Semantic
Semantic --> Arroy[arroy ANN vectors]
Semantic --> Tantivy[Tantivy BM25]
Arroy --> LMDB[(LMDB)]
Tantivy --> TantivyIdx[(Tantivy Index)]
GetChunk --> LMDB
FindImpact -->|C# symbols| CSharpHelper[scip-csharp helper]
CSharpHelper -->|SCIP index| ScipLMDB[(LMDB scip_symbols)]
subgraph "Serve Mode (multi-repo + federation)"
ServeRouter[HTTP Router] -->|project/group routing| Repo1[Repo A]
ServeRouter --> Repo2[Repo B]
ServeRouter --> RepoN[Repo N]
ServeRouter -->|"@peer fan-out · TLS"| CloudPeer["Cloud serve peer<br/>results merged via RRF"]
end
Router -->|client mode| ServeRouter
Quick Start
Install
One line — the installer asks for an install path on first use and updates an existing install in place (stopping a running serve from that directory first):
Windows (PowerShell):
irm https://github.com/flupkede/codesearch/releases/latest/download/install.ps1 -OutFile install.ps1; .\install.ps1
Linux / macOS (bash):
curl -fsSLO https://github.com/flupkede/codesearch/releases/latest/download/install.sh && bash install.sh && rm install.sh
(The download-then-run form matters: piping straight into bash shares stdin with the script, which breaks the first-install path prompt.)
Downloads the -with-csharp build by default (codesearch + scip-csharp, self-contained); add -NoCSharp / --no-csharp for the base build. Archives carry a .sha256 sidecar and the installer verifies it when present. --destination <path> / -Destination <path> skips the prompt.
| Platform | Download |
|---|---|
| Windows x86_64 | codesearch-windows-x86_64.zip |
| Windows x86_64 + C# | codesearch-windows-x86_64-with-csharp.zip |
| Linux x86_64 | codesearch-linux-x86_64.tar.gz |
| Linux x86_64 + C# | codesearch-linux-x86_64-with-csharp.tar.gz |
| macOS ARM64 | codesearch-macos-arm64.tar.gz |
| macOS ARM64 + C# | codesearch-macos-arm64-with-csharp.tar.gz |
Unzip, put codesearch(.exe) on your PATH; for the C# builds keep scip-csharp(.exe) next to it.
Or build from source:
git clone https://github.com/flupkede/codesearch.git
cd codesearch
cargo build --release
Index a repository
# Register and index the current repo (adds to ~/.codesearch/repos.json)
codesearch index add
# Register and index a repo from outside the repo folder
codesearch index add /path/to/my-project
# Incremental update (only changed files)
codesearch index /path/to/my-project
# Full rebuild
codesearch index /path/to/my-project --force
codesearch index add is intended to be run from inside the repo you want to register — pass the path explicitly if launched from elsewhere. First-time indexing takes 2–5 minutes; subsequent runs are incremental (10–30s) and branch switches re-index automatically. Use codesearch index list/rm/prune to manage registrations (see Serve Mode).
Embedding model
The default quantized MiniLM model favors startup speed and a small download. For multilingual text and notes, EmbeddingGemma 300M is available as a quantized ONNX model with retrieval-specific query and document prompts:
codesearch --model embeddinggemma-q4 index /path/to/notes --force
Changing models requires a full reindex because embedding dimensions and vector
spaces are model-specific. Keep the same model selected for later indexing runs.
Search rejects a --model value that differs from the indexed model and points
to the required --force rebuild instead of mixing incompatible vector spaces.
In serve mode the model is resolved per repository, from each index's own
metadata, not from a hub-wide setting: a hub may hold indexes built with
different models, and every query is embedded with the model of the repo it
targets (mixed-model groups are fine). codesearch serve --model <name> sets a
default for newly created indexes: a repo added without an explicit model
(e.g. codesearch index add with no --model, delegated to serve) is indexed
with it, and it is reported in GET /status as default_model. It never
overrides an index that already records its own model — to change an existing
repo's model, re-index that repo
(codesearch --model <name> index <path> --force) and restart serve. A repo
whose metadata.json records no model (a legacy index built before the
recording contract) is queried with the built-in 384-dim default rather than the
serve default, and the search response carries a warning naming the assumed model
and the re-index command.
MCP Configuration
codesearch connects to AI agents via MCP. Two modes:
| Mode | How | Best for |
|---|---|---|
| Local (stdio) | codesearch mcp — single repo, auto-index + file watching |
Working on one project |
| Serve (HTTP) | codesearch serve — multi-repo, TUI dashboard, lazy FSW |
Multiple repos, cross-repo search |
Local / Single Repo
The agent spawns codesearch mcp as a subprocess. It auto-detects the nearest index and starts a file watcher.
OpenCode — ~/.config/opencode/config.json:
{
"mcp": {
"codesearch": {
"type": "local",
"command": ["codesearch", "mcp"],
"enabled": true
}
}
}
Claude Code / Claude Desktop — ~/.config/claude-code/config.json or claude_desktop_config.json (identical schema):
{
"mcpServers": {
"codesearch": {
"command": "codesearch",
"args": ["mcp"]
}
}
}
Serve / Multi-Repo
Start the server first, then connect your agent. The server manages all registered repos with a TUI dashboard, lazy filesystem watchers, and idle eviction.
# Start the server (default port 39725)
codesearch serve
OpenCode — connect via HTTP:
{
"mcp": {
"codesearch": {
"type": "remote",
"url": "http://127.0.0.1:39725/mcp",
"enabled": true
}
}
}
Claude Code / Claude Desktop — force serve connection via --mode client:
{
"mcpServers": {
"codesearch": {
"command": "codesearch",
"args": ["mcp", "--mode", "client"]
}
}
}
Note: In multi-repo mode, agents must specify
projectorgroupin tool calls.statusalways works without scope.get_chunkauto-routes when the chunk_id is unique across repos; if ambiguous, it returns candidates and requiresproject.
Agent Guidance (making agents use codesearch, not grep)
codesearch publishes instructions to every MCP client on connect (via the initialize handshake) — when to reach for codesearch vs grep/glob, which tool to pick, and the serve-mode caveats. Most clients (OpenCode, Cursor) surface these automatically.
If your agent skips codesearch and falls back to grep/glob too often, paste this quickstart into its rules (AGENTS.md for Claude Code/OpenCode, .cursorrules for Cursor):
Prefer codesearch for semantic, cross-file, or symbol-oriented lookup ("where is X implemented", "find usages of Y", "how does Z flow"). Use plain grep/glob for a single known file, trivial one-line edits, or exact literal searches. In remote-serve mode, returned paths are from the server's filesystem — read content via
get_chunkrather than opening paths locally, and unindexed dirs (.venv,node_modules,build/) simply return nothing.
OpenCode: put this in the user-level ~/.config/opencode/AGENTS.md (applies across all projects), or install the OpenCode plugin, which injects this guidance with the resolved project scope automatically. Claude Code reads a project-level AGENTS.md, so add it per-project (or symlink a shared one).
Claude Code specifically tends to ignore this advice more than other clients — its MCP tool schemas are deferred (an extra ToolSearch call is needed before codesearch tools are even callable), while Grep/Glob are always fully loaded and zero-friction, and spawned subagents don't inherit AGENTS.md or the MCP initialize instructions at all.
To make the preference structural instead of advisory, this repo ships five Claude Code hooks (four PreToolUse guards plus one PostToolUse companion):
grep-guard— onGrep. Blocks a grep against an in-repo path when codesearch covers that repo (the target repo — resolved from the grep target's own git root — is registered with the serve hub in~/.codesearch/repos.json, or aCODESEARCH_SERVERenv var is set for remote-serve setups), with a message telling the model how to load and call codesearch instead. Grep is auto-allowed only when the serve hub is genuinely down, established by a live probe of the unauthenticated/healthzendpoint (CODESEARCH_SERVER>127.0.0.1:$CODESEARCH_SERVE_PORT>127.0.0.1:39725); only a connection-level failure counts as down. A low-confidence or empty codesearch result is a successful call meaning "reformulate the query", so it does not open the escape hatch — the deny message steers tofind/explore/a single clean term instead. Greps outside any registered repo are never blocked, and the hook fails open (never traps the model).edit-guard— onEdit/Write/MultiEdit. Blocks an edit to a file in a codesearch-registered repo until codesearch was consulted for that exact path within the last 5 minutes —find_impactfor SCIP-backed languages (.cs .ts .tsx .mts .cts),find(kind="usages")for everything else — making the caller-aware-editing protocol structural. Its companionedit-guard-post(PostToolUse) records the markers on everyfind_impactcall and everyfind(kind="usages"); any outcome counts ("no results" included), so the guard can never wedge. Unregistered repos, non-git paths and hook failures fail open.subagent-preamble— onAgent(the subagent-spawn tool). Prepends a short codesearch preamble to every subagent prompt, since subagents otherwise don't inheritAGENTS.mdor MCP instructions at all — including the edit-guard protocol above.web-guard— onWebSearch/WebFetch. When you have remote documentation projects mounted (codesearch remote mount, e.g.cloud/inriver,cloud/example-dam), it blocks the first web call with guidance to search those indexed mounts first — often more precise and current than the open web. Same 5-minute retry-escape; when no mounts are configured it does nothing.
Install (idempotent — user scope applies to every project; --project is this repo only):
codesearch hooks claude install # preferred — self-contained, all platforms
codesearch hooks claude install --project # project scope (./.claude)
The native command embeds the hook scripts in the binary (no source tree needed) and merges the registrations into settings.json. The equivalent from-source installers still live in integrations/claude-code/ (install.ps1 / install.sh) if you'd rather run them directly.
OpenCode gets the same structural treatment through the OpenCode v2 plugin in integrations/opencode/: it resolves the session directory to an indexed project, injects scope-aware guidance once per session, rescues empty greps with index hits, optionally prunes or blocks grep/glob, keeps the serve hub healthy (with optional auto-start), and adds /codesearch* commands, a codesearch_scope tool, a skill and compaction assistance. Install by copying codesearch.ts into ~/.config/opencode/plugins/ — see the integration README.
Note: the grep-guard detects "codesearch is available for this repo" via that repo's registration with the serve hub (~/.codesearch/repos.json, honoring the CODESEARCH_REPOS_CONFIG / CODESEARCH_HOME overrides) or CODESEARCH_SERVER — not by checking whether a codesearch process is running (that runs almost constantly as a multi-repo hub and would false-fire in every directory), and not via a local .codesearch.db directory (a stale db from a since-unregistered repo used to deny Grep even though the hub could not answer for it). For a remote-serve setup with no local registration, set CODESEARCH_SERVER to opt back into enforcement.
MCP Tools Reference
search — Code Search
| Parameter | Type | Description |
|---|---|---|
query |
string | Natural language, code snippet, regex, or exact term |
mode |
"semantic" | "literal" |
Search backend (default: semantic) |
filter_path |
string | Path prefix filter (semantic mode) |
file_glob |
string | Glob filter (literal mode), e.g. "src/**/*.rs" |
language |
string | Language filter (literal mode) |
regex |
bool | Treat query as regex (literal mode) |
phrase |
bool | Exact phrase match (literal mode) |
compact |
bool | Metadata only, no code (default: true) |
limit |
int | Max results (default: 10 semantic, 20 literal) |
project |
string | Target specific repo (multi-repo) |
group |
string | Search across repo group (multi-repo) |
filter_pathsemantics by routing mode:
- Local project (stdio, or
project=<local-alias>/local group on aservehub):filter_pathis a repo-relative prefix (e.g.src,docs/api) — matched against the routed project's own root, not the<alias>/…prefix shown in results.- Federated / mounted project (
project=<peer>/<alias>or an@peergroup fan-out):filter_pathis matched client-side on the namespaced result path (<peer>/<alias>/…) — i.e. exactly the path you see in the results — because the peer only matches its own un-namespaced store paths. The hub over-fetches from the peer and post-filters.Both modes now work without any client-side workaround; earlier releases dropped every hit when
filter_pathwas combined with a serve-routed or federated project.
Semantic mode combines vector similarity (fastembed) + BM25 lexical scoring + exact identifier boosting, fused with RRF. Best for conceptual queries and mixed natural-language + symbol searches.
Literal mode uses Tantivy FTS. Use regex=true for patterns with punctuation (foo::bar, Vec<T>). Use phrase=true for multi-word exact matches.
find — Symbol Navigation
| Parameter | Type | Description |
|---|---|---|
symbol |
string | Symbol name or file path (for imports) |
kind |
"definition" | "usages" | "imports" | "dependents" |
Navigation type |
definition_kind |
string | Filter: Function, Class, Method, Struct, Trait, Enum, Interface |
project / group |
string | Multi-repo routing |
explore — File Exploration
| Parameter | Type | Description |
|---|---|---|
target |
string | File path (outline) or chunk_id (similar) |
kind |
"outline" | "similar" |
Exploration type |
limit |
int | Max results for similar mode |
project / group |
string | Multi-repo routing |
Outline returns all top-level symbols in a file (kind, signature, line range). Similar finds semantically related chunks to a given chunk_id.
get_chunk — Read Code
| Parameter | Type | Description |
|---|---|---|
chunk_id |
int | Chunk ID from search/explore results |
context_lines |
int | Extra lines before/after (0-20, default: 0) |
project |
string | Disambiguate if chunk_id exists in multiple repos |
In multi-repo mode: auto-routes when chunk_id is unique; returns candidates list when ambiguous.
find_impact — Symbol Reference Impact
Find all call-sites and references to a symbol with file/line precision — the recommended tool for "who calls X?" / "what breaks if I rename X?". Powered by per-language SCIP semantic analysis; precision backends ship per language: C# (bundled scip-csharp helper) and TypeScript (via npx scip-typescript, resolved on the host on demand — no bundle shipped), more planned. When no backend is available for a language, find_impact reports it — fall back to find kind="usages" (lexical) only then.
| Parameter | Type | Description |
|---|---|---|
symbol_name |
string | Symbol name (e.g. "FieldDefinition.Validate") |
file |
string | File path for position-based lookup |
line |
int | Line number for position-based lookup |
language |
string | Language hint (auto-detected from file extension) |
project / group |
string | Multi-repo routing |
Returns a list of references with file, start_line, end_line, and kind (e.g. "call", "definition"). Exposes index_age_seconds so agents can reason about staleness.
Note: SCIP precision requires the
-with-csharprelease variant (or a separately installedscip-csharphelper) for C#, andnpx(withscip-typescript, fetched on first use) on the host's PATH for TypeScript. Without a backend for a language,find_impactreturns a clear message — usefind kind="usages"as the lexical fallback. See C# Semantic Search.
On a running codesearch serve the same lookup is available over plain REST — POST /find-impact with the identical request body, no MCP session required (same auth class as the other read-only REST endpoints).
status — Index Info
| Parameter | Type | Description |
|---|---|---|
kind |
"index" | "projects" |
What to query |
project / group |
string | Multi-repo routing |
Serve Mode (Multi-Repo)
For working across multiple repositories simultaneously:
codesearch serve
This starts a background HTTP server with:
- TUI dashboard (ratatui) showing repo status, CPU usage, active sessions
- Lazy filesystem watchers — activated on first query per repo
- Idle eviction (30min) — unused repos are unloaded from memory
- Session tracking via MCP keep-alive
TUI Keyboard Shortcuts
| Key | Action |
|---|---|
↑ / ↓ |
Navigate repo list |
i |
Show info overlay (chunks, files, model, DB size) |
d |
Run doctor diagnostics on selected repo |
n |
Force reindex selected repo |
r |
Remove selected repo (with confirmation dialog) |
l |
Reload repos config from disk |
q |
Quit serve |
Repository Registration
Repos are registered via codesearch index add:
# Register a repo (creates index + adds to ~/.codesearch/repos.json)
codesearch index add /path/to/my-project
# Remove a repo
codesearch index rm /path/to/my-project
# List registered repos
codesearch index list
# Clean up stale entries (relocates moved repos, drops the rest;
# serve also does this itself at startup and on every status refresh)
codesearch index prune
Serve reads ~/.codesearch/repos.json on startup and manages all registered repos.
Moved, renamed or deleted repositories
If you rename or move a registered folder, serve does not crash. On startup
it tries to relocate each missing repo automatically: it captures every
repo's git remote (remote.origin.url) at registration, and on a missing path
it scans nearby folders (bounded depth, override with
CODESEARCH_RELOCATE_MAX_DEPTH, default 3) for a git checkout with the same
remote. A single unambiguous match is rewritten into repos.json; otherwise the
entry is logged and skipped (never indexed against a dead path).
When a path is unrecoverable, serve now unregisters it by itself — at
startup, and again on every background status refresh — so a deleted repo or
worktree stops showing up as a not indexed ghost on its own (worktree deletion
fires no git hook, and rm -rf bypasses every observer, so serve reconciles
its own registry instead). codesearch index prune stays available as the
manual trigger for the same sweep, e.g. while serve is not running.
A hand-edited repos.json is also tolerated: empty entries, orphaned metadata,
and group references to unknown repos are cleaned up on load rather than
crashing.
Questions sur codesearch MCP
Quels outils codesearch MCP fournit-il ?
Il expose 20 outils, dont query, mode, filter_path, file_glob, language.
Est-ce que codesearch nécessite un GPU ou Docker ?
Non. Il s'exécute uniquement sur CPU avec une empreinte de quelques centaines de Mo et ne nécessite pas Docker.
Quels clients MCP sont compatibles avec codesearch ?
Il fonctionne avec OpenCode, Claude Code, Cursor et n'importe quel client MCP, via stdio ou HTTP.
Puis-je changer le modèle d'embedding après l'indexation ?
Oui, mais cela nécessite une réindexation complète car les dimensions d'embedding et les espaces vectoriels sont spécifiques à chaque modèle.