Skip to main content

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+.

# 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.

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

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):

{
  "mcpServers": {
    "code-context": {
      "command": "uvx",
      "args": ["ethicaldilkhush-code-context-mcp", "serve", "${workspaceFolder}"]
    }
  }
}

If you installed with pipx, use the installed binary instead:

{
  "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:

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):

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:

.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

.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.

Metadata

Release files for ethicaldilkhush-code-context-mcp 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ethicaldilkhush-code-context-mcp 0.1.0
File Size Uploaded Provenance Actions
ethicaldilkhush_code_context_mcp-0.1.0.tar.gz 77.1 kB Without provenance Details for ethicaldilkhush_code_context_mcp-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ethicaldilkhush-code-context-mcp 0.1.0
File Interpreter ABI Platform Actions
ethicaldilkhush_code_context_mcp-0.1.0-py3-none-any.whl Python 3 none any Details for ethicaldilkhush_code_context_mcp-0.1.0-py3-none-any.whl

Total release size: 149.4 kB

Release files / ethicaldilkhush_code_context_mcp-0.1.0.tar.gz

Download URL ethicaldilkhush_code_context_mcp-0.1.0.tar.gz
Size 77.1 kB
Tags Source
SHA-256 checksum
How to use checksums
ace10bbde7a2694ba1eafa706aae059204ab97e3df08517f94940f415abb5617
BLAKE2b-256 checksum
How to use checksums
df420325f9fa4b46e0e93899010a6a67621c4b284580b236826f654be7c859d3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.4

Release files / ethicaldilkhush_code_context_mcp-0.1.0-py3-none-any.whl

Download URL ethicaldilkhush_code_context_mcp-0.1.0-py3-none-any.whl
Size 72.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a8f9300d555ca252bbc4297521cb859de91223e49a39270fb874a8e6e4fd5660
BLAKE2b-256 checksum
How to use checksums
09006d22c93599bf0bdf24b348a361f6dbef60b91496d630f0906bc5bdd97974
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.4

Security for ethicaldilkhush-code-context-mcp 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page