| name | modular-rag-mcp-server |
| description | Expert in deploying and customizing a modular RAG system with MCP protocol for AI assistants |
| triggers | ["how do I set up the modular RAG MCP server","help me configure the RAG knowledge hub","integrate RAG with Claude Desktop using MCP","troubleshoot hybrid search and reranking","add documents to the RAG system","evaluate RAG performance with Ragas","customize RAG components like embeddings or reranker","run the RAG dashboard"] |
Modular RAG MCP Server
Skill by ara.so โ MCP Skills collection.
Expert skill for deploying, configuring, and extending the Modular RAG MCP Server โ a pluggable, observable RAG (Retrieval-Augmented Generation) system that exposes tools via Model Context Protocol for AI assistants like Claude Desktop and GitHub Copilot.
What This Project Does
The Modular RAG MCP Server is a complete RAG pipeline featuring:
- Ingestion Pipeline: PDF โ Markdown โ Chunking โ Embedding โ Vector Store (with multimodal image captioning)
- Hybrid Search: Dense vectors (semantic) + Sparse BM25 (exact match) + RRF fusion + optional reranking
- MCP Protocol: Standard MCP server exposing
query_knowledge_hub, list_collections, get_document_summary tools
- Dashboard: Streamlit-based management UI with 6 pages (overview, data browser, ingestion tracking, query tracking, evaluation)
- Evaluation Framework: Ragas + custom metrics for regression testing
- Full Observability: White-box tracing of ingestion and query pipelines
Key Architecture: Every core component (LLM, Embedding, Reranker, Splitter, VectorStore, Evaluator) is pluggable via abstract interfaces. Switch backends through configuration without code changes.
Installation
Prerequisites
- Python 3.9+
- VS Code with GitHub Copilot or Claude Desktop
- API keys for your chosen providers (OpenAI, Anthropic, Cohere, etc.)
Quick Setup with Setup Skill
The project includes a Setup Skill that automates the entire configuration:
git clone https://github.com/jerry-ai-dev/MODULAR-RAG-MCP-SERVER.git
cd MODULAR-RAG-MCP-SERVER
setup
The Setup Skill will:
- Ask you to select providers (OpenAI, Anthropic, Cohere, etc.)
- Configure API keys
- Install dependencies
- Generate configuration files
- Launch the dashboard
Manual Setup
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
Configuration
Main Configuration File (src/core/config.py)
The system uses a centralized configuration approach. Key settings:
from src.core.config import get_config
config = get_config()
llm_provider = config.llm.provider
embedding_provider = config.embedding.provider
vector_store_type = config.vector_store.type
Environment Variables
Create .env file with required keys:
OPENAI_API_KEY=your_openai_key_here
ANTHROPIC_API_KEY=your_anthropic_key_here
COHERE_API_KEY=your_cohere_key_here
JINA_API_KEY=your_jina_key_here
QDRANT_URL=your_qdrant_url
QDRANT_API_KEY=your_qdrant_key
Provider Configuration
Edit src/core/config.py to set default providers:
class LLMConfig:
provider: str = "openai"
model: str = "gpt-4"
temperature: float = 0.7
max_tokens: int = 2048
class EmbeddingConfig:
provider: str = "openai"
model: str = "text-embedding-3-small"
dimension: int = 1536
class RerankerConfig:
enabled: bool = True
provider: str = "cohere"
model: str = "rerank-english-v3.0"
top_k: int = 5
Key Components and API
1. Ingestion Pipeline
Ingest documents into the knowledge base:
from src.ingestion.pipeline import IngestionPipeline
from src.core.config import get_config
config = get_config()
pipeline = IngestionPipeline(config)
result = pipeline.ingest_document(
file_path="path/to/document.pdf",
collection_name="my_collection",
metadata={"source": "internal_docs", "version": "1.0"}
)
print(f"Ingested {result['chunks_created']} chunks")
print(f"Ingestion ID: {result['ingestion_id']}")
2. Hybrid Search and Query
Query the knowledge base with hybrid search:
from src.retrieval.hybrid_search import HybridSearchRetriever
from src.core.config import get_config
config = get_config()
retriever = HybridSearchRetriever(config)
results = retriever.retrieve(
query="How does the authentication system work?",
collection_name="my_collection",
top_k=10,
rerank_top_k=5
)
for idx, result in enumerate(results):
print(f"{idx+1}. Score: {result.score:.4f}")
print(f" Text: {result.text[:100]}...")
print(f" Metadata: {result.metadata}")
3. MCP Server Integration
The MCP server exposes tools for AI assistants. Start the server:
python src/mcp/server.py
Configure in Claude Desktop (claude_desktop_config.json):
{
"mcpServers": {
"rag-knowledge-hub": {
"command": "python",
"args": ["/path/to/project/src/mcp/server.py"],
"env": {
"PYTHONPATH": "/path/to/project"
}
}
}
}
Available MCP Tools:
-
query_knowledge_hub: Query the RAG system
{
"query": "What are the deployment requirements?",
"collection_name": "my_collection",
"top_k": 5
}
-
list_collections: List all available collections
-
get_document_summary: Get summary of a specific document
{
"document_id": "doc_123",
"collection_name": "my_collection"
}
4. Dashboard
Launch the Streamlit dashboard:
streamlit run src/dashboard/app.py
Dashboard pages:
- Overview: System status, collection stats, recent activity
- Data Browser: Browse and search ingested documents
- Ingestion Management: Upload new documents, view ingestion history
- Ingestion Tracking: Monitor ingestion pipeline steps
- Query Tracking: Analyze query performance and results
- Evaluation Panel: Run evaluations with Ragas metrics
5. Evaluation with Ragas
Evaluate RAG performance:
from src.evaluation.evaluator import RAGEvaluator
from src.core.config import get_config
config = get_config()
evaluator = RAGEvaluator(config)
test_cases = [
{
"query": "What is the API rate limit?",
"expected_answer": "The API rate limit is 1000 requests per hour.",
"ground_truth_context": ["Rate limits are set to 1000 req/hour..."]
},
]
results = evaluator.evaluate(
test_cases=test_cases,
collection_name="my_collection",
metrics=["faithfulness", "answer_relevancy", "context_precision"]
)
print(f"Average Faithfulness: {results['faithfulness']:.3f}")
print(f"Average Answer Relevancy: {results['answer_relevancy']:.3f}")
Common Patterns
Switching Embedding Providers
To switch from OpenAI to Cohere embeddings:
class EmbeddingConfig:
provider: str = "cohere"
model: str = "embed-english-v3.0"
dimension: int = 1024
Or programmatically:
from src.core.config import get_config
config = get_config()
config.embedding.provider = "cohere"
config.embedding.model = "embed-english-v3.0"
config.embedding.dimension = 1024
Adding Custom Chunking Strategy
Implement a custom text splitter:
from src.ingestion.splitters.base import BaseSplitter
from typing import List
class CustomSplitter(BaseSplitter):
def __init__(self, chunk_size: int = 500, overlap: int = 50):
self.chunk_size = chunk_size
self.overlap = overlap
def split(self, text: str, metadata: dict = None) -> List[dict]:
chunks = []
start = 0
while start < len(text):
end = start + self.chunk_size
chunk_text = text[start:end]
chunks.append({
"text": chunk_text,
"metadata": {
**(metadata or {}),
"chunk_index": len(chunks),
"start_char": start
}
})
start += self.chunk_size - self.overlap
return chunks
from src.ingestion.pipeline import IngestionPipeline
pipeline = IngestionPipeline(config)
pipeline.splitter = CustomSplitter(chunk_size=300, overlap=30)
Implementing Custom Reranker
from src.retrieval.rerankers.base import BaseReranker
from typing import List
class CustomReranker(BaseReranker):
def rerank(self, query: str, documents: List[dict], top_k: int = 5) -> List[dict]:
scored_docs = []
for doc in documents:
score = sum(1 for word in query.lower().split()
if word in doc['text'].lower())
scored_docs.append({**doc, 'rerank_score': score})
scored_docs.sort(key=lambda x: x['rerank_score'], reverse=True)
return scored_docs[:top_k]
from src.retrieval.hybrid_search import HybridSearchRetriever
retriever = HybridSearchRetriever(config)
retriever.reranker = CustomReranker()
Multimodal Image Processing
The system supports image captioning in PDFs:
from src.ingestion.pipeline import IngestionPipeline
pipeline = IngestionPipeline(config)
result = pipeline.ingest_document(
file_path="document_with_images.pdf",
collection_name="multimodal_docs",
enable_image_captioning=True,
metadata={"type": "technical_manual"}
)
Batch Ingestion
Ingest multiple documents:
import os
from pathlib import Path
pipeline = IngestionPipeline(config)
docs_dir = Path("./documents")
results = []
for pdf_file in docs_dir.glob("*.pdf"):
try:
result = pipeline.ingest_document(
file_path=str(pdf_file),
collection_name="batch_collection",
metadata={"filename": pdf_file.name}
)
results.append(result)
print(f"โ Ingested {pdf_file.name}")
except Exception as e:
print(f"โ Failed {pdf_file.name}: {e}")
print(f"Total successful: {len(results)}")
Troubleshooting
MCP Server Not Connecting
Issue: Claude Desktop cannot connect to MCP server
Solution:
- Check Claude Desktop config path (macOS:
~/Library/Application Support/Claude/claude_desktop_config.json)
- Ensure Python path and project path are absolute
- Verify environment variables are set in config:
{
"mcpServers": {
"rag-knowledge-hub": {
"command": "/usr/bin/python3",
"args": ["/absolute/path/to/project/src/mcp/server.py"],
"env": {
"PYTHONPATH": "/absolute/path/to/project",
"OPENAI_API_KEY": "sk-..."
}
}
}
}
- Restart Claude Desktop completely
Poor Retrieval Results
Issue: Query returns irrelevant documents
Solutions:
-
Check chunking strategy: Smaller chunks for precise retrieval, larger for more context
config.ingestion.chunk_size = 300
config.ingestion.chunk_overlap = 50
-
Enable reranking: Use cross-encoder or LLM reranker
config.reranker.enabled = True
config.reranker.provider = "cohere"
config.reranker.top_k = 5
-
Adjust hybrid search weights:
from src.retrieval.hybrid_search import HybridSearchRetriever
retriever = HybridSearchRetriever(config)
retriever.dense_weight = 0.7
retriever.sparse_weight = 0.3
-
Use evaluation to iterate:
evaluator = RAGEvaluator(config)
results = evaluator.evaluate(test_cases, collection_name="my_collection")
Vector Store Connection Issues
Issue: Cannot connect to Qdrant/Chroma
Solution:
-
For Qdrant Cloud:
QDRANT_URL=https://your-cluster.qdrant.io
QDRANT_API_KEY=your_api_key
-
For local Qdrant:
docker run -p 6333:6333 qdrant/qdrant
QDRANT_URL=http://localhost:6333
-
For Chroma (local):
class VectorStoreConfig:
type: str = "chroma"
persist_directory: str = "./chroma_db"
Out of Memory During Ingestion
Issue: Large PDFs cause OOM errors
Solutions:
-
Process in batches:
config.ingestion.chunk_size = 800
config.ingestion.batch_size = 10
-
Use streaming for large documents:
pipeline = IngestionPipeline(config)
pipeline.process_streaming(
file_path="large_document.pdf",
collection_name="large_docs"
)
API Rate Limits
Issue: Hitting provider rate limits
Solutions:
-
Implement retry with exponential backoff:
config.llm.max_retries = 5
config.llm.retry_delay = 2.0
-
Use batch embedding APIs:
config.embedding.batch_size = 100
-
Switch to providers with higher limits (e.g., Cohere for embeddings)
Advanced Usage
Custom RAG Pipeline
Build a custom RAG pipeline with specific components:
from src.core.config import get_config
from src.retrieval.hybrid_search import HybridSearchRetriever
from src.generation.generator import Generator
from src.evaluation.evaluator import RAGEvaluator
config = get_config()
retriever = HybridSearchRetriever(config)
retriever.dense_weight = 0.6
retriever.sparse_weight = 0.4
generator = Generator(config)
generator.system_prompt = "You are a helpful technical assistant..."
def custom_rag_query(query: str, collection: str):
contexts = retriever.retrieve(query, collection, top_k=5)
response = generator.generate(
query=query,
contexts=[c.text for c in contexts],
metadata=[c.metadata for c in contexts]
)
evaluator = RAGEvaluator(config)
metrics = evaluator.evaluate_single(
query=query,
response=response,
contexts=[c.text for c in contexts]
)
return {
"response": response,
"contexts": contexts,
"metrics": metrics
}
result = custom_rag_query("What are the system requirements?", "docs")
print(result["response"])
Integrating with Your Own Application
Use the RAG system as a library:
from src.rag_system import RAGSystem
from src.core.config import get_config
config = get_config()
rag = RAGSystem(config)
@app.post("/ask")
async def ask_question(query: str, collection: str = "default"):
result = rag.query(
query=query,
collection_name=collection,
top_k=5
)
return {
"answer": result["response"],
"sources": result["contexts"],
"confidence": result["metrics"]["answer_relevancy"]
}
Branch Strategy
main: Clean, production-ready code (1 commit with latest complete code)
dev: Full commit history showing development progression
clean-start: Skeleton with Skills and DEV_SPEC, zero progress (for learning from scratch)
Choose branch based on your needs:
- Quick deployment โ
main
- Understanding the build process โ
dev
- Learning by building yourself โ
clean-start
Additional Resources
- DEV_SPEC.md: Complete architecture design and task breakdown
- Resume Writer Skill: Generate customized resume descriptions for this project
- QA Tester Skill: Automated testing across unit/integration/E2E layers
- Package Skill: Clean and package project for distribution
Use these skills in VS Code by typing the skill name in Copilot/Claude chat.