cyper-rag-server

Public

51 Downloads

README

MCP RAG Server

A production-grade, fully local MCP server for LM Studio. Semantic document retrieval + live web search — all on your machine, no cloud needed.


Features

CapabilityDetails
11 embedding modelsFrom fast MiniLM to Stella-1.5B / E5-Mistral — switchable with one flag
4 chunking strategiesparagraph · sentence · semantic · fixed
Hybrid retrievalBM25+ sparse + dense cosine, fused via Reciprocal Rank Fusion
Cross-encoder rerankingMiniLM-L6 / L12 / Electra — dramatically improves precision
HyDEHypothetical Document Embedding — better recall on abstract queries
10 file formatsPDF · MD · TXT · HTML · DOCX · EPUB · CSV · JSON
4 web search providersDuckDuckGo · Brave · Tavily · Serper
Live re-indexingAdd documents and re-index without restarting the server
Thread-safe TTL cacheDedup repeated queries; configurable window

Project Structure

mcp-rag-server/
├── server.py                   ← Entry point — run this
├── config.py                   ← All constants + embedding model registry
├── requirements.txt
├── README.md
└── src/
    ├── ingestion/
    │   ├── extractors.py       ← PDF, MD, HTML, DOCX, EPUB, CSV, JSON
    │   └── chunker.py          ← paragraph / sentence / semantic / fixed
    ├── retrieval/
    │   ├── engine.py           ← Unified RAG pipeline orchestrator
    │   ├── bm25.py             ← BM25+ sparse index (zero dependencies)
    │   ├── fusion.py           ← RRF + CombSUM result fusion
    │   ├── reranker.py         ← Cross-encoder reranking
    │   └── hyde.py             ← Hypothetical Document Embedding
    ├── search/
    │   └── providers.py        ← DuckDuckGo / Brave / Tavily / Serper
    ├── tools/
    │   ├── rag_tool.py         ← rag_search MCP tool
    │   ├── web_tool.py         ← web_search MCP tool
    │   └── ingest_tool.py      ← reindex_documents MCP tool
    └── utils/
        ├── cache.py            ← Thread-safe TTL cache
        └── logging.py          ← Structured stderr logging

Quick Start

1. Install

pip install -r requirements.txt

2. Run (minimal)

python server.py --docs /path/to/your/documents

3. Run (maximum power)

python server.py \
  --docs /path/to/your/documents \
  --embedding-model bge-large \
  --chunk-strategy sentence \
  --reranker \
  --hyde \
  --web-search \
  --search-provider tavily \
  --tavily-api-key YOUR_KEY

Embedding Models

python server.py --list-models
KeyTierDimHighlight
minilm-l6⚡ fast384Smallest, lowest RAM
minilm-l12⚡ fast384Better than L6, same size
mpnet⚖ balanced768Strong general-purpose
gte-base⚖ balanced768Top BEIR at this size
bge-base⚖ balanced768Default — top MTEB
bge-large🔥 powerful1024Best English BGE
gte-large🔥 powerful1024Great on long docs
e5-large🔥 powerful1024Instruction-aware, top BEIR
nomic-v1.5🔥 powerful7688192-token context
jina-v3🔥 powerful1024Multilingual · code + text
e5-mistral🔥 powerful4096Highest quality · needs GPU
stella-en-1.5b🔥 powerful1024MTEB SOTA · ~6 GB RAM

Switching models is safe — each model gets its own ChromaDB collection automatically. Delete .chroma_db to force a full re-index.


Chunking Strategies

StrategyBest forNotes
paragraphGeneral documentsDefault — fast, structure-aware
sentenceDense prose, QARequires nltk
semanticMixed-topic documentsSlowest ingest, highest quality
fixedLast resortNo structure awareness

Rerankers

python server.py --list-rerankers
KeySpeedQuality
ms-marco-MiniLM-L-6-v2FastestGood
ms-marco-MiniLM-L-12-v2BalancedBetter
ms-marco-electra-baseSlowestBest

How the Retrieval Pipeline Works

