# lyonzin/knowledge-rag [Health: Active]

**Category:** 🧠 Knowledge & Memory  
**Repository:** https://github.com/lyonzin/knowledge-rag  
**GitHub Stars:** 306  
**Views:** 16  
**Installs:** 0  
**Upvotes:** 0  
**Directory Page:** https://allmcps.com/mcp/lyonzin-knowledge-rag

## Description
Local RAG system for Claude Code with hybrid search (BM25 + semantic), cross-encoder reranking, markdown-aware chunking, query expansion, and 28 MCP tools. Runs entirely offline with zero external servers.

## Tools
Capabilities this server exposes over MCP:

- **search_knowledge** — 
    Hybrid search combining semantic search + BM25 keyword search with cross-encoder reranking.

    Read-only. No side effects.

    Args:
        query: Search query text (1–3 keywords recommended; phrase queries also work)
        max_results: Maximum number of results (default: 5, capped by search.max_results).
        category: Optional category filter. Accepts the categories the server is configured with
            (category_mappings values and keyword_routes keys) plus general; an empty string, like
            omitting it, searches every category, and any other value returns an error that lists
            the valid ones. Call list_categories() first to see which categories hold documents and
            how many.
        hybrid_alpha: Balance between semantic and keyword search. 0.0 = keyword-only (best for exact
            technical terms like CVE IDs or tool names), 0.3 = balanced default, 1.0 = semantic-only
            (best for conceptual or natural-language queries).
        min_score: Minimum score (0.0–1.0) a result needs to be returned; default 0.0 returns all
            results. Scores are min-max normalized per query over its candidates: the best scores 1.0
            and the weakest 0.0, while a single candidate or candidates that all tie score 1.0. On the
            hybrid path (results labeled hybrid, semantic or keyword) the candidates are the returned
            results, so any min_score above 0 drops at least the weakest one unless all tie; fts5
            results are BM25 scores normalized over up to max(3 * max_results, 20) hits, so even the
            weakest returned one can score well above 0.0. It is not an absolute relevance bar.
        snippet_mode: When true (default), truncates content to ~500 characters from the start of the
            matching chunk, at a natural break point, and adds a content_length field with the full
            size. Use get_document() to fetch full content when needed. Set to false to return the full
            content, which can include adjacent chunks; match_offset, when present, is where the match starts.
        search_method: Dispatch selector (v4.8.2+). One of ``"auto"`` (router picks FTS5 fast-path
            for lexical queries when enabled, hybrid otherwise), ``"hybrid"`` (force hybrid path —
            kill switch for suspected router misclassification), or ``"fts5"`` (force FTS5 fast-path
            — debug/testing; errors out when the feature is disabled or the index is not ready).
            Default ``"auto"`` preserves pre-v4.8.2 behavior byte-for-byte when the fast-path is
            disabled in config.
        include_folders: Optional list of directories relative to documents_dir, recursively included
            before candidate selection (e.g. ["manuals/product-a", "runbooks"]). Omit for all folders.
        exclude_folders: Optional recursive directory exclusions, applied before candidate selection.
            Exclusions override inclusions. Paths use / or \, have exact component boundaries,
            and cannot be absolute, contain '..', or resolve outside documents_dir. Maximum 32 each.

    Returns:
        JSON string with results including content chunks, source filepath, relevance score, and
        search method used. Returns chunks, not full document content.

    Usage: Primary search tool — use for any topic or keyword lookup. Prefer search_similar() when
    you already have a reference document and want more like it. Prefer get_document() when you
    already know the exact filepath and need the full content.
    
- **get_document** — 
    Get the full content of a specific document by filepath.

    Read-only. No side effects.

    Args:
        filepath: Relative path to the document within the documents directory
            (e.g., "security/technique.md"). Must be an indexed file — use
            search_knowledge() to find the filepath by topic first, or browse
            list_documents(), which returns one page at a time (see its offset).

    Returns:
        JSON string with full document content and metadata (filepath, category, size).

    Usage: Use when you need the complete text of a known file — search_knowledge()
    returns chunks, not full docs. Use search_knowledge() first to find the filepath
    if unknown. Use list_documents() to browse files by category, one page at a time.
    
