
Contextweaver
io.github.wchiwayPublished by GitHub account wchiwayv1.5.4Updated Oct 24, 2026
Semantic code retrieval engine with hybrid search, context expansion, and 40+ language support.
Overview
A local MCP server that gives an AI assistant semantic code search over an indexed repository, plus file listing, symbol lookup and index statistics.
- What you can do
- Search a codebase semantically with hybrid vector and keyword retrieval, returning packed code snippets with surrounding context and import expansion, with filters by glob, language and output size. Browse indexed files by glob, language or count. Look up likely definitions and text references for a symbol name. Read index, search and health statistics for a project. Indexing runs automatically on the first query and can be kept current with a watch mode.
- When to use it
- Useful when an assistant needs to find relevant code across a larger multi-language repository without reading whole files, or to locate where a symbol is defined or referenced. Less useful for small projects or for exhaustive exact text matching, which the README says should be done with grep.
- Requirements
- Runs as a local process via npm package @chiway/contextweaver on Node.js 20 or newer. Requires an embedding API key, base URL and model (EMBEDDINGS_API_KEY, EMBEDDINGS_BASE_URL, EMBEDDINGS_MODEL) and a reranker API key, base URL and model (RERANK_API_KEY, RERANK_BASE_URL, RERANK_MODEL), configured in a local env file. Network access to those API endpoints is needed for indexing and semantic search.
Installation
In SourceWeft
- Open Contextweaver in the dashboard and add it to a workspace.
- Enable the server for the chats that should use its tools.
Desktop only via STDIO. STDIO servers start a local process, so they need the SourceWeft desktop host.
Other MCP clients
Follow the launch instructions in the repository.
README
ContextWeaver
🧵 A codebase context engine woven for AI agents
Semantic Code Retrieval for AI Agents — Hybrid Search • Graph Expansion • Token-Aware Packing
[npm version] [npm downloads] [GitHub stars] [MCP Bridge] [Install in VS Code] [Install in VS Code Insiders]
English · 简体中文
ContextWeaver is a semantic retrieval engine purpose-built for AI coding assistants. It combines hybrid search (vector + lexical), intelligent context expansion, and token-aware packing to deliver precise, relevant, and context-complete code snippets to LLMs.
[ContextWeaver architecture overview]
✨ Core Features
🔍 Hybrid Retrieval Engine
- Vector Retrieval: deep semantic understanding via similarity
- Lexical Retrieval (FTS): exact matching for function names, class names, and other technical terms
- RRF Fusion (Reciprocal Rank Fusion): intelligently merges multiple recall channels
🧠 AST Semantic Chunking
- Tree-sitter parsing: supports TypeScript, JavaScript, Python, Go, Java, Rust, C, C++, C#, and more
- Dual-Text strategy:
displayCodefor presentation,vectorTextfor embedding - Gap-Aware merging: handles code gaps intelligently while preserving semantic integrity
- Breadcrumb injection: vector text carries hierarchical paths to boost recall
- UTF-16 character-domain normalization: offsets are unified via
SourceAdapter.toCharOffsetbefore writing metadata, preventing multi-byte character slicing errors (v1.4.0+)
📊 Three-Stage Context Expansion
- E1 Neighbor expansion: adjacent chunks within the same file, preserving block completeness
- E2 Breadcrumb completion: sibling methods under the same class/function for structural understanding
- E3 Import resolution: cross-file dependency tracking (configurable toggle)
🎯 Smart TopK Cutoff
- Anchor & Floor: dynamic threshold plus an absolute floor as dual safeguards
- Delta Guard: prevents misjudgment in Top1-outlier scenarios
- Safe Harbor: the first N results only check the floor, guaranteeing baseline recall
🔌 Native MCP Support
- MCP Server mode: launch a Model Context Protocol server with one command
- Multi-tool granularity (v1.5.0+): beyond core semantic retrieval, adds dedicated tools for structure browsing, symbol references, symbol definitions, and statistics
- Intent/term separation: an LLM-friendly API design
- Auto-indexing: the first query triggers indexing automatically; incremental updates are transparent
⚡ Query Cache & File Watching (v1.5.0+)
- Query cache (QueryCache): in-process per-project LRU cache (50 entries by default); a hit skips the entire vector recall / rerank / expansion pipeline
- Automatic cache invalidation: the cache key is composed of
normalized query + projectId + index version + search-config fingerprint, so it invalidates automatically after an index update or config change — stale results are never returned - Watch mode:
contextweaver watchwatches the filesystem and triggers incremental indexing automatically, with debouncing (500ms by default) and scan de-duplication (no concurrent scans)
📈 Statistics & Observability (v1.5.0+)
- Three metric groups: indexing process, search quality/behavior, health/consistency
- Dual exits:
contextweaver statsCLI (with--json) plus the MCPstatstool - Consistency diagnostics: automatically detects abnormal migration state,
pending_marksbacklog, missing vector rows, and more — with suggested fixes
🛡️ Crash-Safe Data Architecture (v1.4.0+)
- Single source of truth for content: LanceDB stores only vectors and locating metadata; content is read back from
files.content, reducing index size by 30–50% - Cross-store transactional compensation: three-stage write LanceDB → FTS+outbox → SQLite mark, with automatic rollback or replay on any failure
- Migration state machine:
pending/done/abortedpersisted, auto-rebuilt on crash recovery - Cross-process mutual exclusion: an advisory lock prevents the MCP server and CLI from triggering LanceDB migration concurrently
- chunk_id de-duplication: pre-delete before write to avoid duplicate rows on retry
📦 Quick Start
Requirements
- Node.js >= 20
- pnpm (recommended) or npm
Installation
Initialize Configuration
Edit ~/.contextweaver/.env and fill in your API keys:
Index a Codebase
Watch Mode (v1.5.0+)
watch runs one full incremental scan on startup, then listens to filesystem events; changes trigger a de-duplicated scan within the debounce window, and paths excluded by ignore rules never trigger a scan.
Local Search
Structure Browsing & Symbol Lookup (v1.5.0+)
The following commands are CLI mirrors of MCP tools, with zero Embedding API cost:
Statistics (v1.5.0+)
Start the MCP Server
Index Management (v1.4.0+)
🔧 MCP Integration
Claude Desktop Configuration
Add the following to your Claude Desktop config file:
MCP Tools Overview (v1.5.0+)
ContextWeaver exposes 5 MCP tools, following a layered design of "semantic retrieval first, structure browsing second":
codebase-retrieval Parameters
list-files Parameters
find-references Parameters
get-symbol-definition Parameters
Note:
find-referencesandget-symbol-definitionare heuristic text lookups over indexed chunks, not compiler-accurate navigation. For exhaustive raw text matching, usegrepoutside MCP.
Design Philosophy
- Intent/term separation:
information_requestdescribes "what to do",technical_termsfilters "what it's called" - Same-file context first: same-file context is provided by default; cross-file exploration is initiated by the agent
- Return to agent instincts: the tool only locates; cross-file exploration is triggered by the agent on demand
🏗️ Architecture
Core Modules
Data Architecture (v1.4.0+)
Key invariants:
- The single source of truth for content is
files.content;ChunkContentLoaderslices viastart_index/end_index(same source asdisplayCode) - All LanceDB offset fields live in the UTF-16 character domain; multi-byte files are never sliced incorrectly
- Cross-store write order: LanceDB → (FTS + outbox single transaction) → SQLite mark + clear outbox
- LanceDB migration state
pending/done/abortedis persisted, with cross-process mutual exclusion via an advisory lock - The query cache key is bound to the index version and search-config fingerprint; it invalidates on any index or config change
📁 Project Structure
⚙️ Configuration Reference
Environment Variables
Search Parameter Env Overrides (v1.5.0+)
The following environment variables override built-in defaults; out-of-range values are automatically clamped to the valid interval. When only one of wVec/wLex is set, the other is automatically set to 1 - x.
Search Config Parameters (built-in defaults)
🌍 Multi-Language Support
ContextWeaver natively supports AST parsing for the following languages via Tree-sitter:
Other languages fall back to line-based chunking and can still be indexed and searched normally.
🔄 Workflows
Indexing Flow
Search Flow
📊 Performance Characteristics
- Query cache: repeated queries hit the LRU cache, skipping the entire recall/rerank/expansion pipeline (v1.5.0+)
- Incremental indexing: only changed files are processed; re-indexing is 10x+ faster
- Batch embedding: adaptive batch size with concurrency control
- Rate-limit recovery: automatic backoff on 429 errors, gradual recovery
- Connection pool reuse: pooled Tree-sitter parsers
- File index caching: lazy-loaded file-path index in GraphExpander
- Zero-cost metadata tools:
list-files/find-references/get-symbol-definitiondo not call the Embedding API (v1.5.0+)
📈 Statistics & Observability (v1.5.0+)
contextweaver stats outputs three sections:
- Indexing process: cumulative index run count, last index time, last-run snapshot (added/modified/deleted/unchanged/skipped/errors + vector index details)
- Search quality/behavior: cumulative queries, cache hit rate, actual compute runs, plus average per-stage latency (retrieve / rerank / expand / pack) and average recalled seed count
- Health/consistency: file count and total content size, LanceDB vector row count, embedding dimensions, index version, migration state,
pending_marks, language breakdown
When an abnormal migration state, pending_marks backlog, or missing vector rows are detected, the report appends diagnostic warnings with the corresponding fix commands. The --json output maps to StatsReport for scripts and monitoring systems.
🐛 Logging & Debugging
Log file location: ~/.contextweaver/logs/app.YYYY-MM-DD.log
Set the log level:
🚨 Troubleshooting (v1.4.0+)
LanceDB Migration Stuck (aborted state)
Symptom: contextweaver index errors with "LanceDB is in the aborted state, refusing to write to prevent schema pollution."
Cause: during the v1.4.0 upgrade, the old LanceDB index's display_code differs from the current files.content by >1% on sampling (typically on legacy indexes whose chunk offsets used the UTF-8 byte domain).
Fix:
You can also run contextweaver stats first to view diagnostic warnings and confirm the current migration state and pending_marks backlog.
Cross-Process Migration Race
If the MCP server is long-running and another terminal runs contextweaver index, the two processes contend for migration. v1.4.0 introduces an advisory lock with a 10-minute zombie threshold, automatically letting one process skip migration while the other completes it.
If the lock gets stuck (after kill -9), clear it manually:
Wasted Duplicate Embeddings
v1.4.0 solves this via the pending_marks outbox: when an FTS write succeeds but the vector_index_hash mark fails, it is replayed automatically on the next launch, avoiding duplicate embeddings.
Search Results Don't Reflect Recent Changes
Confirm incremental indexing has run (or enable contextweaver watch for automatic increments). The query cache key is bound to the index version, so old cache entries invalidate automatically after an index update — no manual clearing needed.
📄 License
This project is licensed under the MIT License.
🙏 Acknowledgements
- Tree-sitter - high-performance syntax parsing
- LanceDB - embedded vector database
- MCP - Model Context Protocol
- Source - Source repository
Made with ❤️ for AI-assisted coding
Source: README.md at commit f1c4fc3
Tools
0Version history
1- v1.5.4LatestSep 16, 2026
Score
50% of the applicable checks met
How complete this listing is, computed from the registry entry, the endpoint and public sources. Not a rating of the server and not a statement that it is safe or working today: reachability is a dated check, and no installs or reviews go into the score.
- Reached in the last 30 days25 pts
Keep the endpoint answering the MCP handshake; SourceWeft probes it every 30 days.
- Auth declared10 pts
Declare the credential headers in the registry entry, or keep the endpoint answering the probe so its auth can be classified.
- Tools listed15 pts
Answer tools/list without a credential, or ship a package that starts in a sandbox without one.
- DescriptionRequired15 pts
- Logo10 pts
- Documentation15 pts
- License10 pts