User Query
    │
    ├──[HyDE]────────────────────────────────────────────────────────────────┐
    │   LLM generates a hypothetical passage that would answer the query.    │
    │   We embed that passage instead of the raw query.                      │
    │   (Greatly improves recall for abstract / jargon-heavy queries)        │
    └────────────────────────────────────────────────────────────────────────┘
         │
    ┌────▼──────────────────┐    ┌──────────────────────────────┐
    │  Dense Retrieval       │    │  BM25+ Sparse Retrieval      │
    │  ChromaDB cosine sim   │    │  Keyword index (in-memory)   │
    │  top  K×4  candidates  │    │  top  K×4  candidates        │
    └────────────┬──────────┘    └──────────────┬───────────────┘
                 │                               │
                 └──────────────┬────────────────┘
                                │
                    ┌───────────▼───────────┐
                    │  Reciprocal Rank       │
                    │  Fusion (RRF)          │
                    │  Combines both lists   │
                    └───────────┬───────────┘
                                │
                    ┌───────────▼───────────┐
                    │  Cross-Encoder         │
                    │  Reranking (optional)  │
                    │  (query, chunk) pairs  │
                    └───────────┬───────────┘
                                │
                    ┌───────────▼───────────┐
                    │  Top-K Results         │
                    │  with source + scores  │
                    └───────────────────────┘

MCP Tools Exposed

rag_search

Search the local document knowledge base.

{
  "query":     "What is the return policy?",
  "top_k":     5,
  "min_score": 0.3
}

web_search

Search the live web (requires --web-search).

{
  "query":       "latest Python 3.13 features",
  "max_results": 5
}

reindex_documents

Re-scan and index new documents without restarting.

{}

LM Studio Configuration

{
  "mcpServers": {
    "rag": {
      "command": "python",
      "args": [
        "/absolute/path/to/mcp-rag-server/server.py",
        "--docs", "/absolute/path/to/your/documents"
      ]
    }
  }
}
{
  "mcpServers": {
    "rag": {
      "command": "python",
      "args": [
        "/absolute/path/to/mcp-rag-server/server.py",
        "--docs",            "/absolute/path/to/your/documents",
        "--embedding-model", "bge-large",
        "--chunk-strategy",  "sentence",
        "--reranker",
        "--hyde",
        "--web-search",
        "--search-provider", "duckduckgo"
      ]
    }
  }
}

Long documents (nomic 8192-token context)

{
  "mcpServers": {
    "rag": {
      "command": "python",
      "args": [
        "/absolute/path/to/mcp-rag-server/server.py",
        "--docs",            "/absolute/path/to/your/documents",
        "--embedding-model", "nomic-v1.5",
        "--chunk-size",      "1024",
        "--chunk-overlap",   "128",
        "--reranker"
      ]
    }
  }
}

All CLI Flags

Documents:
  --docs PATH              Folder to index (required)
  --collection NAME        ChromaDB collection prefix

Chunking:
  --chunk-strategy         paragraph | sentence | semantic | fixed
  --chunk-size INT         Target words per chunk (default: 512)
  --chunk-overlap INT      Overlap between chunks (default: 64)

Embedding:
  --embedding-model KEY    Model key (default: bge-base)
  --list-models            Print all models and exit

Retrieval:
  --top-k INT              Results per query (default: 5)
  --min-score FLOAT        Similarity threshold (default: 0.0)
  --no-hybrid              Dense-only; disable BM25+

Reranking:
  --reranker               Enable cross-encoder reranking
  --reranker-model KEY     Reranker key (default: ms-marco-MiniLM-L-6-v2)
  --list-rerankers         Print all rerankers and exit

HyDE:
  --hyde                   Enable Hypothetical Document Embedding
  --hyde-url URL           Override LM Studio completions URL

Web search:
  --web-search             Enable web_search tool
  --search-provider        duckduckgo | brave | tavily | serper
  --brave-api-key KEY
  --tavily-api-key KEY
  --serper-api-key KEY
  --web-max-results INT    Default results per web query (default: 5)

Notes

  • No cloud. Everything runs locally. Embeddings, BM25, reranking — all on your machine.
  • ChromaDB persists in .chroma_db/ next to your docs folder. Safe to delete to re-index from scratch.
  • HyDE requires LM Studio running at http://localhost:1234 (default). It silently falls back to the original query if the LLM is unreachable.
  • Semantic chunking downloads a small MiniLM model at ingest time to detect topic boundaries. It is separate from your --embedding-model.
  • All log output goes to stderr — it never pollutes the MCP stdio pipe.

Troubleshooting

ProblemFix
ModuleNotFoundError: frontmatterWrong package. Install python-frontmatter, not frontmatter.
ValueError: Unknown embedding modelRun --list-models to see valid keys.
HyDE does nothingLM Studio not running at port 1234. Check --hyde-url or disable --hyde.
Reranker is slowExpected on CPU with large pools. Use a smaller --reranker-model.
No results returnedLower --min-score to 0.0 or check that ingest completed at startup.
EPUB / DOCX not extractedInstall optional deps: pip install ebooklib python-docx