Skip to main content
Glama

coderag

Code search for a single repository that combines BM25 and vector retrieval, scores itself against a set of golden queries, and runs as an MCP server so coding agents can use it.

I built it because the two usual approaches both fail on code in predictable ways. Keyword search finds parseConfig when you type its name and finds nothing when you type "where do settings get loaded". Embedding search handles the paraphrase and then ranks a test file or a README paragraph above the function you wanted. coderag runs both, fuses the rankings, and gives you an eval harness so changes to chunking or ranking are measured instead of eyeballed.

What it does:

  • Chunks Python, Go, TypeScript and JavaScript with tree-sitter at function, method, class and type boundaries, keeping doc comments with the code they describe. Markdown is split by heading, other text by overlapping line windows.

  • Indexes incrementally. A manifest of file hashes means an unchanged repo re-embeds zero chunks, and an edited file only re-embeds that file.

  • Searches in vector, bm25 or hybrid mode (Reciprocal Rank Fusion), with filters for language, chunk kind and path glob, and optional cross-encoder reranking.

  • Evaluates with hit@1, recall@k, MRR and nDCG@k, compares modes side by side, and can fail a CI job when a metric drops.

  • Exposes search_code, get_chunk, index_status and reindex over MCP (stdio or streamable HTTP).

Quickstart

Requires Python 3.11+ and uv.

git clone https://github.com/jonthdiaz/coderag
cd coderag
uv sync                      # add --all-extras for the reranker
uv run coderag index .
uv run coderag search "reciprocal rank fusion"
  1    0.0294  src/coderag/fusion.py:1-11  module  [bm25 #8, vector #8]
  2    0.0292  src/coderag/fusion.py:14-44  function reciprocal_rank_fusion  [bm25 #7, vector #10]
  3    0.0282  src/coderag/search.py:1-25  module  [bm25 #10, vector #12]

The brackets show where each retriever ranked the hit before fusion. Those ranks are low because tests/test_fusion.py and the docs fill the top of both lists; the test and prose demotion described below moves the implementation back up. The index lives in .coderag/ inside the target repo and ignores itself, so it never shows up in git status.

By default coderag uses an offline hashing embedder, so the commands above work without a model server. For real semantic search, point it at any OpenAI-compatible embeddings endpoint. With Ollama:

ollama pull nomic-embed-text
export CODERAG_EMBEDDING_PROVIDER=openai
export CODERAG_EMBEDDING_BASE_URL=http://localhost:11434/v1
export CODERAG_EMBEDDING_MODEL=nomic-embed-text
export CODERAG_EMBEDDING_QUERY_PREFIX="search_query: "
export CODERAG_EMBEDDING_DOCUMENT_PREFIX="search_document: "
uv run coderag index .       # embedder changed, so this rebuilds the index

For OpenAI itself, set the base URL to https://api.openai.com/v1, pick a model such as text-embedding-3-small, and put the key in CODERAG_API_KEY.

Related MCP server: CodeNib MCP Server

CLI

coderag index [PATH] [--full] [--json]
coderag search "QUERY" [--mode hybrid|vector|bm25] [-k 10] [--lang go] [--kind method]
               [--path 'src/**'] [--rerank] [--code [LINES]] [--json]
coderag eval GOLDEN.yaml [--modes vector,bm25,hybrid,hybrid+rerank] [-k 10]
               [--granularity symbol|file] [--json out.json] [--markdown out.md]
               [--fail-under 0.4 --metric mrr --gate-mode hybrid] [--show-misses]
coderag serve [--transport stdio|streamable-http] [--host 127.0.0.1] [--port 8765]
coderag status

search, eval, serve and status take --repo PATH (default: the current directory).

Configuration

Settings come from defaults, then coderag.toml in the repo root, then environment variables named CODERAG_<SECTION>_<KEY>. The full list is in src/coderag/config.py. A typical file:

[index]
exclude = ["tests/fixtures/", "migrations/"]
max_file_bytes = 512000

[search]
mode = "hybrid"
rrf_k = 60          # RRF constant; smaller values favour the top of each list
candidates = 50     # hits each retriever contributes before fusion
test_weight = 0.5   # multiply scores of test files; 1.0 disables
doc_weight = 0.5    # same for Markdown, reST and plain text

[embedding]
provider = "openai"
base_url = "http://localhost:11434/v1"
model = "nomic-embed-text"

Using it from an MCP client

Claude Code:

claude mcp add coderag -- uv run --directory /path/to/coderag coderag serve --repo /path/to/your/repo

Claude Desktop (claude_desktop_config.json) or any client that launches stdio servers:

{
  "mcpServers": {
    "coderag": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/coderag", "coderag", "serve",
               "--repo", "/path/to/your/repo"]
    }
  }
}

For clients that connect over HTTP, run coderag serve --transport streamable-http and point them at http://127.0.0.1:8765/mcp. Tool reference and more examples: docs/mcp.md.

How it fits together

flowchart LR
    subgraph Indexing
        A[discover<br/>.gitignore, size cap,<br/>binary/generated filters] --> B[chunk<br/>tree-sitter / markdown / lines]
        B --> C{manifest<br/>hash changed?}
        C -- yes --> D[embed]
        C -- no --> X[skip]
        D --> E[(Chroma<br/>vectors)]
        D --> F[(BM25<br/>JSON)]
    end
    subgraph Query
        Q[query] --> V[vector top-N]
        Q --> L[BM25 top-N]
        V --> R[RRF fusion]
        L --> R
        R --> P[test and prose priors]
        P --> RR[optional rerank]
        RR --> OUT[results]
    end
    E --> V
    F --> L
    OUT --> CLI[CLI]
    OUT --> MCP[MCP server]
    OUT --> EV[eval harness]

More detail on each stage and the reasoning behind it: docs/architecture.md.

Why hybrid

Code queries come in two flavours. Some name the thing (UserStore.get, "retry_with_backoff"). Others describe it ("where do we give up on a slow request"). BM25 with a tokenizer that splits camelCase and snake_case is very good at the first kind and useless at the second when the words don't overlap. Embeddings handle descriptions but blur exact identifiers, and they happily return a test or a doc paragraph that talks about the function instead of the function.

Reciprocal Rank Fusion combines the two rankings using ranks only, so there's no need to make BM25 scores and cosine similarities comparable. A chunk that both retrievers rank fairly high beats one that a single retriever ranks first. When the two fail on different queries, fusion recovers most of what either one misses. How much it recovers depends on how different the retrievers are, which the numbers below show.

Evaluation

examples/golden/self.yaml has 28 queries over coderag's own source, each with the expected file and symbol. These are real numbers from coderag eval on this repository at v0.1.0, using the offline hash embedder (hash-v1-512), not a neural model. k = 10.

Did search land in the right file (--granularity file):

mode

hit@1

recall@10

MRR

nDCG@10

vector (hash)

0.786

1.000

0.872

0.895

bm25

0.714

1.000

0.836

0.878

hybrid

0.786

1.000

0.887

0.914

hybrid + rerank

0.571

0.982

0.721

0.784

Did it land on the exact function or method (--granularity symbol, the default):

mode

hit@1

recall@10

MRR

nDCG@10

vector (hash)

0.286

0.661

0.424

0.477

bm25

0.214

0.625

0.355

0.417

hybrid

0.214

0.714

0.385

0.465

hybrid + rerank

0.143

0.679

0.305

0.390

At file level hybrid has the best MRR and nDCG and ties the vector mode on hit@1. At symbol level the hash "vector" mode beats it on MRR and nDCG, and hybrid only wins on recall. I don't think that says much about hybrid search in general: the hash embedder is itself a fuzzy keyword model (tokens plus character trigrams), so the two retrievers are correlated and fusion has little to work with. The cross-encoder (ms-marco-MiniLM-L-12-v2, trained on web passages) made results worse and cost about 1.5 s per query on CPU.

The change that mattered most was demoting test files and prose. With both priors off, hybrid file-level MRR is 0.603 instead of 0.887, because tests and docs describe each function in the same words as the queries.

How the set was built, per-query misses, and how to reproduce: docs/evaluation.md. I haven't run the eval with a neural embedding model yet, so there are no numbers for one here.

Limitations

  • One repository per index and per server process.

  • Nested .gitignore files are honoured, but a deeper file can't re-include something an outer file excluded (!pattern across files). Global git excludes are not read.

  • tree-sitter chunking covers Python, Go, TypeScript/TSX and JavaScript. Rust, Java and the rest fall back to line windows.

  • BM25 has no stemming, so "embedding" does not match "embedder". Several of the misses in the eval come from this.

  • The golden set is small (28 queries) and I wrote it, on code I wrote. The test and prose priors were tuned on the same queries. Treat the numbers as a regression baseline for this repo, not a benchmark.

  • Module docstrings are chunked with the imports and constants around them, and that chunk often outranks the function the query is about.

  • If indexing dies halfway, the next run repeats the in-flight files. It never trusts a half-written manifest, but it can leave orphaned vectors until those files are indexed again.

Roadmap

  • Run and publish the eval with nomic-embed-text and a code-specific embedding model.

  • Light stemming or subword matching in the BM25 tokenizer.

  • A code-trained reranker, or skip reranking when both retrievers already agree.

  • Query-time expansion of symbols into their callers and callees using the tree-sitter parse.

  • Watch mode that reindexes on file save.

  • More grammars (Rust and Java first).

Development

make install   # uv sync --all-extras
make lint      # ruff check + ruff format --check
make test      # pytest, no network
make eval      # index this repo and score it against examples/golden/self.yaml

See CONTRIBUTING.md. MIT licensed.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      C
      maintenance
      Provides a local-first code indexing and search engine for coding agents via MCP, enabling precise codebase queries, symbol lookup, and freshness-aware retrieval.
      -
    • A
      license
      Not graded
      quality
      A
      maintenance
      Provides coding agents with searchable codebase context through an MCP server, enabling hybrid BM25 and semantic search, symbol graph navigation, and dependency mapping over an incrementally maintained repository index.
      220 PyPI
      112
      Apache 2.0
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables MCP-based hybrid semantic code search over repositories, providing tools for searching code by meaning or keyword, retrieving symbol definitions, finding usages, reading chunks, and listing indexed repos.
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Provides coding agents with read-only MCP tools to search Python repositories, retrieve size-bounded cited source context, analyze dependency impact, and check index status—all via local incremental AST indexing and BM25 retrieval.
      MIT