Skip to main content
Glama
q6066697

rag-mcp-server

by q6066697

rag-mcp-server

MCP-сервер, оборачивающий production RAG pipeline (rag-eval-service) в стандартный протокол (Model Context Protocol) для агентов — гибридный поиск (dense-эмбеддинги + BM25 + RRF) становится инструментом, который может вызвать любой MCP-клиент: Claude Desktop, Claude Code или собственный агент.

Архитектура

Client (Claude Desktop / Claude Code / любой MCP-клиент)
    |
    v  MCP over stdio (JSON-RPC)
FastMCP server  (rag_mcp_server/server.py)
    |
    +--> search_documents(query, top_k)
    +--> get_document(doc_id)
    +--> rerank_results(query, doc_ids)
    |
    v
Hybrid retrieval  (rag_mcp_server/core/retrieval.py)
    |
    +---> Dense retriever  --- OpenAI text-embedding-3-small ---> Qdrant (cosine, 1536d)
    |                                                                 |
    +---> Sparse retriever -- BM25 (rank-bm25 / BM25Okapi) ----------+
    |                                                                 |
    |                                 +-------------------------------+
    |                                 v
    |                        Reciprocal Rank Fusion (k=60)
    |                                 |
    +---------------------------------v
                              Top-k документов --> клиент (LLM формирует ответ)

Qdrant по умолчанию работает в embedded-режиме (файл на диске, без отдельного процесса) — сервер self-contained и не требует внешней инфраструктуры для демо. При желании можно переключиться на полноценный Qdrant-сервер через docker-compose.yml (см. ниже).

Related MCP server: RAG MCP Server

Что это и зачем

Это MCP-обёртка, а не переизобретение retrieval-логики: сам гибридный поиск (dense + BM25 + RRF) портирован из rag-eval-service почти без изменений. Новое, что добавляет именно эта обёртка:

  • Протокол вместо HTTP API — инструменты видны любому MCP-клиенту (Claude Desktop, Claude Code) без написания кастомного HTTP-клиента и без необходимости держать сервис постоянно поднятым за REST.

  • Self-contained демо-режим — embedded Qdrant вместо докер-контейнера, чтобы git clone → работающий инструмент занимал минимум шагов.

  • doc_id/title-схема и агрегация результатов на уровне документа (а не чанка) — под нужды LLM-клиента, который вызывает search_documents → get_document, а не работает с сырыми чанками.

  • Docstring-контракты, написанные для LLM-потребителя инструмента (см. rag_mcp_server/server.py), а не для человека, читающего API-документацию.

Как запустить локально

Требования: Python 3.10+, ключ OpenAI API (для эмбеддингов).

git clone https://github.com/q6066697/rag-mcp-server.git
cd rag-mcp-server

python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install -r requirements.txt  # или: pip install -e ".[dev]"

cp .env.example .env
# впишите свой OPENAI_API_KEY в .env

Построить индекс (одноразово; читает data/, эмбеддит чанки через OpenAI и заливает их в embedded Qdrant):

python -m rag_mcp_server.core.indexing

(Опционально) реальный Qdrant вместо embedded-режима:

docker-compose up -d
# затем в .env: QDRANT_MODE=server

Запустить сервер (stdio-транспорт):

python -m rag_mcp_server.server

Проверить через MCP Inspector (встроенный инспектор из mcp[cli], открывает веб-UI для ручного вызова tools):

mcp dev rag_mcp_server/server.py

Тесты (не требуют живого Qdrant/OpenAI — векторный поиск и cross-encoder замоканы):

pytest

Как подключить в Claude Desktop / Claude Code

Добавьте в claude_desktop_config.json (Claude Desktop: Settings → Developer → Edit Config; Claude Code: .mcp.json в проекте или claude mcp add):

{
  "mcpServers": {
    "rag-mcp-server": {
      "command": "/absolute/path/to/rag-mcp-server/.venv/bin/python",
      "args": ["-m", "rag_mcp_server.server"],
      "cwd": "/absolute/path/to/rag-mcp-server",
      "env": {
        "OPENAI_API_KEY": "sk-..."
      }
    }
  }
}

После перезапуска клиента инструменты search_documents, get_document и rerank_results должны появиться в списке доступных tools.

Примеры вызова tools

search_documents

