
Mcp Local Rag
io.github.damoqiongqiu由 GitHub 账号 damoqiongqiu 发布v0.21.0更新于 Oct 24, 2026
Semantic code & doc search with keyword boost. AST code nav, auto HF mirror, local, privacy-first.
概览
本地 RAG 服务器,在本机索引代码与文档,让 AI 助手进行语义检索、代码符号导航并管理索引。
- 可以做什么
- 导入单个文件、内存文本或整个目录,代码按 AST 分块、文档按语义分块,PDF 图形可选视觉描述,开启监视后文件变动会自动重新导入。以语义加关键词的混合方式检索索引,可按路径范围或时间范围过滤,并展开命中位置前后的上下文。代码导航,查找符号定义及其全部引用。索引管理,列出文件及导入状态、删除条目、查看统计信息。维护操作,热更新配置、检测重复文件、导出索引,以及全量或仅针对变更文件重建索引。
- 适用场景
- 适合让助手回答关于本地代码库或文档集的问题、定位函数及其调用方,或在不上传云端的前提下检索私有资料。对经常变动且可在本地建立索引的项目尤为合适。
- 运行要求
- 通过 npx 作为本地进程运行,需要 Node.js。用 BASE_DIR 或 BASE_DIRS 指定要索引的目录,DB_PATH 和 CACHE_DIR 指定向量数据库与模型存放位置。首次运行需从 HuggingFace 下载嵌入模型,可通过 HTTPS_PROXY、HTTP_PROXY、HF_ENDPOINT 或自动镜像链完成。无需 API 密钥或账号。
安装
在 SourceWeft 中
- 打开 控制台中的 Mcp Local Rag,将其添加到工作区。
- 为需要使用其工具的对话启用该服务。
Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。
其他 MCP 客户端
参照 仓库 中的启动说明。
README
[MCP Local RAG — Search below the surface.]
MCP Local RAG
[GitHub stars] [npm version] [License: MIT] [TypeScript] [MCP Registry]
🍴 Forked from shinpr/mcp-local-rag — original work by Shinsuke Kagawa
Local code intelligence engine for AI coding assistants. AST-level semantic chunking + keyword boost for pinpointing functions, classes, and APIs — fully private, zero setup.
📖 中文文档
Table of Contents
- Features
- Quick Start
- Core Concepts
- 3.1 Dual-Strategy Chunking
- 3.2 Hybrid Search
- 3.3 Security Boundary
- MCP Tool Reference
- 4.1 Ingest Tools
- 4.2 Search Tools
- 4.3 Management Tools
- 4.4 Code Intelligence
- 4.5 System Tools
- CLI
- 5.1 Basic Commands
- 5.2 CLI Configuration
- Network & Models
- 6.1 Mirror Auto-Detection
- 6.2 Model Selection
- 6.3 File Watching
- Search Tuning
- Performance Tuning
- Configuration Reference
- Troubleshooting
- Development
1. Features
- Smart dual-strategy chunking — AST-level code chunking via tree-sitter (splits at function/class/method boundaries, injects scope chain + imports). Semantic chunking for documents (splits by meaning, not character count).
- Semantic search + keyword boost — Vector search first, then keyword matching boosts exact terms.
useEffect, error codes, class names rank higher — not just semantically guessed. - 15 MCP tools — Ingest, search, manage, code intelligence, and system ops in one server.
- AST code intelligence —
find_definitionandfind_referencesfor IDE-level code navigation, powered by tree-sitter metadata captured at ingest time. - Three-tier mirror auto-fallback —
huggingface.co → hf-mirror.com → modelscope.cn, zero config for users in mainland China. - Runs entirely locally — No API keys, no cloud, no data leaving your machine. Works offline after the first model download.
- Zero-friction setup — One
npxcommand. No Docker, Python, or servers to manage.
2. Quick Start
Set BASE_DIR to the folder you want to search (BASE_DIRS for multiple roots — see Configuration).
2.1 Configure Your AI Coding Tool
Cursor — ~/.cursor/mcp.json:
Claude Code:
Codex — ~/.codex/config.toml:
WorkBuddy — Settings → Custom Connectors → Add:
⚠️ WorkBuddy: you MUST click "Trust" in the Custom Connectors list after adding, otherwise the server is silently blocked.
2.2 CLI Quick Start
No MCP needed — run directly from the terminal:
That's it. No Docker, Python, or server setup.
2.3 First-Time Project Indexing
3. Core Concepts
3.1 Dual-Strategy Chunking
Chunking strategy is chosen per file type:
- Code files (50+ languages) —
CodeChunkerparses source via tree-sitter AST, splits at structural boundaries (functions, classes, methods). Each chunk'scontextualizedTextincludes its scope chain and import context for precise semantic search. - Documents (PDF/DOCX/TXT/MD/HTML) —
SemanticChunkersplits into sentences, groups by embedding similarity to find natural topic boundaries. Markdown code blocks remain intact — never split mid-block.
3.2 Hybrid Search
Search = semantic similarity + keyword boost (RAG_HYBRID_WEIGHT, default 0.6):
- Query vectorization → semantic search finds most relevant chunks
- Quality filters apply (distance threshold, grouping)
- Keyword matching boosts exact-term rankings
Exact identifiers like useEffect are never buried by semantic approximations.
3.3 Security Boundary
Only files under BASE_DIR / BASE_DIRS are accessible for ingest, list, delete, or read-neighbor operations. Symlinks resolved outside roots are rejected. Sibling-prefix paths (e.g., /foo/barista when root is /foo/bar) are also blocked — prevents path traversal attacks.
4. MCP Tool Reference
15 tools organized into 5 categories.
4.1 Ingest Tools
ingest_file supports 50+ code languages. PDFs support an optional visual mode — a local VLM generates captions for figure pages, making visual content searchable. Two profiles available:
ingest_data runs Readability → Markdown → index. Perfect for web content fetched by your AI assistant. Re-ingesting replaces old versions automatically.
ingest_directory scans recursively, respects .gitignore, shows real-time progress via MCP notifications.
4.2 Search Tools
query_documents — scope accepts a single path prefix or list, restricting results to that subtree. highlightContext returns snippets around matched terms. fromTimestamp / untilTimestamp enable time-range filtering.
read_chunk_neighbors — defaults to 2 chunks before and after (like grep -C 2), max 50 each. Response includes the target chunk marked isTarget: true.
4.3 Management Tools
list_files supports scope filtering with the same prefix-match semantics as search. In large directories, scope accelerates the scan by skipping out-of-scope subtrees.
4.4 Code Intelligence
Both tools depend on AST metadata (imports, entities, scope chains) extracted by tree-sitter at ingest time. Only works for code files ingested with CodeChunker — files ingested before v0.18.7 lack this metadata and require reindex_all to rebuild.
find_references uses a two-phase strategy: (1) exact match in codeMeta.imports → (2) FTS full-text search for the symbol name. Results are deduplicated by (filePath, chunkIndex), with import references listed first.
4.5 System Tools
config hot-swaps hybridWeight, modelName, cacheDir, baseDir/baseDirs, etc. Switching models auto-disposes the old Embedder and initializes the new one — note: changing models alters the embedding space and requires reindex_all.
dedup_check is especially useful in monorepos — spot ↔ futures mirror code is typically flagged with similarity 1.0.
5. CLI
5.1 Basic Commands
query, read-neighbors, list, status, delete emit JSON to stdout (pipe to jq). ingest emits progress to stderr.
Global options (--db-path, --cache-dir, --model-name) go before the subcommand:
⚠️ The CLI does NOT read your MCP client config (
mcp.json, etc.). Configure via flags or environment variables.
5.2 CLI Configuration
Flags — global options before, subcommand options after:
--base-dir is repeatable on ingest and list:
Environment variables:
For multiple roots, use BASE_DIRS (JSON array):
Precedence: CLI flags > environment variables > defaults.
6. Network & Models
6.1 Mirror Auto-Detection
huggingface.co is inaccessible from mainland China. Built-in three-tier mirror chain with automatic fallback:
At startup, each mirror is HEAD-probed (3s timeout). The first reachable mirror with a complete API is selected:
- With proxy (
HTTPS_PROXY) → direct to huggingface.co - No proxy → auto-switch to hf-mirror.com
- hf-mirror API unavailable → fallback to modelscope.cn
No manual HF_ENDPOINT required. For manual control:
v0.18.5+ uses
setGlobalDispatcher(ProxyAgent)— all Node.js 22 network requests go through the proxy.
6.2 Model Selection
6 embedding models with alias resolution via model-registry:
Guidance: code repos → default model + high keyword boost; multilingual → consider embeddinggemma-300m; scientific papers → consider allenai-specter.
RAG_DTYPE controls ONNX precision (fp32 / fp16 / q8). Default fp32; use q8 when memory-constrained. ⚠️ Changing models or dtype requires deleting DB_PATH and re-indexing.
6.3 File Watching
Set RAG_WATCH=true — the server starts recursive fs.watch on baseDirs (500ms debounce):
- File creation/modification → auto
ingest_file - File deletion → auto
delete_file
Ideal for actively changing projects.
7. Search Tuning
Code-focused tuning (recommended default):
Document-focused tuning:
Keyword boost is applied after semantic filtering — improves precision without introducing noise.
8. Performance Tuning
Beyond search accuracy, inference performance is also configurable. All optimizations are environment variables — no code changes required.
8.1 Quantization Precision (RAG_DTYPE)
Controls ONNX model inference precision. For all-MiniLM-L6-v2, three levels are available:
⚠️ Changing dtype requires index rebuild — embedding spaces are incompatible.
Verify it works: After restart, call status via MCP and check the dtype field. Should match your setting (e.g., "fp16").
If it fails: Startup throws EmbeddingError with a list of supported dtypes. Common cause: the model doesn't provide the q8 variant — switch to fp16.
8.2 Execution Device (RAG_DEVICE)
Controls which ONNX Runtime backend to use:
⚠️ Changing device changes the embedding space — requires index rebuild. Stacks with RAG_DTYPE — fp16 + webgpu gives both model-size reduction and GPU speedup.
Verify it works: MCP startup log should show Loading model on device "webgpu". status should show device: "webgpu".
If it fails:
Unsupported deviceat startup → WebGPU unavailable in your environment, revert to"cpu"- Starts successfully but inference crashes → likely an ONNX WebGPU backend bug, revert to
"cpu" - Just delete the
RAG_DEVICEline to fall back — other config is untouched
8.3 Minimum Chunk Length (CHUNK_MIN_LENGTH)
Filters out chunks shorter than this value during ingest. Default 50 keeps nearly everything; 200 drops 30-40% of noise fragments.
⚠️ Blunt instrument — short but important code (e.g., config constants) may also be discarded. Requires index rebuild. Sweet spot: 100-200.
8.4 Recommended Configurations
All changes require reindex_all (MCP) or re-running ingest (CLI). If something breaks, delete the failing env line to revert to defaults.
9. Configuration Reference
MCP server: environment variables only (via your MCP client's env block).
CLI: environment variables + equivalent flags (flags take precedence).
Root resolution order: CLI --base-dir > BASE_DIRS > BASE_DIR > cwd. BASE_DIRS and BASE_DIR are never merged. Only JSON array syntax supported for BASE_DIRS — delimiter syntax is intentionally rejected.
10. Troubleshooting
Model download failed
Symptoms: fetch failed, status shows searchMode: fts instead of hybrid.
Solutions:
-
Network restriction (mainland China, etc.) — use proxy:
Set in your MCP client config, not the terminal. v0.18.5+ globally effective via
setGlobalDispatcher. -
Auto-mirror fallback (v0.18.2+, default) — three-tier probe. Usually works without any config.
-
Manual override —
HF_ENDPOINT=https://modelscope.cnor download models manually intoCACHE_DIR. -
npx cached old version — clear and restart:
MCP client doesn't see tools
- Verify config file syntax
- WorkBuddy users: confirm "Trust" button clicked
- Restart client completely (Cmd+Q on macOS)
- Test directly:
npx @damoqiongqiu/mcp-local-ragshould run without errors
Rebuilding the index
After switching models or when the database is corrupted:
- Stop the MCP service
- Delete
DB_PATHdirectory (default./lancedb/) — safe, doesn't affect source files - Restart MCP → fresh database auto-created
- Bulk re-ingest:
FAQ
- Private? Yes. After model download, nothing leaves your machine.
- Offline? Yes, once models are cached.
- Supported formats? 50+ code languages + PDF/DOCX/TXT/MD/HTML. No Excel, PPT, or images.
- GPU acceleration? Opt-in via
RAG_DEVICE. Support depends on your system, Node.js version, and the ONNX backend. - Backup? Copy the
DB_PATHdirectory.
11. Development
License
MIT License. Free for personal and commercial use.
Acknowledgments
Built with Model Context Protocol (Anthropic), LanceDB, and Transformers.js.
来源:README.md,提交 3e94e45
工具
0版本历史
1- v0.21.0最新Sep 16, 2026
评分
已满足适用检查项的 50%
该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。
- 近 30 天内可连通25 分
请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。
- 已声明认证方式10 分
请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。
- 已列出工具15 分
请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。
- 描述必需15 分
- 图标10 分
- 文档15 分
- 许可证10 分