- **reindex_documents** — Index or reindex all documents in the knowledge base (runs in background).

    No flags — incremental pass: index new or changed files, skip unchanged
    ones, prune deleted sources. Use after filesystem edits outside
    add_document/update_document.
    ``force`` — smart reindex: re-embed every file, unchanged ones included,
    and rebuild BM25. Slow on a large corpus; use after changing the
    query/passage prefixes or chunking settings.
    ``full_rebuild`` — nuclear rebuild (delete + re-embed). Use only after
    embedding-model change or index corruption. Mutually exclusive with resume.
    ``resume`` — pick up an interrupted smart reindex from
    ``data/reindex_checkpoint.json``. Falls back to a fresh smart run silently
    if the checkpoint is missing/corrupt/drifted (v4.8.0 Fase 4).

    Returns a JSON envelope. Poll ``get_reindex_status()`` until
    ``reindex.active`` becomes false. Add/update/URL tools already auto-index —
    use these flags only for the recovery/rebuild scenarios above.
    
- **get_reindex_status** — 
    Get the current status of a background reindex operation.

    Lightweight — does not compute full index statistics. Use this to poll progress
    after calling reindex_documents().

    Returns:
        JSON string with reindex status. When active: operation name, progress (processed/total),
        percent complete, indexed/skipped/errors counts, and start time. When inactive: active=false,
        plus last_result or last_error from the most recent completed reindex.

    Usage: Call repeatedly after reindex_documents() to monitor progress. When reindex.active
    becomes false, the operation is complete. Use get_index_stats() for full index health metrics.
    
- **list_categories** — 
    List all document categories with their document counts.

    Read-only. No side effects. Reflects the live index state.

    Returns:
        JSON string with category names, document counts per category, and total document count.

    Usage: Use before filtering search_knowledge() or list_documents() by category to see
    which categories exist and how many documents each contains; search_knowledge() still
    rejects a listed name that is not configured, such as one stored by add_document().
    Use get_index_stats() instead for broader system health metrics (model name, cache hit
    rate, BM25 status).
    
- **list_documents** — 
    List indexed documents one page at a time, optionally filtered by category.

    Read-only. No side effects.

    Args:
        category: Optional category filter, matched exactly against each document's category; an
            empty string, like omitting it, lists every document, and a category without documents
            returns an empty page (total 0). Call list_categories() to see the categories that hold
            documents.
        limit: Maximum number of documents to return (default: 100, max: 200).
        offset: Number of matching documents to skip (default: 0). For the next page, call
            again with offset + count until offset reaches total.

    Returns:
        JSON string with total (documents matching the filter), offset, limit, count (documents
        in this page) and the filepaths, categories, and metadata of this page, ordered by filepath.

    Usage: Use to browse what's in the index, one page at a time; to see every document, call
    again with offset + count until offset reaches total. Use list_categories() first to see
    which categories hold documents. Use search_knowledge() when you want to find documents by
    topic rather than browsing the full list. Use get_document() to read a specific file once
    you have its filepath.
    
- **get_index_stats** — 
    Get statistics and health metrics for the knowledge base index.

    Read-only. No side effects.

    Returns:
        JSON string with system metrics: total documents, total chunks, embedding model name,
        BM25 status, query cache hit rate, and file watcher status.

    Usage: Use for system health checks — inspecting embedding runtime status, checking
    index population, or monitoring cache efficiency. This does not load the embedding
    model or initialize BM25. Use list_categories() for per-category
    document counts instead. Use evaluate_retrieval() to measure actual search quality with
    test queries.
    
