contextd
contextd is a local-first, privacy-preserving semantic context daemon for AI coding agents.
It watches your local workspaces, chunks source code and documents with Tree-sitter and PDF/plugin extractors, generates ONNX embeddings locally, stores vectors and full-text indexes in SQLite WAL (sqlite-vec + FTS5), and exposes hybrid retrieval over MCP stdio, HTTP REST, and CLI.
Why contextd?
- 100% Local — Your code and embeddings never leave your machine
- MCP Native (
2025-06-18) — One-command auto-setup (contextd connect --all) for 9 AI tools including Claude Desktop, Claude Code, Cursor, VS Code Copilot, Codex, OpenCode, Continue, Copilot CLI, and Antigravity - Hybrid Search — Combines
sqlite-vecKNN vector similarity with tokenized SQLiteFTS5keyword search via normalized Reciprocal Rank Fusion (RRF) - Concurrent WAL Storage — Dedicated 8-connection read-only
r2d2reader pool, transactional writes,blake3incremental change detection, and batched ONNX inference - Polyglot Smart Chunking — Tree-sitter AST splitting for Rust, Python, JS/JSX, TS/TSX, and Go, plus Markdown headers, built-in PDF extraction, and timeout- and output-capped external format parser subprocesses
- Hardened by Default — Loopback DNS-rebinding checks, mandatory Bearer auth on non-loopback binds, untrusted workspace config isolation,
O_NOFOLLOWreads, secret/binary exclusions, and SHA-256 verified model downloads
Getting Started
Install
One-line installer (Linux/macOS, SHA-256 verified)
curl -fsSL https://raw.githubusercontent.com/sandy-sachin7/contextd/main/scripts/install.sh | bash
Cargo (Crates.io, Rust 1.95+)
cargo install contextd --locked
Windows (PowerShell, SHA-256 verified)
irm https://raw.githubusercontent.com/sandy-sachin7/contextd/main/scripts/install.ps1 | iex
Homebrew (macOS/Linux)
brew install --HEAD --build-from-source ./homebrew/contextd.rb
Docker
The container binds 0.0.0.0:3030 inside the container, so CONTEXTD_AUTH_TOKEN is required:
docker run --rm -p 127.0.0.1:3030:3030 \
-e CONTEXTD_AUTH_TOKEN=replace-with-strong-token \
-v "$PWD:/workspace:ro" \
ghcr.io/sandy-sachin7/contextd
From source
git clone https://github.com/sandy-sachin7/contextd.git
cd contextd
cargo build --release --locked
./target/release/contextd setup
Run as Daemon
# Download and verify the default embedding model
contextd setup
# Start the daemon (watches your configured directories and serves HTTP on 127.0.0.1:3030)
contextd daemon
# Or run one-off hybrid queries from the CLI
contextd query "authentication system" --limit 10 --context 2
Connect your AI Tool
Auto-configure all detected AI tools (Claude Desktop, Claude Code, Cursor, VS Code Copilot, Copilot CLI, OpenCode, Continue, Antigravity, Codex):
contextd connect --all
See the Integrations section for manual setup guides.
Configuration
contextd uses a TOML configuration file. Resolution order:
- Explicit
--config <path>CLI flag (global across all subcommands) - Workspace-local
./contextd.toml - User-global config (
~/.config/contextd/contextd.tomlon Linux,~/Library/Application Support/contextd/contextd.tomlon macOS) - Platform defaults (
~/.local/share/contextd/contextd.dband~/.local/share/contextd/models)
Workspace config trust
A workspace-local ./contextd.toml is untrusted. Only [watch] and [chunking]
apply from it. The [server] and [storage] sections come from the user-global
config, or from platform defaults when no user-global config exists. [plugins]
requires allow_workspace_plugins = true in the user-global config or the
--trust-workspace-plugins CLI flag.
To change network or storage settings, use the user-global config or an
environment override below. An explicit --config <path> outside the user
config directory is also treated as untrusted for those sections unless you
explicitly pass --trust-config (which allows [server], [storage], and
[plugins] from that file).
Environment Variable Overrides
| Variable | Description |
|---|---|
CONTEXTD_HOST | HTTP API bind host (default 127.0.0.1) |
CONTEXTD_PORT | HTTP API bind port (default 3030) |
CONTEXTD_AUTH_TOKEN | Bearer token (required when binding non-loopback hosts) |
CONTEXTD_DB_PATH | SQLite database path |
CONTEXTD_MODEL_PATH | Root directory for model-specific cache folders |
CONTEXTD_MODEL_TYPE | all-minilm-l6-v2, all-mpnet-base-v2, or bge-small-en-v1.5 |
CONTEXTD_WATCH_PATHS | Colon/semicolon/comma-separated list of directories to watch |
CONTEXTD_MAX_FILE_SIZE | Maximum file size in bytes (default 2097152) |
Example
[server]
host = "127.0.0.1"
port = 3030
[storage]
db_path = "~/.local/share/contextd/contextd.db"
model_path = "~/.local/share/contextd/models"
model_type = "all-minilm-l6-v2"
[watch]
paths = ["."]
debounce_ms = 500
max_file_size = 2097152
[chunking]
max_chunk_size = 1500
overlap = 150
[security]
allow_workspace_plugins = false
[plugins]
docx = ["pandoc", "-t", "plain"]
Ignoring Files
contextd automatically excludes secrets (.env*, *.pem, *.key, id_rsa), binary files, and heavy build directories (.git/, node_modules/, target/, .venv/, __pycache__/, dist/, build/). It also respects .gitignore and .contextignore.
Usage
contextd provides six subcommands: daemon, mcp, setup, query, connect, and completions.
daemon(default) — Runs as a background service, watches configured paths, maintains the SQLite WAL index, and serves the hardened HTTP REST API.mcp— Runs as an async JSON-RPC 2.0 / MCP stdio server for AI tool integrations.setup— Downloads and SHA-256 verifies the configured ONNX embedding model.query— Executes one-off hybrid semantic + FTS5 searches directly from the terminal.connect— Auto-detects and configures MCP settings for 9 AI tools with.bakbackups.completions— Generatesbash,zsh, orfishshell completion scripts.
Global Flags
These flags work before or after any subcommand:
-c, --config <PATH>— Explicit TOML configuration file path.--trust-config— Explicitly trust a--configfile located outside the user config directory (allows[server],[storage], and[plugins]).--trust-workspace-plugins— Explicitly trust and execute[plugins]from a workspace-local./contextd.toml.
CLI
Daemon Mode (Background Service)
contextd daemon
contextd daemon --config /path/to/contextd.toml --trust-config
# Optional: exit when stdin closes (useful when spawned by an editor extension)
contextd daemon --exit-on-stdin-eof
Query Mode (One-off Hybrid Queries)
contextd query "authentication"
contextd query "database schema" --limit 10 --min-score 0.5 --file-types rs,sql --context 2
contextd query "API changes" --paths src/,docs/ --after 2025-01-01 --before 2026-12-31
Setup Mode
Downloads and SHA-256 verifies the configured embedding model from pinned HuggingFace revisions:
contextd setup
Supports all-minilm-l6-v2 (default, 384d), all-mpnet-base-v2 (768d), and bge-small-en-v1.5 (384d).
Connect Mode (AI Tool Auto-Configuration)
contextd connect --all
contextd connect --all --scope project
contextd connect --tool claude-desktop
Shell Completions
contextd completions bash > ~/.local/share/bash-completion/completions/contextd
contextd completions zsh > ~/.zfunc/_contextd
contextd completions fish > ~/.config/fish/completions/contextd.fish
REST API
The REST API is served by the daemon on the configured host:port (default 127.0.0.1:3030).
Security & Limits
- Loopback DNS-Rebinding Protection: In unauthenticated loopback mode, requests must include a loopback
Hostheader (localhost,127.0.0.1, or[::1]). - Bearer Authentication: Binding a non-loopback host (e.g.,
0.0.0.0) requiresserver.auth_tokenorCONTEXTD_AUTH_TOKEN. When configured, passAuthorization: Bearer <token>on/statusand/query(loopback/healthremains open for healthchecks). - Resource Caps: 64 KiB max request body, 16 KiB max query string, 30-second request timeout, and 64 max concurrent requests.
Health
curl http://127.0.0.1:3030/health
Response:
{
"status": "ok",
"uptime_secs": 3600
}
Status
curl http://127.0.0.1:3030/status
Response:
{
"status": "ok",
"uptime_secs": 3600,
"indexed_files": 1500,
"total_chunks": 45000,
"database_size_bytes": 52428800
}
Query
curl -X POST http://127.0.0.1:3030/query \
-H "Content-Type: application/json" \
-d '{
"query": "How does auth work?",
"limit": 5,
"min_score": 0.5,
"file_types": ["rs", "py"],
"context_lines": 2
}'
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
query | string | Yes | Search query (max 16 KiB) |
limit | number | No | Max results (default: 5, max: 100) |
max_results | number | No | Additional response cap (min(limit, max_results), max: 100) |
min_score | number | No | Minimum relevance score (0.0-1.0, finite) |
file_types | string[] | No | Filter by file extensions (e.g., ["rs", "py"]) |
paths | string[] | No | Filter by file path substrings |
start_time | number | No | Filter by earliest modification time (UNIX seconds) |
end_time | number | No | Filter by latest modification time (UNIX seconds) |
context_lines | number | No | Surrounding source lines to include (0-20) |
MCP Server
Run contextd as an async JSON-RPC 2.0 / Model Context Protocol stdio server:
# Uses trusted user-global config (~/.config/contextd/contextd.toml) or platform defaults
contextd mcp
# Or point to an explicit config outside the user config dir
contextd mcp --config /path/to/contextd.toml --trust-config
contextd mcpwrites protocol diagnostics exclusively tostderr(neverstdout) and never logs indexed source code or search result contents.
Protocol & Hardening
- Negotiated Versions:
2025-06-18(latest),2025-03-26,2024-11-05 - Frame Cap: 16 MiB max line length on
stdin - Cancellation: Honors
notifications/cancelledvia in-flight abort handles - Tool Annotations: Read-only (
readOnlyHint: true,destructiveHint: false,idempotentHint: true,openWorldHint: false)
Available Tools
search_context
Hybrid semantic (sqlite-vec KNN) + keyword (FTS5) search over your indexed codebase.
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
query | string | Yes | Natural language or keyword search query |
limit | integer | No | Max results (default: 5, max: 100) |
file_types | string[] | No | Filter by file extensions (e.g., ["rs", "py"]) |
paths | string[] | No | Filter by file path substrings |
min_score | number | No | Minimum relevance score (0.0-1.0) |
start_time | integer | No | Filter files modified at or after UNIX timestamp (seconds) |
end_time | integer | No | Filter files modified at or before UNIX timestamp (seconds) |
context_lines | integer | No | Surrounding source lines to include (0-20) |
get_status
Get the current indexing status (indexed_files, total_chunks, database_size_bytes).
Integrations
contextd works with any tool that supports the Model Context Protocol (MCP).
Claude Desktop Integration
Add contextd to your claude_desktop_config.json:
{
"mcpServers": {
"contextd": {
"command": "/path/to/contextd",
"args": ["mcp"],
"env": {}
}
}
}
Or run
contextd connect --tool claude-desktopto configure this automatically. When--configis omitted,contextd mcploads config, database, and models from platform XDG directories (~/.config/contextd/contextd.toml). If you pass a custom config path outside that directory and want its[server]/[storage]settings honored, add"--config", "/path/to/contextd.toml", "--trust-config".
Config locations:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Linux:
~/.config/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json
Usage in Claude
"Search contextd for functions that handle file indexing" "Find code related to embedding generation, only in Rust files" "Use contextd to get the indexing status"
Cline / Roo Code (VSCode)
- Open the MCP Servers settings (via the "MCP Servers" tab or command palette).
- Add a new server:
- Name:
contextd - Command:
/path/to/contextd - Args:
mcp
- Name:
When
--configis omitted,contextd mcpresolves your user-global config, database, and models from platform XDG directories. If you pass a custom config file outside your user config directory and want its[storage]/[server]settings honored, passmcp,--config,/path/to/contextd.toml,--trust-config.
Continue.dev Integration
You can configure Continue automatically with:
contextd connect --tool continue
Or configure it manually in ~/.continue/config.yaml (recommended — uses your trusted user-global ~/.config/contextd/contextd.toml or platform defaults):
mcpServers:
- name: contextd
command: /absolute/path/to/contextd
args:
- mcp
To point at a project-specific config outside your user config directory, create .continue/mcpServers/contextd.yaml and add --trust-config if you want its [storage] or [plugins] sections applied:
name: contextd
command: /absolute/path/to/contextd
args:
- mcp
- --config
- /absolute/path/to/contextd.toml
- --trust-config
Without
--trust-config, a config file outside the user config directory is treated as untrusted:[server]and[storage]remain governed by your user-global config or platform defaults, and[plugins]remain disabled.
Usage in Continue
In Continue chat, select MCP tools or ask naturally:
"Use search_context to find code about semantic search with limit 3"
Features
Hybrid Search
contextd combines sqlite-vec KNN vector similarity with full-text keyword search (SQLite FTS5) across CLI, HTTP API, and MCP:
- Semantic (
sqlite-vec): Cosine similarity via local ONNX embeddings (WHERE embedding MATCH ?1 AND k = ?2), with progressivekexpansion when file, path, or time filters are active. - Keyword (
FTS5): Sanitized, tokenizedORqueries using the Porter stemming tokenizer (porter unicode61), with SQL filters applied beforeLIMIT. - Normalized Fusion: Reciprocal Rank Fusion (
k = 60) normalized to[0.0, 1.0]and blended with semantic cosine similarity.
Search Ranking Pipeline
- Vector KNN fetches top candidates (
clamp(limit * 5, 50, 200)) viasqlite-vecand applies recency decay (default weight0.1) and logarithmic frequency boost (default weight0.1). - FTS5 Keyword Search fetches top keyword matches with SQL filters applied prior to
LIMIT. - Normalized RRF combines both rank lists into
[0.0, 1.0]and blends rank consensus with vector similarity. - Filtering & Truncation applies
min_score, sorts deterministically (mappingNaNto0.0), truncates tolimit, and resolves optionalcontext_linesonly for the final results.
Smart Chunking
contextd uses Tree-sitter AST parsing for semantic code splitting:
| Language | Strategy | AST Nodes Captured |
|---|---|---|
| Rust | Tree-sitter | function_item, impl_item, struct_item, enum_item, mod_item, trait_item |
| Python | Tree-sitter | function_definition, class_definition, decorated_definition |
| JavaScript | Tree-sitter | function_declaration, class_declaration, export_statement, lexical_declaration, expression_statement |
| TypeScript | Tree-sitter | Same as JS + interface_declaration, type_alias_declaration |
| Go | Tree-sitter | function_declaration, method_declaration, type_declaration, const_declaration, var_declaration |
| Markdown | Header-based | Sections by heading hierarchy |
| Page/form-feed | Paragraph split | |
| Other | Paragraph split | By blank lines |
Plugin System
Extend indexing to additional file formats via external converter commands. Native Tree-sitter chunkers (Rust, Python, JS/JSX, TS/TSX, Go), Markdown splitting, plain text, and built-in PDF extraction (pdf-extract) work out of the box — plugins are only needed for extra formats like .docx, .odt, .epub, or .ipynb.
Plugins are invoked with -- <canonical_file_path> appended as the final arguments and must write UTF-8 text to stdout.
Configuration
Configure [plugins] in your trusted user-global config (~/.config/contextd/contextd.toml on Linux, ~/Library/Application Support/contextd/contextd.toml on macOS):
[plugins]
# External PDF override (wrapper strips the leading `--` guard before calling pdftotext)
pdf = ["./scripts/pdftotext.sh"]
# Office documents (requires pandoc)
docx = ["pandoc", "-t", "plain"]
odt = ["pandoc", "-t", "plain"]
rtf = ["pandoc", "-t", "plain"]
epub = ["pandoc", "-t", "plain"]
# Jupyter notebooks (requires jupyter nbconvert)
ipynb = ["jupyter", "nbconvert", "--to", "markdown", "--stdout"]
Security & Trust Model
- Workspace Isolation:
[plugins]defined in a workspace-local./contextd.toml(or an untrusted--configfile) are disabled by default to prevent arbitrary command execution when indexing untrusted repositories. Enable explicitly via--trust-workspace-plugins,--trust-config, orsecurity.allow_workspace_plugins = truein your user-global config. - Flag-Injection Guard:
contextdalways inserts--before the canonicalized file path so filenames starting with-cannot be interpreted as flags. Custom wrapper scripts should strip an optional leading--(seescripts/pdftotext.sh). - Execution Limits:
stdinis bound to/dev/null, child processes usekill_on_drop(true), execution times out after 30 seconds,stdoutis capped at 10 MiB, and output must be valid UTF-8.
Search Intelligence
contextd layers three ranking and presentation signals on top of sqlite-vec KNN + FTS5 hybrid retrieval:
Recency Boost
Recently modified files rank higher during vector candidate scoring. The boost decays smoothly by 50% every 24 hours:
recency_boost = 1.0 / (1.0 + age_hours / 24.0)
Default recency_weight in SearchOptions is 0.1.
Frequency Ranking
Files that are repeatedly matched gain a logarithmic priority boost using the query_hits table:
frequency_boost = ln(1 + hit_count) * frequency_weight
Default frequency_weight in SearchOptions is 0.1.
Smart Context Windows
When context_lines (1-20) is requested via CLI (--context), HTTP API, or MCP (search_context), contextd reads surrounding lines and computes 1-indexed line_start / line_end bounds from disk only for the final top-N results after ranking and truncation.
Embedding Models
Embedding Models Guide
contextd supports multiple local ONNX embedding models for different speed/quality trade-offs.
Available Models
| Model | Dimensions | Pooling | Best For |
|---|---|---|---|
all-minilm-l6-v2 (default) | 384 | Mean | General purpose FP32 (~91 MB) |
all-minilm-l6-v2-q8 | 384 | Mean | Quantized int8 (~22 MB), faster CPU indexing and lower cold query latency |
all-mpnet-base-v2 | 768 | Mean | Higher quality, recommended for code |
bge-small-en-v1.5 | 384 | CLS | Balanced quality/speed for retrieval |
All supported models are downloaded from pinned HuggingFace commit revisions and verified with SHA-256 checksums before installation.
Each model uses its own subdirectory under model_path. A model switch loads the selected model's files and keeps the other model caches.
Configuration
Set the model in your contextd.toml (or via CONTEXTD_MODEL_TYPE):
[storage]
model_type = "all-mpnet-base-v2"
Switching Models
- Update
model_typein your config. - Run setup to download and verify the model files:
contextd setup - Remove or point
db_pathat a new SQLite database file and restartcontextd daemon. contextd recordsmodel_typeandembedding_dimin the databasemetatable and will fail fast with a clear error if an existing database does not match the active model.
Architecture
┌──────────────────┐
│ Watcher + Walk │ → 500ms Debounce → Default Secret/Build Exclusions + .gitignore/.contextignore
└──────────────────┘
│
▼
┌──────────────────┐
│ safe_read + │ → O_NOFOLLOW / Reparse-Point Guard → Binary Sniff (8 KiB) → blake3 Hash
│ PathCoordinator │
└──────────────────┘
│
▼
┌──────────────────┐
│ Parser/Chunker │ → Tree-sitter (Rust/Py/JS/TS/Go) / Markdown / PDF / Sandboxed Plugins
└──────────────────┘
│
▼
┌──────────────────┐
│ Batched Embedder │ → ONNX Runtime (SHA-256 Pinned Models, Mean/CLS Pooling, L2 Norm)
└──────────────────┘
│
▼
┌──────────────────┐
│ SQLite WAL v2 │ → Transactional Writer + 8-Conn Reader Pool + sqlite-vec KNN + FTS5
└──────────────────┘
│
▼
┌──────────────────┐
│ Query Layer │ → MCP stdio (2025-06-18) / Hardened Axum HTTP / CLI
└──────────────────┘
Components
Daemon (src/daemon.rs)
The orchestration layer that manages the indexing lifecycle:
- Initial scan streamed from
WalkBuilderwith bounded worker concurrency (available_parallelism().clamp(2, 8)) - Startup reconciliation that prunes deleted files under active watch roots
- File watcher via
notify-debouncer-miniwith500msdefault debounce (watch.debounce_ms) - Per-path coalescing (
PathCoordinator) andblake3+(mtime_ns, file_size)fast-skipping for incremental updates - Symlink-safe regular file reads via
safe_read(O_NOFOLLOWon Unix, reparse-point checks on Windows)
Embedder (src/indexer/embeddings.rs, src/download.rs)
Local ONNX Runtime inference pipeline:
- Tokenizes input text via HuggingFace
tokenizers - Batched ONNX Runtime inference (
embed_batch) with Mean pooling (all-minilm-l6-v2,all-mpnet-base-v2) or CLS pooling (bge-small-en-v1.5) - L2 normalization for cosine similarity across 384d and 768d models
- Pinned HuggingFace commit downloads verified by SHA-256 into per-model cache subdirectories
Storage (src/storage/db.rs)
SQLite schema v2 in WAL mode:
- Single transactional writer (
Mutex<Connection>) + 8-connection read-onlyr2d2reader pool (PRAGMA query_only = ON) chunks_vec(sqlite-vecKNN virtual table) +chunks_fts(Porter-stemmed FTS5 virtual table)- Normalized Reciprocal Rank Fusion (RRF) with progressive filter over-fetching
metatable validatingschema_version,model_type, andembedding_dimon openquery_hitstable for logarithmic frequency ranking
Query Layer (src/api/mod.rs, src/mcp/server.rs, src/cli.rs)
Three async interfaces:
- HTTP REST API: Hardened Axum server (loopback
Hostvalidation, mandatory Bearer auth on non-loopback binds, 64 KiB body cap, 30s timeout, 64 concurrent requests) - MCP Server: Async stdio JSON-RPC 2.0 server (
2025-06-18, 16 MiB frame cap,notifications/cancelled) - CLI: One-off hybrid search (
contextd query) and AI tool auto-configuration (contextd connect)
See ARCHITECTURE.md for the full design and trust-boundary documentation.
Testing
contextd includes unit, doctest, integration, MCP end-to-end, benchmark, and memory-stress suites.
Test Suites
| Suite | Command | Coverage |
|---|---|---|
| Unit & Library Tests | cargo test --lib --bins --locked | Config & trust isolation, Tree-sitter/PDF chunking & UTF-8 budgets, safe_read (O_NOFOLLOW), ignore/secret exclusions, external parser plugins, SQLite WAL/sqlite-vec/FTS5 hybrid search, HTTP API security middleware, MCP server, connect, download |
| Doc Tests | cargo test --doc --locked | Crate-level embedded library quickstart in src/lib.rs |
| Integration Tests | cargo test --tests --locked | watcher_test (file events/renames/deletes), load_test (concurrent HTTP API + rapid edits), zero_config_test (model cache & setup) |
| Embedded Example | cargo run --example embedded_search | Offline Tree-sitter + SQLite WAL hybrid search library usage |
| MCP E2E Suite | CONTEXTD_BIN=./target/debug/contextd python3 scripts/test_mcp_local.py | 17 end-to-end JSON-RPC 2.0 / MCP protocol, validation, cancellation, and edge-case checks |
| Memory Stress | python3 scripts/memory_stress_test.py | Large corpus (10K files, 1K queries) memory-bound check |
| Benchmarks | cargo bench --locked / bash scripts/bench.sh | Criterion benchmarks (chunker_bench, db_bench) |
Running the Full Verification Suite
# Formatting, lints, and rustdoc
cargo fmt --all -- --check
cargo clippy --all-targets -- -D warnings
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --locked
# All Rust tests (unit, doc, integration)
cargo test --locked
# Offline embedded example
cargo run --example embedded_search
# MCP end-to-end tests
CONTEXTD_BIN=./target/debug/contextd python3 scripts/test_mcp_local.py
# Shell script syntax checks
bash -n scripts/install.sh scripts/playground.sh scripts/pdftotext.sh
Contributing to contextd
Thank you for contributing to contextd! Whether you are fixing a bug, improving retrieval quality, adding language chunkers, or tightening security boundaries, this guide will get you productive quickly.
Please also review our Code of Conduct, Architecture Guide, and Security Policy.
Prerequisites
- Rust:
1.91+(MSRV enforced inCargo.toml;rust-toolchain.tomltracksstablewithrustfmtandclippy) - Python 3 (optional, for MCP end-to-end tests in
scripts/test_mcp_local.py)
Getting Started
git clone https://github.com/sandy-sachin7/contextd.git
cd contextd
cargo build --locked
Module Map
| Path | Responsibility |
|---|---|
src/main.rs | CLI entrypoint (clap), global flags (--config, --trust-config, --trust-workspace-plugins), subcommand dispatch |
src/cli.rs | setup, query, completions, date/timestamp parsing |
src/config.rs | TOML loading, workspace trust isolation, XDG path resolution, CONTEXTD_* env overrides |
src/daemon.rs | Initial scan (WalkBuilder), notify watcher loop, PathCoordinator coalescing, startup reconciliation |
src/indexer/ | Tree-sitter & text/PDF chunking (chunker.rs), ONNX batched embeddings (embeddings.rs), O_NOFOLLOW reads (safe_read.rs), ignore/secret filters (ignore.rs), sandboxed external plugins (plugins.rs), file watcher (watcher.rs) |
src/storage/db.rs | SQLite WAL storage (schema v2), r2d2 read-only pool, sqlite-vec KNN, FTS5, normalized RRF hybrid search |
src/api/mod.rs | Hardened Axum HTTP API (/health, /status, /query), DNS-rebinding & Bearer auth middleware |
src/mcp/server.rs | JSON-RPC 2.0 / MCP stdio server (search_context, get_status, cancellation, frame limits) |
src/connect.rs | Auto-configuration for 9 AI tools with JSONC/TOML preservation and .bak backups |
src/download.rs | Pinned HuggingFace downloads, SHA-256 verification, per-model cache directories & legacy migration |
Verification Checklist
Before opening a pull request, run the full local verification suite:
# Formatting
cargo fmt --all -- --check
# Linting (zero warnings)
cargo clippy --all-targets -- -D warnings
# Rustdoc build (zero warnings)
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --locked
# Unit, doc, and integration tests
cargo test --locked
# Offline embedded library example
cargo run --example embedded_search
# MCP end-to-end test suite (17 checks)
CONTEXTD_BIN=./target/debug/contextd python3 scripts/test_mcp_local.py
# Shell script syntax checks (if scripts changed)
bash -n scripts/install.sh scripts/playground.sh scripts/pdftotext.sh
If you modify CLI flags or subcommands, regenerate shell completions:
cargo run -- completions bash > completions/contextd.bash
cargo run -- completions zsh > completions/_contextd
cargo run -- completions fish > completions/contextd.fish
Commit & Pull Request Conventions
We use Conventional Commits:
feat:— new user-facing capabilityfix:— bug fixperf:— performance improvementsecurity:— security hardening or vulnerability fixdocs:— documentation or mdBook updatesrefactor:— code restructuring without behavior changetest:— adding or updating testschore:— tooling, CI, or dependency maintenance
Guidelines for smooth reviews:
- Keep PRs focused on a single concern and include unit/integration tests for all behavior changes.
- Never log user source code or search result contents to
stdoutorstderr. - Preserve security invariants (trust boundaries,
O_NOFOLLOW, loopback/auth gates, bounded inputs). - Update relevant docs in
README.md,ARCHITECTURE.md, ordocs/book/src/when changing user-facing behavior.
Security Issues
Do not report security vulnerabilities in public issues or PRs. Follow SECURITY.md to submit a private GitHub Security Advisory.
License
By contributing to contextd, you agree that your contributions will be licensed under the MIT License.