search_documents(query="что такое Reciprocal Rank Fusion", top_k=3)
[
  {
    "doc_id": "reciprocal-rank-fusion.md",
    "title": "Reciprocal Rank Fusion",
    "snippet": "RRF сливает несколько ранжированных списков без нормализации сырых score — документ на позиции r получает вклад 1/(k+r)…",
    "score": 0.0328
  },
  {
    "doc_id": "hybrid-search.md",
    "title": "Hybrid Search",
    "snippet": "Гибридный поиск комбинирует dense-эмбеддинги и BM25, чтобы ловить и семантическое сходство, и точные термины…",
    "score": 0.0301
  }
]

get_document

get_document(doc_id="reciprocal-rank-fusion.md")
"# Reciprocal Rank Fusion (RRF)\n\nRRF — метод слияния нескольких ранжированных списков результатов…"

rerank_results

rerank_results(
    query="как оценивать качество ретривера",
    doc_ids=["eval-retrieval-metrics.md", "reranking.md", "hybrid-search.md"]
)
[
  {
    "doc_id": "eval-retrieval-metrics.md",
    "title": "Evaluating Retrieval Quality",
    "snippet": "Метрики retrieval — hit@k, recall@k, MRR, nDCG@k — измеряют, находит ли поиск релевантные документы…",
    "score": 4.81
  },
  {
    "doc_id": "reranking.md",
    "title": "Reranking",
    "snippet": "Cross-encoder реранкинг переупорядочивает шортлист кандидатов, читая query и passage вместе…",
    "score": 1.02
  }
]

Структура репозитория

rag-mcp-server/
├── rag_mcp_server/
│   ├── server.py          # точка входа, FastMCP инстанс, регистрация tools
│   ├── core/
│   │   ├── retrieval.py   # портированная гибридная логика поиска (dense + BM25 + RRF + rerank)
│   │   └── indexing.py    # загрузка корпуса, чанкинг, индексация в Qdrant
│   └── config.py          # конфигурация из .env
├── data/                  # bootstrap-корпус (15 markdown-доков, копия из rag-eval-service)
├── tests/
│   └── test_server.py     # unit-тесты на MCP tools (мокают поиск)
├── docker-compose.yml     # опциональный Qdrant-сервер
├── pyproject.toml / requirements.txt
├── .env.example
└── LICENSE (MIT)

Источник retrieval-логики

Гибридный поиск (rag_mcp_server/core/retrieval.py, core/indexing.py) портирован из rag-eval-service — там же живёт eval-harness (NFCorpus/BEIR-бенчмарк, custom golden set, метрики hit@k/recall@k/MRR/nDCG), которого в этом репозитории намеренно нет: rag-mcp-server — это тонкая протокольная обёртка над уже провалидированным retrieval-пайплайном, а не его переоценка.

Известная проблема и её решение

При запуске через mcp dev изначально возникала ошибка AlreadyLocked от embedded Qdrant — Storage folder is already accessed by another instance of Qdrant client.

Причина: mcp dev импортирует модуль сервера дважды — сам инспектор (чтобы прочитать зависимости) и дочерний процесс uv run mcp run, который реально запускает сервер. Индексы (DenseIndex, SparseIndex, CrossEncoderReranker) изначально создавались на уровне модуля при импорте — второй импорт натыкался на файловый лок, оставленный первым.

Решение: инициализация индексов сделана ленивой — через геттер с кэшированием, вызываемый при первом обращении к tool, а не при импорте модуля. Это заодно и более правильная архитектура для MCP-сервера: сервер стартует мгновенно, тяжёлая инициализация (эмбеддинг-клиент, cross-encoder) откладывается до первого реального запроса.

Что бы добавил дальше

  • Docker для самого MCP-сервера — сейчас в контейнер оборачивается только Qdrant; для деплоя самого сервера нужен свой Dockerfile.

  • SSE/HTTP-транспорт — stdio предполагает локальный процесс на одной машине с клиентом; для удалённого доступа (несколько пользователей, облачный деплой) нужен SSE или Streamable HTTP транспорт из MCP SDK.

  • Авторизация — у stdio-транспорта её нет по конструкции (процесс доверенный, запущен локально); при переходе на сетевой транспорт понадобится API-ключ/OAuth на уровне сервера.

  • Инкрементальная индексация — сейчас core.indexing пересоздаёт коллекцию целиком; для растущего корпуса нужен upsert только изменившихся документов.

  • Реальный Qdrant по умолчанию в CI/проде — embedded-режим отлично подходит для демо и тестов, но для конкурентного доступа нескольких процессов нужен сервер.