- **add_document** — 
    Add a new document to the knowledge base from raw text content.

    Mutating — writes a file to disk and indexes it immediately. No auth required.

    Args:
        content: Full text content of the document (markdown supported)
        filepath: Relative path within documents directory (e.g., "security/new-technique.md").
            The subdirectory should match the category.
        category: Category stored with the document (default: general). Any name is accepted, but
            search_knowledge() filters only by configured categories (category_mappings values,
            keyword_routes keys, general), and update_document() or re-indexing the file detects it
            again from the path through category_mappings. list_categories() shows the categories in use.

    Returns:
        JSON string with indexing results (filepath, chunks created, status).

    Usage: Use to add new documents from text content. Use add_from_url() instead when
    the source is a web page. Use update_document() to replace content of an existing file.
    The document is immediately searchable after this call — no manual reindex needed.
    
- **update_document** — 
    Update the content of an existing document in the knowledge base.

    Mutating — overwrites the file on disk and re-indexes immediately. Old chunks are
    removed and replaced with new ones. Full content replacement, not a patch. The category
    is detected again from the path through category_mappings (general when none matches), so
    a category stored by add_document() or add_from_url() is not kept.

    Args:
        filepath: Full or relative path to the document file. Must be an already-indexed
            file — list_documents() lists indexed paths, one page at a time.
        content: New full-text content to replace the existing content entirely

    Returns:
        JSON string with update results (old chunk count, new chunk count, status).

    Usage: Use to replace a document's content completely. Use add_document() to create
    a new file instead. Use remove_document() to delete without replacing. Changes are
    immediately searchable — no manual reindex needed.
    
- **remove_document** — 
    Remove a document from the knowledge base index.

    Mutating — removes index entries. If delete_file=True, also permanently deletes
    the file from disk (irreversible, cannot be undone).

    Args:
        filepath: Path to the document file. Must be an indexed document —
            list_documents() lists indexed paths, one page at a time.
        delete_file: If True, permanently deletes the file from disk in addition to
            removing from the index (default: False).

    Returns:
        JSON string with removal results (filepath, status).

    Usage: Use to unindex a document while keeping the file on disk (default). Set
    delete_file=True only for permanent removal. Use update_document() to replace
    content instead of removing. Use reindex_documents(force=True) if you deleted
    the file manually on disk outside of this tool.
    
