mcp-docs-assistant
🔌 MCP Docs Assistant
公式 Model Context Protocol ドキュメントに対する本番グレードの Retrieval-Augmented Generation(RAG)パイプライン — REST、MCP ツール、Docker で利用できます。
MCP について(アーキテクチャ、サーバー/クライアントの構築、ツール/リソース/プロンプト、セキュリティ)を自然言語で質問すると、実際のドキュメントに基づいた回答が得られます。ガードレール、PII マスキング、リランキング、セマンティックキャッシュ、ハルシネーションチェックが組み込まれています。
✨ 機能
機能 | 実装 |
🔀 マルチキー LLM ゲートウェイ | Portkey のルーティングにより 2 つの Gemini キー + 2 つの Groq キーを負荷分散し、プロバイダーを自動フォールバック |
📚 根拠に基づく検索 | 公式 MCP ドキュメントをチャンク化し、永続化される Qdrant ベクターストアに埋め込み |
🎯 リランキング | クロスエンコーダ( |
🛡️ ガードレール | NeMo Guardrails(Colang 2.x)— 入出力の安全性チェック、ジェイルブレイク検出、指示漏洩検出 |
🕵️ PII マスキング | Microsoft Presidio — 入力・出力の両方でメールアドレス、電話番号、クレジットカードをマスキング |
🧮 トークン予算管理 | 取得したコンテキストは、LLM に渡す前に固定トークン予算に貪欲に詰め込まれます |
⚡ セマンティックキャッシュ | 完全一致ではなく埋め込み類似度で判定する、TTL ・サイズ上限付きキャッシュ |
💬 マルチターン会話 | LangGraph チェックポインター + フォローアップクエリの圧縮(例:「その Python の例を教えて」) |
🔍 ハルシネーション チェック | 生成された各回答に対し、実行時に |
📊 オフライン評価 | 25 組のリファレンス Q&A に対する RAGAS メトリクス(faithfulness、relevancy、context precision/recall) |
🔌 MCP ネイティブ | 自身を MCP ツール( |
🌐 REST API | あらゆる一般的な HTTP クライアント向けの FastAPI エンドポイント |
🐳 Docker 対応 |
|
Related MCP server: RLM Knowledge Base
🏗️ アーキテクチャ
flowchart TD
A[User Question] --> B[Guard Input<br/>NeMo Guardrails]
B -->|blocked| Z[Refusal message]
B -->|allowed| C[Mask Input PII<br/>Presidio]
C --> D[Condense Follow-up<br/>into standalone question]
D --> E{Semantic<br/>Cache Hit?}
E -->|yes| F[Return cached answer]
E -->|no| G[Retrieve Top-15<br/>Qdrant Vector Store]
G --> H[Rerank Top-5<br/>Cross-Encoder]
H --> I[Fit to Token Budget]
I --> J[Generate Answer<br/>Portkey: Gemini / Groq]
J --> K[Guard Output<br/>leak / PII pattern check]
K --> L[Hallucination Check<br/>LLM-as-judge]
L --> M[Mask Output PII]
M --> N[Cache + Store History]
N --> O[Return Answer]上の各ノードは rag_pipeline/ 内のモジュールで、rag_pipeline/graph.py で LangGraph の StateGraph として組み合わされています。rag_core.py はすべての依存関係を一度だけ構築し(シングルトン)、chat()、search()、get_history()、cache_stats() という小規模で安定した API を提供します。この API は REST レイヤー(main.py)と MCP レイヤー(mcp_server.py)の両方から同じように利用されるため、リクエストがどのインターフェースから来ても、単一のベクターストア / キャッシュ / 会話履歴が共有されます。
📁 プロジェクト構成
mcp-docs-rag-assistant/
├── main.py # FastAPI app — REST endpoints + mounts MCP at /mcp
├── mcp_server.py # MCP tools (stdio standalone, or mounted in main.py)
├── rag_core.py # Singleton facade wiring the whole pipeline together
├── rag_pipeline/
│ ├── config.py # Env vars / secrets (single source of truth)
│ ├── logging_setup.py # Logging + Logfire
│ ├── gateway.py # Portkey multi-key LLM gateway
│ ├── errors.py # Retry + safe-node error handling
│ ├── ingestion.py # MCP docs loader + splitter
│ ├── vectorstore.py # Embeddings + persistent Qdrant store
│ ├── reranker.py # Cross-encoder reranking
│ ├── pii_masking.py # Presidio PII masking
│ ├── guardrails.py # NeMo Guardrails (Colang 2.x)
│ ├── token_management.py # Context window budgeting
│ ├── semantic_cache.py # Embedding-similarity cache
│ ├── query_condensation.py # Follow-up question rewriting
│ ├── hallucination.py # Runtime hallucination judge
│ └── graph.py # LangGraph StateGraph — full pipeline
├── scripts/
│ └── evaluate_ragas.py # Offline RAGAS evaluation (25 reference Q&A)
├── tests/
│ └── test_pipeline.py # Fast smoke tests (no API keys needed)
├── configs/guardrails/ # Colang rail files (generated at first run)
├── data/ # Persisted Qdrant vector store (gitignored)
├── notebooks/ # Original development notebook
├── Dockerfile
├── docker-compose.yml
├── requirements.txt
└── .env.example🚀 はじめに
前提条件
Python 3.11+
API キー: Google AI Studio(Gemini、×2)、Groq(×2)、Portkey(ゲートウェイ + 設定 ID)
1. クローンと仮想環境のセットアップ
git clone https://github.com/<your-username>/mcp-docs-rag-assistant.git
cd mcp-docs-rag-assistant
python -m venv venv
venv\Scripts\activate # Windows
# source venv/bin/activate # macOS/Linux2. 依存関係のインストール
pip install -r requirements.txt
python -m spacy download en_core_web_sm # required by Presidio for PII detection3. 環境変数の設定
cp .env.example .env.env を開き、実際のキー(GEMINI_API_KEY_1/2、GROQ_API_KEY_1/2、PORTKEY_API_KEY、PORTKEY_CONFIG_ID)を入力してください。
4. サーバーの起動
uvicorn main:app --reload⏳ 初回のみ: ベクターストアが存在しないため、サーバーは MCP ドキュメントを取り込んで、レート制限のあるバッチでベクトル化します。これには 5〜10 分かかる場合があります。以降の起動では
data/qdrant_mcp_db/から永続化されたストアを即座に読み込みます。
起動時に Startup: RAG pipeline ready. と表示されたら、以下の URL を開いてください:
http://localhost:8000/docs— インタラクティブな Swagger UI。POST /chatを試せます。http://localhost:8000/health— ヘルスチェック
📡 REST API
Method メソッド | Endpoint エンドポイント | Description 説明 |
|
| 質問する。ボディ: |
|
| 生のコンテキストを検索し再ランク付けする。ボディ: |
|
| スレッドの会話履歴を取得する |
|
| セマンティックキャッシュの観測性 |
|
| ヘルスチェック |
🔌 MCP サーバーとして利用する
スタンドアロン(stdio) — Claude Desktop 向け
直接実行:
python mcp_server.pyまたは、ローカルの MCP ホストに設定します。例: Claude Desktop の設定 (claude_desktop_config.json) 内:
{
"mcpServers": {
"mcp-docs-assistant": {
"command": "python",
"args": ["E:\\mcp-docs-rag-assistant\\mcp_server.py"]
}
}
}リモート開発(streamable-http) — FastAPI 経由
main.py が起動している場合、同じ MCP ツールが次の場所で利用できます:
http://localhost:8000/mcp利用可能なツール: ask_mcp_docs、search_mcp_docs、get_conversation_history、cache_stats
🐳 Docker
Docker の唯一の必要条件は Docker Desktop です(Docker Compose が同梱)。Python や pip の依存関係、spacy のモデルを個別にインストールする必要はありません。これらはすべて、イメージのビルド時にコンテナ内部で自動的に実行されます(Dockerfile を参照: ビルドステップとして pip install -r requirements.txt と python -m spacy download en_core_web_sm が実行されます)。
# 1. Make sure .env exists (same as the local setup, step 3 above)
cp .env.example .env # then fill in real keys
# 2. Build and run
docker compose up --buildこの1つのコマンドで、イメージのビルド、内部での apt内、コンテナの起動まで行えます。data/ フォルダはボリュームとしてマウントされるため(docker-compose.yml 参照)、ベクターストアはコンテナを再起動しても保持され、初回の取り込みコストが遅いのは Docker でも一度だけです。
ローカル実行と同じ方法で利用できます: http://localhost:8000/docs
停止するには:
docker compose downコードや依存関係を変更した後の再ビルド:
docker compose up --build🧪 テスト
高速なスモークテスト — API キーもネットワークも不要(フェイクの埋め込みを使用):
pip install pytest
pytest tests/ -v📊 オフライン評価 (RAGAS)
パイプラインを、手書きの MCP 質問 25 件(リファレンス回答付き)と照合してスコアリングします。RAGAS を使います:
python scripts/evaluate_ragas.pyこれはサーバーが起動している必要はありません — パイプライン自身を(main.py / mcp_server.py と同じシングルトンとして)構築し、メトリクステーブルを出力します。
Faithfulness — 回答は取得したコンテキストに基づいているか?
Response Relevancy — 回答は質問に直接的に対応しているか?
Context Precision — 取得されたコンテキストは関連しているか?
Context Recall — 取得されたコンテキストは参照回答に必要な内容をカバーしているか?
⏱️ 数分かかります: この25質問のそれぞれが実際に検索 + 生成を実行し、それから各メトリクスが LLM-as-judge によってスコアされます。
⚙️ 設定リファレンス
全ての設定は .env にあります(.env.example を参照)。主要な変数:
Variable 変数 | Purpose 目的 |
| プロバイダキー。Portkey でロードバランス |
| Portkey ゲートウェイの認証情報 + ルーティング設定 |
| ベクターストアの場所 / 名前 |
| オプション — 省略するとコンソールのみのログ |
| サーバのバインド設定 |
🛠️ 使用技術スタック
FastAPI ・ LangChain ・ LangGraph ・ Qdrant ・ Portkey ・ Sentence-Transformers ・ Presidio ・ NeMo Guardrails ・ RAGAS ・ MCP Python SDK ・ Docker
📄 ライセンス
MIT — はLICENSE を参照してください.
This server cannot be deployed
Maintenance
Related MCP Connectors
- docs2mcpOAuthcom.docs2mcp
Query your own PDFs and documents from any MCP client. Every answer cites the page it came from.
The AWS Knowledge MCP server is a fully managed remote Model Context Protocol server that provides real-time access to official AWS content in an LLM-compatible format. It offers structured access to AWS documentation, code samples, blog posts, What's New announcements, Well-Architected best practices, and regional availability information for AWS APIs and CloudFormation resources. Key capabilities include searching and reading documentation in markdown format, getting content recommendations, listing AWS regions, and checking regional availability for services and features.
The CustomGPT.ai MCP server is a fully managed, RAG-powered endpoint that connects large language models with private knowledge bases and external data sources. It provides tools for retrieval-augmented generation queries (send_message), data ingestion (upload_file), and source listing, enabling AI agents to query private documents like PDFs with high accuracy and real-time citations.
The Grafbase MCP server sits in front of a GraphQL API and exposes an MCP protocol-compliant interface that allows AI agents and LLMs to explore and query GraphQL APIs using natural language. It provides tools to search schemas, introspect types and fields, and execute GraphQL queries while minimizing context bloat by returning only relevant schema subsets, with built-in support for authentication, authorization, and configurable access control.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to access hybrid vector, reasoning-based tree retrieval, and agent memory through the Model Context Protocol (MCP), supporting Claude Desktop and other MCP-compatible clients.113 npmApache 2.0
- AlicenseNot gradedqualityCmaintenanceAn MCP server that enables Claude Desktop to search and read local documents via full-text and fuzzy search, providing direct access to indexed files without chunking.MIT
- FlicenseCqualityDmaintenanceProvides RAG (Retrieval-Augmented Generation) capabilities via Contextual AI, enabling query processing and context-aware responses with citations. Integrates with MCP clients like Cursor IDE and Claude Desktop.1-
- AlicenseNot gradedqualityCmaintenanceEnables hybrid retrieval-augmented generation with semantic and keyword search over documents, supporting multiple formats and providing MCP integration for Claude Desktop.MIT