Available Tools

3 tools
get_documentA

Возвращает полный текст документа из корпуса по его doc_id.

Используй этот инструмент после search_documents(), когда сниппета недостаточно и нужен полный текст найденного документа — например, чтобы процитировать точную формулировку или прочитать раздел, который не попал в сниппет.

Args: doc_id: Идентификатор документа, как он возвращается в поле "doc_id" у search_documents() (совпадает с именем файла в корпусе, например "hybrid-search.md").

Returns: Полный текст документа (markdown). Если doc_id не найден в корпусе, вместо ошибки возвращается строка со списком доступных doc_id, чтобы клиент мог сразу повторить вызов с корректным значением.

ParametersJSON Schema
NameRequiredDescriptionDefault
doc_idYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.6/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Since no annotations are provided, the description carries the full burden for behavioral disclosure. It explicitly mentions the graceful error handling: if doc_id is not found, it returns a list of available doc_ids instead of an error, which is key behavioral context. However, it does not mention potential performance implications (e.g., fetching a large document) or any authentication requirements, so it is not perfect.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is reasonably concise, with a clear first sentence stating the main purpose, followed by usage guidance and parameter/returns details. It is structured in sections (Args, Returns) for readability. However, the 'Args:' section is somewhat redundant with the schema, and the text could be slightly more streamlined without losing value.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's simplicity (one parameter, no annotations) and the presence of an output schema, the description is complete. It covers purpose, usage context, parameter semantics, and return behavior. The graceful error handling is a nice touch that prepares the agent for a non-standard response, making it comprehensive.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema defines doc_id as a string but provides no documentation. The description adds significant meaning by explaining that doc_id matches the field returned by search_documents() and corresponds to the filename in the corpus (e.g., 'hybrid-search.md'), which is not evident from the schema. With 0% schema description coverage, this compensation is crucial and well-executed.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: retrieving the full text of a document from a corpus by its doc_id. It uses a specific verb ('Возвращает') and resource ('документ из корпуса'), and it distinguishes itself from siblings by focusing on fetching full text, while search_documents is for searching snippets.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly states when to use this tool: after search_documents() when the snippet is insufficient, and provides concrete examples (quoting exact phrasing or reading sections not in the snippet). It also names the sibling tool search_documents as the prior step, making the workflow clear.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

rerank_resultsA

Переранжирует переданный список документов-кандидатов относительно query с помощью cross-encoder модели, которая читает пару (query, документ) вместе — точнее, чем независимое векторное сходство, но дороже по compute, поэтому применяется к уже отфильтрованному шортлисту, а не ко всему корпусу.

Используй этот инструмент, когда уже есть список кандидатов (например, из search_documents() или собранный вручную из нескольких запросов) и нужно уточнить их порядок релевантности перед тем, как процитировать top-N пользователю. Для поиска по всему корпусу используй search_documents() — этот инструмент только переупорядочивает уже известные doc_id и не находит новые документы.

Args: query: Запрос, относительно которого переранжируются документы. doc_ids: Список doc_id кандидатов (см. search_documents/ get_document). Неизвестные doc_id молча пропускаются.

Returns: Список [{"doc_id": str, "title": str, "snippet": str, "score": float}, ...], отсортированный по убыванию cross-encoder score. score здесь — необязательно вероятность и несравним по шкале со score из search_documents() (RRF-скор).

ParametersJSON Schema
NameRequiredDescriptionDefault
queryYes
doc_idsYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.5/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the burden. It discloses that unknown doc_ids are silently skipped and that scores are not comparable to search_documents scores, which is helpful. However, it doesn't detail side effects (none expected) or performance implications beyond general compute cost, which is mentioned.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise but thorough, with front-loaded purpose, clear usage guidance, parameter details, and return format. Every sentence adds value without redundancy, despite being longer than ideal, it remains structured and readable.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description is complete for a tool with two simple params, no annotations, and a clear output schema. It explains the return format and score semantics, covers edge cases (unknown ids), and contextualizes the tool's role in the workflow, making it self-sufficient.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, but the description provides meaningful semantics for both parameters: query is the reference for re-ranking, doc_ids is the candidate list and indicates unknown ids are skipped. This adds value beyond the minimal schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly specifies the tool re-ranks a provided candidate list relative to a query using a cross-encoder, distinguishing it from direct similarity search. It explicitly states it does not find new documents, differentiating it from sibling tools like search_documents and get_document.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides explicit when-to-use (when a candidate list already exists) and when-not-to-use (for corpus-wide search, use search_documents). Mentions alternatives and gives a specific scenario (before quoting top-N to the user), making usage guidance clear.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

