Code Context MCP
README.md
# Code Context MCP
A Model Context Protocol server that gives AI coding assistants a persistent,
searchable understanding of a codebase. It indexes a repository at structural
boundaries (functions, methods, classes, ...), embeds every chunk, stores it
all in SQLite, and exposes hybrid semantic + keyword search, relationship
exploration and a knowledge-note memory through MCP tools. The index stays in
sync with the working tree, so assistants stop rediscovering the project each
session.
```
repository ──scan──► changed files ──tree-sitter──► chunks + metadata ──embed──► SQLite
(.gitignore aware) (size/mtime/hash) (15 grammars) (calls, bases, imports) (fastembed) (FTS5 + vectors + notes)
│
AI assistant ◄──── MCP (stdio / HTTP) ◄──── hybrid search · relationships · notes ◄──────────┘
```
## Install
Requires Python 3.11+.
```bash
# recommended: isolated CLI install
pipx install ethicaldilkhush-code-context-mcp
# or with uv
uv tool install ethicaldilkhush-code-context-mcp
# or into a virtualenv
pip install ethicaldilkhush-code-context-mcp
```
The first semantic index downloads the local embedding model (~70 MB, once).
After that the default setup runs offline. Use `--embedder hash` to skip the
model for a fast lexical-only mode.
```bash
code-context index /path/to/repo
code-context search -r /path/to/repo "where are retries handled"
code-context serve /path/to/repo # MCP server on stdio
```
Every CLI command takes `-r/--repo` (default: `$CODE_CONTEXT_REPO` or the
current directory) and `--json`. Commands: `index [--full] [--watch]`,
`status`, `search`, `context`, `show <chunk_id>`, `related <chunk_id | -s symbol>`,
`outline <file>`, `symbol <name>`, `overview`, `notes add|list|search|delete`, `serve`.
### Develop from this repository
```bash
python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"
.venv/bin/code-context --version
.venv/bin/python -m pytest
```
## Connecting an AI assistant
The server speaks MCP over stdio by default (`--transport http` serves
streamable HTTP on `127.0.0.1:8765/mcp`). On startup it indexes in the
background and then watches the repository for changes.
**Cursor** (`.cursor/mcp.json` or `~/.cursor/mcp.json`):
```json
{
"mcpServers": {
"code-context": {
"command": "uvx",
"args": ["ethicaldilkhush-code-context-mcp", "serve", "${workspaceFolder}"]
}
}
}
```
If you installed with `pipx`, use the installed binary instead:
```json
{
"mcpServers": {
"code-context": {
"command": "code-context",
"args": ["serve", "${workspaceFolder}"]
}
}
}
```
This repository also ships a local `.cursor/mcp.json` that points at the
editable `.venv` install for development.
**Claude Code**:
```bash
claude mcp add code-context -- uvx ethicaldilkhush-code-context-mcp serve /path/to/repo
```
**Claude Desktop** (`claude_desktop_config.json`): same `command`/`args`
shape as above with an absolute repository path.
**MCP Inspector** (interactive testing):
```bash
npx @modelcontextprotocol/inspector uvx ethicaldilkhush-code-context-mcp serve /path/to/repo
npx @modelcontextprotocol/inspector --cli uvx ethicaldilkhush-code-context-mcp serve /path/to/repo \
--method tools/call --tool-name search_code --tool-arg query="parse config file"
```
The server can also start with no repository; the assistant then calls
`index_repository(path=...)` to choose one, and can switch repositories the same way.
## MCP interface
| Tool | Purpose |
| --- | --- |
| `index_repository` | Index or update incrementally (`full_rebuild`, or `path` to switch repos). Waits up to `wait_seconds`, then keeps going in the background. |
| `index_status` | State, progress, per-language counts, embedding coverage, files with issues, recent runs, on-disk freshness. |
| `search_code` | Hybrid / semantic / keyword search with `language`, `kind` and `path` filters. |
| `get_context` | One call for a task: top results with full source, their calls and callers, more locations, relevant notes. |
| `find_symbol` | Definitions by name or qualified name (`Server.Start`, `billing::Invoice`). |
| `get_code` | Complete source of a result, plus parent, members, file notes and optional live surrounding lines. |
| `read_file` | Read a file or line range from disk, confined to the repository. |
| `get_file_outline` | Symbols of a file with line ranges and signatures, its imports and its importers. |
| `get_related` | Calls, callers, base types, subclasses, members and file dependencies, each with a confidence level. |
| `get_call_graph` | Multi-level call graph (`out` = callees, `in` = callers). |
| `repository_overview` | Languages, layout, entry points, most referenced symbols, largest types, README intro, notes. |
| `save_note` / `update_note` / `delete_note` | Persistent knowledge, optionally linked to a path and/or symbol. |
| `search_notes` / `list_notes` | Retrieve knowledge by meaning, tag or path. |
Resources: `codecontext://overview`, `codecontext://status`, `codecontext://notes`.
Prompt: `explore_codebase(task)` walks an assistant through orient → gather context → follow relationships → record notes.
All results are structured JSON. Every chunk carries `chunk_id`, `path`,
`start_line`/`end_line`, `location`, `language`, `kind`, `name`,
`qualified_name`, `signature`, `docstring`, `calls` and `bases`. Search
results add `score`, `matched_by` (`semantic`, `keyword`, `exact_name`, ...)
and a preview.
## How it works
**Scanning** (`scanner.py`): uses `git ls-files` when available, so
`.gitignore` is honoured exactly; otherwise it walks the tree with the root
`.gitignore`. Dependency and build directories, minified and generated files,
empty files and files over `max_file_kb` are skipped, and the skips are
counted by reason in the index report.
**Parsing and chunking** (`chunker.py`, `languages.py`): tree-sitter grammars
for Python, JavaScript, TypeScript, TSX, Go, Rust, Java, C, C++, C#, Ruby,
PHP, Swift, Kotlin and Bash. Each function, method, constructor, class,
interface, struct, enum, trait, impl, protocol, extension or type alias
becomes a chunk. The chunk includes its decorators and leading doc comments
and records:
- the qualified name (`ns.Class.method`; Go receivers and out-of-line C++ methods are attached to their type);
- the signature and docstring;
- the parent chunk;
- base types;
- called names;
- the file's imports.
Classes are embedded as a skeleton with member bodies elided, so they don't
drown out their methods. Code between definitions becomes `module` chunks.
Markdown is split by heading and other text by blank-line-aware windows.
Syntax errors don't stop parsing: the file is flagged and still chunked.
**Embeddings** (`embeddings.py`): the default is local `fastembed`
(`BAAI/bge-small-en-v1.5`, ONNX, CPU, no API key). `openai` uses any
OpenAI-compatible `/embeddings` endpoint. `hash` is a deterministic
feature-hashing embedder that needs no model. With the default `auto`
setting, the server falls back to `hash` when the model can't load, and
reports this in the status output.
**Storage** (`store.py`): one SQLite database per repository, by default under
`~/.code-context/indexes/`, in WAL mode so the CLI and a running server can
share it. It holds:
- files (hash, mtime, status, issues);
- chunks (metadata, source, float32 embedding);
- an FTS5 table;
- call and inheritance references;
- imports;
- notes, with their own FTS5 table and embeddings;
- the history of indexing runs.
**Search** (`search.py`):
- Semantic search is cosine similarity against an in-memory matrix that reloads when the index changes.
- Keyword search is FTS5 BM25. It weights names over signatures, docstrings and code, and indexes the sub-words of camelCase and snake_case identifiers, so `user name` finds `getUserName`.
- Hybrid search fuses both rankings with Reciprocal Rank Fusion (k = 60). It adds a bonus when the query names a symbol (exact or all its sub-words) and slightly discounts module and glue chunks.
**Relationships** (`relations.py`): imports are resolved to repository files
per language: Python modules and relative imports, relative JS/TS paths with
extension and index lookup, C includes, Go packages, Rust `mod`/`use`,
Java/Kotlin packages, PHP namespaces, Ruby `require_relative` and Bash
`source`. Calls and inheritance are matched by name within the same language
family. Each edge's confidence is `high` when the two pieces of code share a
file or one imports the other, `medium` for the same directory, and `low`
otherwise.
**Knowledge that improves over time**: notes are stored in the same database,
embedded, and returned by `search_notes`. They are also attached to code
search results on the same topic or file. A note linked to a symbol or file
records a hash of that code. When the code changes, the note is flagged
`stale` with a reason, and `update_note` re-verifies it. Notes survive
re-indexing and schema rebuilds.
**Staying in sync without re-analysing unchanged code** (`indexer.py`, `watcher.py`):
- Files whose size and mtime are unchanged are not read again. A touched file with an unchanged content hash is not re-parsed.
- Changed files are re-chunked in one transaction each. Deleted files are removed.
- Embeddings are reused for any chunk whose text was already embedded, even in another file, so renames and moves cost nothing.
- Chunks are re-embedded only when their text or the embedding model changes. Changing the chunking code re-parses everything automatically.
- While serving, a file watcher triggers an incremental run about 1.5 s after changes. `index_status` reports whether anything on disk is newer than the index.
## Errors and visibility
- Every anticipated failure is a `CodeContextError` whose message is shown verbatim, as a CLI error or an MCP tool error with `isError: true`. Examples: no repository configured, path outside the repository, unknown chunk id, nothing indexed yet, empty query.
- Unexpected exceptions become a one-line internal error. The indexer never takes the server down.
- Unreadable, binary, non-UTF-8 or syntactically broken files are recorded with their issue and listed in `index_status`. The rest of the repository still indexes.
- Database failures (locked, corrupt, unwritable) raise `StoreError` naming the database file and suggesting `index --full`.
- If embedding fails, the run finishes as `partial`: keyword search keeps working, the error is reported, and the next run embeds the remaining chunks. In hybrid mode, search falls back to keyword results with a warning.
## Configuration
| Setting | Environment variable | `.codecontext.toml` key | Default |
| --- | --- | --- | --- |
| Repository | `CODE_CONTEXT_REPO` | - | CLI argument / cwd |
| Data directory | `CODE_CONTEXT_HOME` | - | `~/.code-context` |
| Database file | `CODE_CONTEXT_DB` | - | `<home>/indexes/<repo>-<hash>.db` |
| Embedder | `CODE_CONTEXT_EMBEDDER` | `embedder` | `auto` (`fastembed`, `openai`, `hash`) |
| Embedding model | `CODE_CONTEXT_EMBEDDING_MODEL` | `embedding_model` | `BAAI/bge-small-en-v1.5` / `text-embedding-3-small` |
| Max file size | `CODE_CONTEXT_MAX_FILE_KB` | `max_file_kb` | `1024` |
| Extra excludes | - | `exclude = ["docs/generated/**"]` | - |
| OpenAI-compatible endpoint | `CODE_CONTEXT_OPENAI_BASE_URL`, `CODE_CONTEXT_OPENAI_API_KEY` / `OPENAI_API_KEY` | `openai_base_url` | `https://api.openai.com/v1` |
`.codecontext.toml` lives in the repository root. API keys are read only
from the environment and are never stored or logged.
## Demo
From a checkout of this repository:
```bash
.venv/bin/python examples/demo_client.py # this repository, neural embeddings
.venv/bin/python examples/demo_client.py /path/to/repo --embedder hash
```
The demo launches the server over stdio, like a real client, and runs two
sessions. In session 1 the assistant indexes the repository, reads the
overview, searches "how does hybrid search combine semantic and keyword
results", fetches the full source of the top hit, follows its calls and
callers, and saves a note about what it learned. Session 2 is a new server
process (a new chat): it checks the index status, finds the note with
`search_notes`, and gets the note back attached to `get_context` for a
related task.
## Tests
```bash
.venv/bin/python -m pytest
```
The suite covers:
- chunking for every language;
- incremental indexing (unchanged, touched, changed, deleted and renamed files, embedding reuse);
- invalid input (binary, non-UTF-8, syntax errors, unsupported, ignored and empty files);
- embedding outage and recovery;
- embedder changes;
- the file watcher;
- the search modes and filters;
- path confinement;
- import resolution across languages;
- calls, callers, inheritance and call graphs;
- notes (persistence, staleness, validation);
- corrupt databases;
- the full MCP tool workflow through an MCP client.
## Limitations
- Relationships are name based, without type inference. A method call such as `x.save()` links to every same-language `save`, ranked by confidence and flagged when ambiguous.
- Vector search is brute force over an in-memory matrix. That is fast up to roughly 100k chunks; beyond that, an ANN index would be the next step.
- The `hash` fallback embedder is lexical, not semantic. Status output and search warnings say when it is active.
- The first `fastembed` run downloads the model and needs network access. After that everything runs offline.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues