{
  "markdown": "<p align=\"center\">\n  <img src=\"assets/banner.jpg\" alt=\"MCP Local RAG: Search below the surface.\" width=\"600\" />\n</p>\n\n# MCP Local RAG\n\n[![GitHub stars](https://img.shields.io/github/stars/shinpr/mcp-local-rag?style=social)](https://github.com/shinpr/mcp-local-rag)\n[![npm version](https://img.shields.io/npm/v/mcp-local-rag.svg)](https://www.npmjs.com/package/mcp-local-rag)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![MCP Registry](https://img.shields.io/badge/MCP-Registry-green.svg)](https://registry.modelcontextprotocol.io/)\n\n<p align=\"center\">\n  <strong>English</strong> |\n  <a href=\"README.zh-CN.md\">简体中文</a> |\n  <a href=\"README.de.md\">Deutsch</a> |\n  <a href=\"README.es.md\">Español</a> |\n  <a href=\"README.pt-BR.md\">Português (Brasil)</a> |\n  <a href=\"README.fr.md\">Français</a>\n</p>\n\nSearch private documents from an MCP client or the terminal without sending them to an\nembedding API.\n\nmcp-local-rag indexes PDF, DOCX, Markdown, and text files on your machine. Search combines\nsemantic similarity with keyword matching, so queries can match both intent and exact technical\nterms such as API names, class names, and error codes.\n\n## Features\n\n- **Runs locally:** Document parsing, embeddings, storage, and search run on your machine.\n  After the initial model download, text ingestion and search work offline.\n- **Hybrid search:** Semantic retrieval finds related concepts, while keyword matching boosts\n  exact technical terms.\n- **Configurable embeddings:** Choose a Hugging Face embedding model that fits the language and\n  domain of your documents.\n- **Semantic chunking:** Documents are split at topic boundaries instead of fixed character\n  counts. Markdown code blocks stay intact.\n- **MCP and CLI:** Use the same index from an AI coding tool or directly from the terminal.\n\nNo API key, Docker, Python, or external database is required.\n\n## Quick Start\n\n### Requirements\n\n- Node.js 22 or later\n- Internet access on first use to download the npm package and embedding model\n- A directory containing the documents you want to search\n\nSet `BASE_DIR` to that directory. It is also the security boundary for file operations. Replace\n`/absolute/path/to/your/documents` below with the directory's absolute path.\n\nmcp-local-rag uses the standard MCP protocol over a local stdio server, so it works with AI\ncoding tools and other MCP hosts that support local MCP servers.\n\nUse one of the examples below, or register `npx -y mcp-local-rag` and set `BASE_DIR` using your\nclient's MCP configuration format.\n\n**For Claude Code:** Run this command:\n\n```bash\nclaude mcp add local-rag --scope user --env BASE_DIR=/absolute/path/to/your/documents -- npx -y mcp-local-rag\n```\n\n**For Codex:** Add to `~/.codex/config.toml`:\n\n```toml\n[mcp_servers.local-rag]\ncommand = \"npx\"\nargs = [\"-y\", \"mcp-local-rag\"]\n\n[mcp_servers.local-rag.env]\nBASE_DIR = \"/absolute/path/to/your/documents\"\n```\n\n**For OpenCode:** Add to `~/.config/opencode/opencode.json` (or `opencode.jsonc`):\n\n```json\n{\n  \"$schema\": \"https://opencode.ai/config.json\",\n  \"mcp\": {\n    \"local-rag\": {\n      \"type\": \"local\",\n      \"command\": [\"npx\", \"-y\", \"mcp-local-rag\"],\n      \"environment\": {\n        \"BASE_DIR\": \"/absolute/path/to/your/documents\"\n      }\n    }\n  }\n}\n```\n\n**For Cursor:** Add to `~/.cursor/mcp.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"local-rag\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"mcp-local-rag\"],\n      \"env\": {\n        \"BASE_DIR\": \"/absolute/path/to/your/documents\"\n      }\n    }\n  }\n}\n```\n\nRestart the client, then ask it to build the index:\n\n```text\nSync all documents in the configured root and wait until it finishes.\n```\n\nThe first sync downloads the default embedding model (about 90 MB) and may take 1–2 minutes\nbefore ingestion starts. Later runs use the local cache.\n\nOnce the sync completes:\n\n```text\nWhat does the API documentation say about authentication?\n```\n\n### CLI Quick Start\n\nTo use the CLI without an MCP client:\n\n```bash\nnpx mcp-local-rag ingest ./docs/\nnpx mcp-local-rag query \"authentication API\"\n```\n\nThe CLI uses the current directory as its document root by default. Run both commands from the\nsame directory so they use the same default index, or set `BASE_DIR` and `DB_PATH` explicitly.\n\n## Why This Exists\n\nSome document sets cannot be sent to a hosted embedding service because of confidentiality or\norganizational policy. Keeping the index local makes them searchable without adding a per-query\nAPI cost.\n\nSemantic search alone can miss exact identifiers that matter in technical documentation.\nKeyword reranking keeps those terms visible without giving up natural-language retrieval.\n\n## Supported Content\n\n| Input | How to ingest |\n|---|---|\n| PDF, DOCX, TXT, Markdown | File ingestion or directory sync |\n| HTML already fetched by the client | `ingest_data`; cleaned with Readability and converted to Markdown |\n| Plain text or Markdown held in memory | `ingest_data` with a stable source identifier |\n\nHTML fetching is not built into the server. An MCP client can fetch a page and pass its HTML to\n`ingest_data`.\n\nExcel, PowerPoint, standalone images, and source-code file extensions are not supported by file\ningestion. PDFs can optionally use a local vision model to describe figures, but this is not OCR\nor image search.\n\n## MCP Tools\n\n| Tool | Purpose |\n|---|---|\n| `sync_start` | Reconcile the index with all configured roots or one path |\n| `sync_status` | Poll a running sync job |\n| `ingest_file` | Ingest or replace one file |\n| `ingest_data` | Ingest text, Markdown, or HTML already held by the client |\n| `query_documents` | Search with semantic matching and keyword boost |\n| `read_chunk_neighbors` | Read surrounding chunks from a search result |\n| `list_files` | Show supported files and their ingestion state |\n| `delete_file` | Delete an indexed file or an `ingest_data` item |\n| `status` | Show index and search status |\n\n### Syncing a Document Root\n\n`sync_start` ingests new and changed files, skips byte-identical files, and removes index entries\nfor files that no longer exist:\n\n```text\nSync everything under the configured document roots and wait for completion.\n```\n\nThe tool returns a `jobId` immediately. Clients should poll `sync_status` until its state becomes\n`succeeded` or `failed`. A changed PDF keeps the visual profile it was indexed with; `sync_start`\ncannot change it. Set `STORE_IMAGES=true` in the MCP server environment to store supported PDF and\nDOCX images for new or changed files selected by sync; unchanged files remain skipped.\n\nOnly one sync job is retained by the server process. A newer job replaces a finished record, and\nrestarting the server discards it.\n\n### Ingesting One File\n\n`ingest_file` accepts PDF, DOCX, TXT, and Markdown. MCP file paths must be absolute and must stay\ninside a configured document root:\n\n```text\nIngest the document at /Users/me/docs/api-spec.pdf.\n```\n\nRe-ingesting the same path replaces its existing chunks.\n\n### Searching and Reading More Context\n\n```text\nWhat does the API documentation say about authentication?\nFind the documented behavior of ERR_CONNECTION_REFUSED.\n```\n\nResults contain the text, source path, title, chunk index, relevance score, and any images stored\non that chunk. MCP returns each image as an image content block paired with its result identity;\nCLI `query` includes an `images` array of `{ imageIndex, mimeType, data }` on every result. Pass the\n`chunkIndex` and either `filePath` or `source` from a result to `read_chunk_neighbors` when the\nanswer needs more context:\n\n```text\nRead the surrounding chunks for that authentication result.\n```\n\nBoth `query_documents` and `list_files` accept an optional absolute `scope` path prefix, or a\nlist of prefixes. A prefix matches the exact path and its descendants.\n\n### Ingesting HTML\n\nUse `ingest_data` after the MCP client fetches a page:\n\n```text\nFetch https://example.com/docs and ingest the HTML.\n```\n\nThe server extracts the main article, converts it to Markdown, and stores it under the supplied\nsource identifier. Reusing the same source updates the existing content.\n\nRespect the source site's terms and copyright when indexing external content.\n\n### PDF Visual Captions and Stored Images\n\nVisual mode adds a generated caption for figure-heavy PDF pages. It is opt-in and does not load\na vision model during normal ingestion.\n\n```text\nIngest /Users/me/docs/research-paper.pdf with visual: true.\n```\n\n```bash\nnpx mcp-local-rag ingest ./docs/research-paper.pdf --visual\n```\n\nImage storage is independent of visual captions. Set `STORE_IMAGES=true` for the MCP server, or\npass `--images` to CLI ingestion and sync:\n\n```bash\nnpx mcp-local-rag ingest ./docs/research-paper.pdf --images\nnpx mcp-local-rag sync ./docs/ --images\n```\n\nPDF storage uses detected figure/table regions. DOCX storage includes only PNG/JPEG images that\nthe existing Mammoth conversion emits as `<img>`; charts, SmartArt, and shapes are not separately\nrendered. Stored images follow their surrounding text into the final semantic chunk and do not\nalter ranking, scores, or result count.\n\n| `visual` / `--visual` | `STORE_IMAGES` / `--images` | PDF behavior |\n|---|---|---|\n| false | false | Text only; no visual captions or returned images. |\n| true | false | Generated captions become searchable text; no images are stored or returned. |\n| true | true | Generated captions become searchable text, and images from matched chunks are returned inline. |\n| false | true | Images are attached to nearby retained PDF text and returned inline for matched chunks; the VLM is not imported, loaded, or run. |\n\n| Profile | Model cache | Use case |\n|---|---:|---|\n| `fast` (default) | about 250 MB | Lightweight visual indexing |\n| `quality` | about 1.7 GB | Figures containing labels, annotations, or other in-image text |\n\nSelect the larger model with `visualQuality: \"quality\"` over MCP or\n`--visual-quality quality` over CLI. Measured CPU inference was about three times as slow as\n`fast`, though results depend on hardware and model updates.\n\n#### Updating Existing `quality` Captions\n\nFrom 0.18.4 `quality` runs Qwen3.5-2B; earlier versions ran Qwen2.5-VL-3B. Captions already indexed\nkeep the wording the old model produced, and `sync` will not redo them, so re-ingest the files you\nwant refreshed:\n\n```bash\nnpx mcp-local-rag ingest ./docs/research-paper.pdf --visual --visual-quality quality\n```\n\nAdd `--images` if the file was ingested with it, because a run without it replaces the stored\nimages. The old model stays on disk. Once nothing else uses it, delete\n`onnx-community/Qwen2.5-VL-3B-Instruct-ONNX/` from the model cache directory — `<cache-dir>`, which\ndefaults to `./models/`.\n\n#### Visual Mode Across Syncs\n\nThe profile a PDF was indexed with is recorded, and `sync` reuses it: a PDF indexed with `fast` or\n`quality` is re-ingested with that same profile, and a PDF with no recorded profile is ingested as\ntext.\n\n```bash\nnpx mcp-local-rag sync ./docs/                      # keep each PDF's recorded profile\nnpx mcp-local-rag sync ./docs/ --visual             # request fast for every PDF in scope\nnpx mcp-local-rag sync ./docs/ --visual --visual-quality quality\n```\n\n`--visual` overrides recorded profiles, so it also captions PDFs that were indexed as text.\nChanging a profile re-ingests the PDF even when the file itself has not changed; running the same\ncommand again does nothing and loads no model. Image settings are never recorded, so `--images`\nand `STORE_IMAGES` never cause a re-ingest.\n\nTo turn captions off for a path, run `ingest` on it: a successful normal ingest clears the\nrecorded profile. To retry a page whose captioning failed, run `ingest <path> --visual\n--visual-quality <profile>` with the profile you want — a plain `ingest` clears it instead. If a\nPDF's indexed rows disagree about the profile, sync stops before changing anything and names the\nfile; re-run it with `--visual` to settle the profile.\n\nCaptions are auxiliary text, not faithful transcriptions. Treat retrieved captions and document\ntext as untrusted input rather than instructions.\n\nAt high limits, matched chunks and their attachments can approach the model/client context ceiling;\nchoose the query limit with the calling model's available context in mind.\n\n## CLI\n\nThe CLI uses the same parser, embedder, and vector store without an MCP client:\n\n```bash\nnpx mcp-local-rag ingest ./docs/\nnpx mcp-local-rag sync ./docs/\nnpx mcp-local-rag query \"authentication API\"\nnpx mcp-local-rag query \"auth\" --scope /docs/api --scope /docs/guide\nnpx mcp-local-rag read-neighbors --file-path /abs/path.md --chunk-index 5\nnpx mcp-local-rag list\nnpx mcp-local-rag status\nnpx mcp-local-rag delete ./docs/old.pdf\nnpx mcp-local-rag delete --source \"https://example.com/docs\"\n```\n\nGlobal options such as `--db-path`, `--cache-dir`, and `--model-name` go before the subcommand.\nSubcommand options go after it:\n\n```bash\nnpx mcp-local-rag --db-path ./my-db query \"authentication\"\n```\n\nRun `npx mcp-local-rag --help` for the complete command reference.\n\nThe CLI does not read MCP client configuration. Set the same environment variables or flags if\nboth interfaces should share an index. In particular, `MODEL_NAME` and the CLI `--model-name`\nmust match for a shared database.\n\n## Search Tuning\n\nKeyword boost is enabled by default. Relevance-gap grouping and the distance and file filters are\noptional controls for corpora that need tighter result selection.\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `RAG_HYBRID_WEIGHT` | `0.6` | Keyword boost factor (0.0–1.0). 0 disables keyword reranking; 1 applies the maximum boost. |\n| `RAG_GROUPING` | (not set) | `similar` keeps the first relevance group; `related` keeps up to two, using significant vector-distance gaps as boundaries. |\n| `RAG_MAX_DISTANCE` | (not set) | Filter out low-relevance results (e.g., `0.5`). |\n| `RAG_MAX_FILES` | (not set) | Limit results to top N files (e.g., `1` for single best file). |\n\nFor API specifications and other documents containing many identifiers, a stronger keyword\nweight can improve exact-term ranking:\n\n```json\n\"env\": {\n  \"RAG_HYBRID_WEIGHT\": \"0.7\"\n}\n```\n\n- `0.7`: slightly stronger exact-term reranking than the default\n- `1.0`: maximum keyword boost\n\n## How It Works\n\nDuring ingestion:\n\n1. The parser extracts text for the input format.\n2. The semantic chunker finds topic boundaries and preserves Markdown code blocks.\n3. Transformers.js creates embeddings locally.\n4. LanceDB stores the chunks, metadata, vectors, and full-text index.\n\nDuring search:\n\n1. The query is embedded with the same model.\n2. Vector search retrieves semantically related chunks.\n3. Optional distance and relevance-group filters narrow the candidates when configured.\n4. Full-text matches boost exact query terms.\n\n## Agent Skills\n\n[Agent Skills](https://agentskills.io/) provide query and ingestion guidance for AI assistants:\n\n```bash\nnpx mcp-local-rag skills install --claude-code\nnpx mcp-local-rag skills install --claude-code --global\nnpx mcp-local-rag skills install --codex\n```\n\nInstalled skills cover query formulation, result refinement, and HTML ingestion. Ask the\nassistant to use the mcp-local-rag skill explicitly if it does not activate automatically.\n\n## Configuration\n\nThe MCP server reads environment variables. The CLI accepts the listed global environment\nvariables and flags; image storage on CLI ingestion and sync is enabled only with `--images`.\n\n| Environment Variable | CLI Flag | Default | Description |\n|---------------------|----------|---------|-------------|\n| `BASE_DIR` | `--base-dir` | Current directory | One document root; the CLI flag is repeatable on `ingest`, `list`, and `sync` |\n| `BASE_DIRS` | N/A | (unset) | JSON array of document roots; takes precedence over `BASE_DIR` |\n| `DB_PATH` | `--db-path` | `./lancedb/` | Vector database location |\n| `CACHE_DIR` | `--cache-dir` | `./models/` | Model cache directory |\n| `MODEL_NAME` | `--model-name` | `Xenova/all-MiniLM-L6-v2` | Hugging Face embedding model |\n| `MAX_FILE_SIZE` | `--max-file-size` | `104857600` (100MB) | Maximum file size in bytes |\n| `CHUNK_MIN_LENGTH` | `--chunk-min-length` | `50` | Minimum chunk length in characters (1–10000) |\n| `STORE_IMAGES` | N/A | `false` | MCP server only: store supported PDF/DOCX images and return them with matched chunks. CLI uses `--images`. |\n| `RAG_DEVICE` | N/A | `cpu` | ONNX Runtime execution device |\n| `RAG_DTYPE` | N/A | `fp32` | Embedding dtype passed to the selected model |\n\n### Document Roots (`BASE_DIR` and `BASE_DIRS`)\n\nmcp-local-rag only allows file operations inside configured roots. For multiple roots,\n`BASE_DIRS` must be a JSON array of non-empty paths:\n\n```bash\nexport BASE_DIRS='[\"/Users/me/Documents/work\",\"/Users/me/Projects/specs\"]'\n```\n\nRoot configuration is resolved in this order:\n\n1. CLI `--base-dir <path>` flags (repeatable on `ingest`, `list`, and `sync`)\n2. `BASE_DIRS`\n3. `BASE_DIR`\n4. Current directory\n\nEach source replaces the lower-priority source rather than merging with it. Invalid `BASE_DIRS`\nconfiguration fails instead of falling back to `BASE_DIR` or the current directory. `status`\nremains available in MCP so the client can report the configuration error.\n\n```bash\nnpx mcp-local-rag ingest --base-dir /Users/me/work --base-dir /Users/me/specs /Users/me/work/readme.md\nnpx mcp-local-rag list --base-dir /Users/me/work --base-dir /Users/me/specs\nnpx mcp-local-rag sync --base-dir /Users/me/work --base-dir /Users/me/specs\nBASE_DIRS='[\"/Users/me/work\",\"/Users/me/specs\"]' npx mcp-local-rag list\n```\n\n### Storage and Models\n\n`DB_PATH` and `CACHE_DIR` are relative to the process working directory by default. Set absolute\npaths when the MCP client may start the server from different project directories.\n\nSet `MODEL_NAME` or pass `--model-name` to choose a Hugging Face embedding model that fits the\nlanguage and domain of your documents.\n\nmcp-local-rag generates embeddings with mean pooling and L2 normalization. When choosing a\nmodel, check whether these settings match its recommended inference setup, since the pooling\nmethod can affect retrieval quality.\n\nChanging `MODEL_NAME`, `RAG_DEVICE`, or `RAG_DTYPE` can make existing vectors incompatible.\nUse a new `DB_PATH` or delete the existing index and re-ingest after changing the embedding\nconfiguration.\n\nAn example model for English documents is `Xenova/bge-small-en-v1.5`.\n\n## Security and Operation\n\n- File access is restricted to `BASE_DIR`, `BASE_DIRS`, or CLI `--base-dir` roots.\n- Symlinks that resolve outside every configured root are rejected.\n- Document processing and search make no network requests after the required models are cached.\n- The server is designed for one local user and does not provide authentication or access control.\n- Do not run multiple CLI or MCP writers against the same `DB_PATH`. Read-only queries can run\n  while a sync is active.\n- Back up an index by copying its `DB_PATH` directory while no writer is active.\n\n<details>\n<summary><strong>Troubleshooting</strong></summary>\n\n### \"No results found\"\n\nDocuments must be ingested first. Run `\"List all ingested files\"` to verify.\n\n### Model download failed\n\nCheck internet connection. If behind a proxy, configure network settings. The model can also be [downloaded manually](https://huggingface.co/Xenova/all-MiniLM-L6-v2).\n\n### \"File too large\"\n\nDefault limit is 100MB. Split large files or increase `MAX_FILE_SIZE`.\n\n### Slow queries\n\nCheck chunk count with `status`. Large documents with many chunks may slow queries. Consider splitting very large files.\n\n### \"Path outside BASE_DIR\"\n\nEnsure file paths are within one of the configured roots (`BASE_DIR`, any `BASE_DIRS` entry, or any CLI `--base-dir`). Use absolute paths.\n\n### \"BASE_DIRS must be a JSON array...\"\n\n`BASE_DIRS` accepts a JSON array of one or more non-empty path strings:\n\n- Valid: `BASE_DIRS='[\"/Users/me/work\",\"/Users/me/specs\"]'`\n- Invalid: `BASE_DIRS=/a:/b` (delimiter syntax not supported)\n- Invalid: `BASE_DIRS='[]'` (empty array)\n\n### MCP client doesn't see tools\n\n1. Verify config file syntax\n2. Restart client completely (Cmd+Q on Mac for Cursor)\n3. Test directly: `npx mcp-local-rag` should run without errors\n\n</details>\n\n## Contributing\n\nContributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for setup and guidelines.\n\n## License\n\nMIT License. Free for personal and commercial use.\n\n## Blog Posts\n\n- [Building a Local RAG for Agentic Coding](https://www.norsica.jp/blog/local-rag-agentic-coding): Technical deep-dive into the semantic chunking and hybrid search design.\n\n## Acknowledgments\n\nBuilt with [Model Context Protocol](https://modelcontextprotocol.io/) by Anthropic, [LanceDB](https://lancedb.com/), and [Transformers.js](https://huggingface.co/docs/transformers.js).\n",
  "bytes": 20789,
  "sha": "609c2760cc9662ba145249674325ab924abf5c1dd715fd40bbfb7f15f8615f7c",
  "repo_slug": "shinpr/mcp-local-rag",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_shinpr_mcp_local_rag_0ecd178a/readme"
}