search_documentsA

Гибридный поиск (dense-эмбеддинги + BM25, слитые через Reciprocal Rank Fusion) по проиндексированному корпусу markdown-документов о RAG, поиске и LLM-инфраструктуре.

Используй этот инструмент, когда нужно найти релевантные документы или факты по теме или вопросу пользователя, прежде чем отвечать — вместо того, чтобы полагаться на собственные знания. Одинаково хорошо работает и для семантических запросов на естественном языке ("как оценивать качество ретривера"), и для точных терминов/аббревиатур ("RRF", "BM25"), поскольку сочетает векторный и лексический поиск.

Args: query: Запрос на естественном языке или ключевые слова. top_k: Сколько документов вернуть (по умолчанию 5, максимум 20).

Returns: Список словарей, отсортированный по убыванию релевантности — [{"doc_id": str, "title": str, "snippet": str, "score": float}, ...]. doc_id — идентификатор документа, который нужно передать в get_document(), чтобы получить его полный текст, или в rerank_results(), чтобы уточнить порядок кандидатов.

ParametersJSON Schema
NameRequiredDescriptionDefault
queryYes
top_kNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.6/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provisioned, the description carries the full explanation burden. It does well by disclosing the dense+BM25 RRF behavior, a relevance-sorted return structure, and downstream integration via doc_id to get_document or rerank_results. It maybe does not explicitly state side-effect safety or permissions, but such considerations are minimal for a search operation.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well structured: a front-loaded explanation of the retrieval mechanism, followed by concrete usage guidance and a neat Args/Returns block. Every sentence completes the main explanation of what the tool does, when to use it, how it behaves, and what the caller receives.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the output schema, sibling tools, and search-oriented complexity, the description provides a practically complete flow: search for candidates, receive relevant snippets and scores, then optionally pass doc_id to get_document for full content or rerank_results for reranking. This is sufficient contextual guidance for agentic use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

While the schema description coverage is 0%, the description fully explains both parameters: query is a natural-language request or keywords, and top_k is the number of documents to return with a default of 5 and maximum of 20. This adds strong semantic value beyond the bare input schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states a specific verb and resource: hybrid search over an indexed corpus of markdown documents about RAG, retrieval, and LLM infrastructure. It distinguishes this tool from siblings like get_document and rerank_results by making search and retrieval its primary role.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description gives explicit direction: use this tool to find relevant documents or facts before answering instead of relying on internal knowledge. It also explains suitability for semantic queries and exact terms; however, it does not explicitly describe when not to use this tool versus its siblings.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 3 tool updatesv0.1.0
    • First observedget_document
    • First observedrerank_results
    • First observedsearch_documents

TDQS

A4.7/5.0

Scored across 3 tools

Disambiguation5/5

Tools have clear boundaries: search_documents retrieves candidates, get_document fetches full text by ID, rerank_results reorders given IDs. No overlap in purpose, and each description explicitly states when to use it.

Naming Consistency5/5

All tool names follow a consistent verb_noun pattern (search_documents, get_document, rerank_results) in snake_case. Naming convention is uniform and predictable.

Tool Count5/5

Three tools is well-scoped for a focused retrieval server: search, fetch full content, and re-rank. Each tool serves a distinct step in the pipeline without redundancy, fitting the typical 3-15 range.

Completeness5/5

The tool surface covers the full read-only retrieval workflow: hybrid search with snippets, full document access, and optional cross-encoder re-ranking. No missing operations are needed for the stated purpose.

Maintenance

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    B
    maintenance
    Enables any MCP-compatible AI assistant to search, filter, and retrieve information from a local document collection using a hybrid search pipeline with vector, BM25, reranking, and LLM enrichment.
    4
    -
  • F
    license
    Not graded
    quality
    C
    maintenance
    Provides RAG-based knowledge retrieval and document management as MCP tools, supporting hybrid search, reranking, and retrieval process visualization.
    -
  • F
    license
    Not graded
    quality
    C
    maintenance
    Enables agent tools like Claude Code and GitHub Copilot to perform knowledge retrieval using hybrid search (BM25 + dense) with reranking, via MCP protocol.
    -