- **add_from_url** — 
    Fetch content from a URL, convert to markdown, and add to the knowledge base.

    Mutating — makes an outbound HTTP request (requires internet access), strips HTML,
    converts to markdown, saves to disk, and indexes immediately.

    Args:
        url: Full URL to fetch (https:// required). The page must be publicly accessible.
        category: Category stored with the document and the folder it is saved in; default:
            general. Being part of the path, it must stay inside documents_dir: a value such as
            ../outside returns a "Filepath rejected" error. Any other name is accepted, but
            search_knowledge() filters only by configured categories (category_mappings values,
            keyword_routes keys, general), and update_document() or re-indexing the file detects it
            again from the path through category_mappings. list_categories() shows the categories
            in use.
        title: Optional document title. Auto-detected from the page's <title> tag if omitted.

    Returns:
        JSON string with indexing results (filepath, category, chunks added, status). The page is
        saved as <category>/<title slug>.md, or as <title slug>-<first 8 hex characters of the
        URL's SHA-256>.md (then 16, then the full digest) when a file not saved from this URL
        already has the shorter name. Use the returned filepath instead of building the path.

    Usage: Use to ingest web content (writeups, blog posts, documentation pages) directly
    by URL. Use add_document() instead when you already have the text content. The document
    is immediately searchable after this call — no manual reindex needed.
    
- **search_similar** — 
    Find documents semantically similar to a given reference document.

    Read-only. No side effects. Uses the document's embedding for similarity comparison.

    Args:
        filepath: Path to the reference document (must already be indexed — list_documents()
            lists indexed paths, one page at a time). E.g., "security/technique.md"
        max_results: Number of similar documents to return (default: 5, max: 20)

    Returns:
        JSON string with list of similar document filepaths and similarity scores (0.0–1.0).

    Usage: Use when you have a specific document and want to discover thematically related
    ones. Use search_knowledge() instead when you have a text query rather than a reference
    document. The reference document must be indexed; list_documents() lists indexed paths
    one page at a time.
    
- **evaluate_retrieval** — 
    Evaluate search quality by testing whether search_knowledge() retrieves expected documents.

    Read-only. Runs multiple search queries internally. No side effects on the index.

    Args:
        test_cases: JSON string array of test cases. Each item requires "query" (search string)
            and "expected_filepath" (path of the document that should appear in top-5 results).
            Example: [{"query": "suid exploit", "expected_filepath": "security/suid.md"}]

    Returns:
        JSON string with MRR@5 (Mean Reciprocal Rank), Recall@5, and per-query hit/miss breakdown.
        MRR@5 above 0.7 indicates good retrieval quality.

    Usage: Use to audit search quality after bulk document ingestion or after tuning
    hybrid_alpha. Use get_index_stats() for system health checks instead. Use
    search_knowledge() for actual document retrieval — this tool is for quality measurement only.
    

## Claude Desktop Quick Installation
Install path detected from listing signals. Uses `uvx` (confidence: high):

```json
"mcpServers": {
  "knowledge-rag": {
    "command": "uvx",
    "args": ["knowledge-rag"]
  }
}
```

## Documentation

## What lyonzin/knowledge-rag does

lyonzin/knowledge-rag provides a local retrieval-augmented knowledge base through MCP. It indexes files placed in a documents directory, stores their searchable chunks, and returns matching content with source paths and relevance scores. Supported categories include security, ctf, logscale, development, general, redteam, and blueteam.

The primary retrieval path combines semantic search with BM25 keyword matching and cross-encoder reranking. Search parameters control the balance between conceptual matching and exact terms, result count, minimum score, category, snippets, and search dispatch. This makes it suitable for both natural-language questions and identifiers such as CVE numbers or tool names.

## How it works

Embedding generation, indexing, and retrieval run locally using FastEmbed ONNX. After the initial model download, the server can operate without external services. A local corpus can be populated from files, raw text, or publicly accessible web pages. URL ingestion makes an outbound HTTPS request, converts page content to Markdown, saves it, and indexes it.

Search results normally contain chunks rather than complete files. Once a relevant filepath is known, `get_document` returns the full document and metadata. `search_similar` uses an indexed document as the reference for finding related documents. The server can also report category counts, index health information, and retrieval metrics such as MRR@5 and Recall@5.

## Setup and configuration

Install the Python package and initialize a workspace:

```bash
pip install knowledge-rag
knowledge-rag init
```

Place Markdown, PDF, or code files in the generated `documents/` directory, then restart the MCP client. Python 3.11 or newer is supported, and the project targets Windows, Linux, and macOS. No Docker, Ollama instance, or separate embedding server is required.

The server supports stdio for a client-owned process and SSE or streamable HTTP for shared deployments. HTTP configuration can set the host, port, bearer token, rate limiting, Prometheus metrics, and JSON logging. Streamable HTTP clients can connect to the `/mcp` endpoint; health and metrics endpoints are also available for HTTP deployments.

## Tools and capabilities

- Search with semantic, BM25, hybrid, or FTS5 dispatch, optional category filtering, score thresholds, and snippets.
- Retrieve complete indexed documents by filepath and browse documents or category counts.
- Add text, update existing files, remove index entries, or optionally delete files from disk.
- Fetch public web pages, convert them to Markdown, and index them immediately.
- Find documents similar to an indexed reference document.
- Start background indexing, resume interrupted work, rebuild indexes, and poll reindex progress.
- Inspect index statistics and test retrieval quality against expected filepaths.

Documents added or updated through the MCP tools become searchable immediately. Files changed outside those tools can be handled with a smart reindex; a full rebuild is intended for embedding-model changes or index corruption.

## Limitations and notes

Search parameters and filepaths must refer to the indexed corpus. `get_document` requires a known indexed path, while `search_similar` also requires its reference document to be indexed. Removing a file from the index does not delete it unless the destructive `delete_file` option is enabled.

Local retrieval does not mean every operation is network-free: the initial model download and URL ingestion use network access, and MCP clients receive the retrieved content. HTTP deployments should therefore be configured with appropriate transport and access controls.

_Full upstream README: https://allmcps.com/mcp/lyonzin-knowledge-rag/readme_

