MCP Local RAG

repository·main·Indexed 43 days ago

https://github.com/shinpr/mcp-local-rag

A local Retrieval-Augmented Generation (RAG) server implementing the Model Context Protocol (MCP) for searching private documents. It supports indexing PDF, DOCX, Markdown, and text files locally without external embedding APIs. Features include hybrid search (semantic and keyword), semantic chunking, and optional visual captioning for PDFs. Compatible with AI coding tools like Claude Code, Cursor, Codex, and OpenCode. Version 0.18.5.

Tokens
40.7K
Snippets
127
Records
183
Agent score
53%

What's inside MCP Local RAG

  1. Overview of MCP Local RAG

    main

    MCP Local RAG is a local Retrieval-Augmented Generation (RAG) system that allows you to search through confidential documents via an MCP client or terminal without sending data to external embedding APIs. It indexes PDF, DOCX, Markdown, and Text files directly on your machine.

    Key features include:

    • Local Execution: Document parsing, embeddings, storage, and search all happen locally. It works offline after the initial model download.
    • Hybrid Search: Combines semantic similarity (for related concepts) with keyword search (for exact technical terms like API names or error codes).
    • Configurable Embeddings: Supports Hugging-Face embedding models.
    • Semantic Chunking: Documents are split at topic changes rather than fixed character counts, preserving Markdown code blocks.
    • MCP & CLI Support: Both AI coding tools (via MCP) and the terminal (via CLI) access the same index.
  2. Search and read context with `query_documents` and `read_chunk_neighbors`

    main

    To perform a search, use query_documents. Results include text, source path, title, chunkIndex, and relevance score.

    To get more context around a specific result, pass the chunkIndex and the filePath (or source) to read_chunk_neighbors.

    Que dit la documentation de l'API au sujet de l'authentification ?
    ...
    Lis les segments voisins de ce résultat sur l'authentification.
  3. Configure PDF visual profiles

    main

    The visual mode adds generated descriptions to PDF pages containing many figures. This is optional and does not load models during normal ingestion.

    Profiles:

    ProfileModel CacheUse Case
    fast (default)~250 MBLightweight visual indexing
    quality~1.7 GBFigures with labels, annotations, or embedded text

    Usage:

    • In MCP: Set visualQuality: "quality".
    • In CLI: Use --visual-quality quality.

    Updating existing quality descriptions: Since version 0.18.4, quality uses Qwen3.5-2B. Previous versions used Qwen2.5-VL-3B. Because sync does not regenerate existing descriptions, you must re-ingest files to update them:

    npx mcp-local-rag ingest ./docs/research-paper.pdf --visual --visual-quality quality --images

    Note: Use --images if the file was originally ingested with that option, otherwise stored images will be replaced.

    Managing Profiles during sync:

    • sync reuses the registered profile for each PDF.
    • Using --visual replaces registered profiles (it will describe PDFs previously indexed as text).
    • To disable descriptions for a path, run ingest on it without visual flags.
    npx mcp-local-rag ingest ./docs/research-paper.pdf --visual
  4. Manage storage and embedding models

    main

    Database and Cache Paths

    DB_PATH and CACHE_DIR default to the process's working directory. If your MCP client starts the server from different project directories, use absolute paths to ensure consistency.

    Embedding Models

    Use MODEL_NAME or --model-name to select a Hugging-Face embedding model.

    • Note on Pooling: mcp-local-rag generates embeddings using Mean Pooling and L2 Normalization. Ensure your chosen model is compatible with these settings for optimal search quality.
    • German Language Example: For German documents, consider using jinaai/jina-embeddings-v2-base-de.

    Critical: Configuration Changes

    Changing MODEL_NAME, RAG_DEVICE, or RAG_DTYPE will make existing vectors incompatible. If you change these settings, you must either:

    1. Use a new DB_PATH,
    2. Delete the existing index and re-import your documents.
  5. Configure PDF Visual Captions and Image Storage

    main

    Visual mode adds a generated caption for figure-heavy PDF pages. This is opt-in and does not load a vision model during normal ingestion.

    Image Storage: Image storage is independent of visual captions. To store images, set STORE_IMAGES=true in the MCP server environment or pass --images to the CLI.

    Behavior Matrix:

    visual / --visualSTORE_IMAGES / --imagesPDF behavior
    falsefalseText only; no visual captions or returned images.
    truefalseGenerated captions become searchable text; no images are stored or returned.
    truetrueGenerated captions become searchable text, and images from matched chunks are returned inline.
    falsetrueImages are attached to nearby retained PDF text and returned inline for matched chunks; the VLM is not imported, loaded, or run.

    Visual Profiles:

    • fast (default): Lightweight visual indexing (~250 MB model cache).
    • quality: For figures with labels/annotations (~1.7 GB model cache). Use visualQuality: "quality" (MCP) or --visual-quality quality (CLI).
    # Ingest with visual captions
    npx mcp-local-rag ingest ./docs/research-paper.pdf --visual
    
    # Ingest with visual captions and image storage
    npx mcp-local-rag ingest ./docs/research-paper.pdf --visual --images
    
    # Sync with images
    npx mcp-local-rag sync ./docs/ --images
  6. Expand context using read_chunk_neighbors

    main

    The read_chunk_neighbors tool is an on-demand utility used to expand the context of a search hit. Because chunks are stored as semantic units (sentences or paragraphs grouped by topic) rather than fixed-size slices, reading neighbors provides coherent surrounding context.

    When to use it

    1. Insufficient Context: When a query_documents result is too brief to answer a question (e.g., it uses pronouns like "this approach" without defining them).
    2. Explicit User Request: When a user asks to "read more around that section" or "show me what comes before that".

    How to use it

    To call this tool, you need a chunkIndex and either a filePath (for files) or a source (for raw data) from a previous query_documents result.

    Workflow:

    1. Identify the target chunkIndex and its filePath or source from a search result.
    2. Call read_chunk_neighbors with these identifiers.
    3. The tool returns the target chunk plus its semantic neighbors, sorted by chunkIndex.
  7. Manage embedding model compatibility and storage

    main

    mcp-local-rag uses mean pooling and L2 normalization for embeddings. When selecting a MODEL_NAME, ensure the model's recommended inference setup matches these settings to maintain retrieval quality.

    Warning: Changing MODEL_NAME, RAG_DEVICE, or RAG_DTYPE will make existing vectors in your database incompatible. If you change these settings, you must either:

    1. Use a new DB_PATH
    2. Delete the existing index and re-ingest your documents.

    For English documents, Xenova/bge-small-en-v1.5 is a recommended model.

  8. Search and Read Contextual Neighbors

    main

    Searching

    Use query_documents to find information. Results include text, source path, title, section number, and relevance score.

    Reading More Context

    If a search result requires more context, use read_chunk_neighbors. You must provide the chunkIndex and either the filePath or the source from the original hit.

  9. Security and operational best practices

    main

    File Access

    • Access is strictly limited to the roots defined by BASE_DIR, BASE_DIRS, or the --base-dir CLI option.
    • Symbolic links pointing outside configured roots are rejected.

    Concurrency and Backups

    • Do not run multiple CLI or MCP write processes on the same DB_PATH simultaneously. Read-only queries are possible during a synchronization process.
    • To back up an index, copy the DB_PATH directory only when no write processes are active.

    Privacy

    • Document processing and searching do not perform network requests once the necessary models are cached locally.
  10. Visual quality profiles for PDF captioning

    main

    When using the --visual flag for PDF ingestion, you can choose between two VLM (Vision Language Model) profiles. Both run locally and offline.

    ProfileModelCache (approx)Per-page inference (approx)Suited for
    fast (default)HuggingFaceTB/SmolVLM-256M-Instruct~250 MBbaselineChart titles, figure types, broad layout.
    qualityonnx-community/Qwen3.5-2B-ONNX~1.7 GB~3× fastFigures with in-image text (axis labels, annotations) where fidelity matters.

    Note: The first-time download for a profile is triggered on its first use and cached in CACHE_DIR. Switching profiles does not invalidate the other's cache.

  11. Ensure CLI options match MCP server configuration

    main
    When using the CLI to operate against an existing database, your CLI options must match the configuration used by the MCP server. Specifically, the --model-name must be identical. Using a different embedding model will generate vectors in a different mathematical space, which will silently degrade search quality and result in incorrect retrieval.
  12. Configure multiple root directories with BASE_DIRS

    main

    To allow operations on multiple directories, use the BASE_DIRS environment variable. It must be a valid JSON array of non-empty paths. If BASE_DIRS is invalid (e.g., an empty array or a colon-separated string), the application will error instead of falling back to BASE_DIR.

    Configuration Precedence:

    1. CLI --base-dir <path> options (can be repeated in ingest, list, and sync)
    2. BASE_DIRS environment variable
    3. BASE_DIR environment variable
    4. Current working directory

    Note: Each source replaces the one with lower priority; they are not merged.

    # Correct usage
    export BASE_DIRS='["/Users/me/work","/Users/me/specs"]'
    
    # Using repeated CLI flags
    npx mcp-local-rag ingest --base-dir /Users/me/work --base-dir /Users/me/specs /Users/me/work/readme.md