Observed since 21 Oct, 10:51 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
RAG知识库检索增强生成系统 - MCP服务器
基于 LlamaIndex + MCP 协议的企业级 RAG 知识库系统
支持多种检索模式 | 模块化架构 | HTTP/STDIO双传输 | 生产就绪
RAG MCP Server 是一个基于 LlamaIndex 框架和 **MCP(Model Context Protocol)**协议的企业级检索增强生成(RAG)系统。该系统提供了强大的知识库管理和智能检索能力,支持多种检索模式,可通过 MCP 协议与 AI 助手(如 Claude Desktop)无缝集成。
✅ 多模式检索:支持向量检索、BM25检索和混合检索
✅ 模块化设计:清晰的代码组织,易于维护和扩展
✅ 双传输支持:STDIO 和 HTTP/SSE 两种传输方式
✅ 中文优化:使用 jieba 分词,完美支持中文文档
✅ 生产就绪:支持 Qdrant 云存储,可横向扩展
✅ 开发友好:完整的日志系统和错误处理
向量检索(Vector Search)
BM25检索(Sparse Retrieval)
混合检索(Hybrid Search) 🌟
本地存储(Simple Vector Store)
Qdrant云存储
STDIO传输
HTTP/SSE传输
| 工具名称 | 功能描述 |
|---|---|
build_index | 构建知识库索引(向量+BM25) |
query_knowledge | 查询知识库并生成答案(使用LLM) |
retrieve_documents | 检索相关文档片段(不使用LLM) 🆕 |
get_index_status | 获取索引状态和统计信息 |
get_config | 获取系统配置信息 🆕 |
delete_index | 删除所有索引 |
| 资源URI | 功能描述 |
|---|---|
config://system | 系统配置信息 |
stats://index | 索引统计信息 |
stats://index/verbose | 索引详细统计信息 🆕 |
支持的文档格式:
.txt - 纯文本文件.md - Markdown 文档.pdf - PDF 文档.docx - Word 文档# 克隆项目
git clone <repository-url>
cd aigroup-rag-mcp
# 安装依赖
pip install -r requirements.txt
创建 .env 文件并配置必要参数:
# ========== API 密钥 ==========
# DeepSeek API(必需)
DEEPSEEK_API_KEY=your_deepseek_api_key
DEEPSEEK_BASE_URL=https://api.deepseek.com/v1
# SiliconFlow API(必需,用于 Embedding)
SILICONFLOW_API_KEY=your_siliconflow_api_key
SILICONFLOW_BASE_URL=https://api.siliconflow.cn/v1
# ========== 模型配置 ==========
DEEPSEEK_MODEL=deepseek-chat
EMBEDDING_MODEL=Qwen/Qwen3-Embedding-8B
# ========== 检索配置 ==========
# 检索模式:vector, bm25, hybrid
RETRIEVAL_MODE=hybrid
DEFAULT_TOP_K=3
# BM25 配置
USE_BM25=True
BM25_TOP_K=5
BM25_LANGUAGE=chinese
# ========== 向量存储配置 ==========
USE_QDRANT=True
QDRANT_URL=your_qdrant_url
QDRANT_API_KEY=your_qdrant_api_key
QDRANT_COLLECTION_NAME=knowledge_base
# ========== 其他配置 ==========
CHUNK_SIZE=1024
CHUNK_OVERLAP=200
LLM_TEMPERATURE=0.1
LOG_LEVEL=INFO
将你的文档放入 my_knowledge_base 目录:
my_knowledge_base/
├── document1.txt
├── document2.md
├── guide.pdf
└── manual.docx
# 使用 Python 脚本
from src.core import RAGSystem
rag = RAGSystem()
rag.build_index('./my_knowledge_base')
python mcp_server.py
在 Claude Desktop 配置文件中添加:
{
"mcpServers": {
"rag-knowledge-base": {
"command": "python",
"args": ["D:/aigroup-rag-mcp/mcp_server.py"],
"env": {}
}
}
}
# 启动 HTTP 服务器
python mcp_http_server.py
# 或使用 Uvicorn
uvicorn mcp_http_server:app --host 0.0.0.0 --port 8000
访问 http://localhost:8000 查看服务状态。
from src.core import RAGSystem
rag = RAGSystem()
result = rag.query("什么是RAG技术?", mode="hybrid", top_k=3)
print(result['answer'])
aigroup-rag-mcp/
├── src/ # 源代码目录
│ ├── config/ # 配置模块
│ │ └── config.py # 系统配置类
│ ├── core/ # 核心业务逻辑
│ │ └── rag_system.py # RAG系统核心实现
│ ├── embeddings/ # 嵌入模型
│ │ └── siliconflow_embedding.py
│ ├── tokenizers/ # 分词器
│ │ └── jieba_tokenizer.py # 中文分词器
│ ├── storage/ # 存储管理
│ │ ├── vector_store.py # 向量存储管理
│ │ └── bm25_store.py # BM25存储管理
│ ├── mcp/ # MCP服务器
│ │ └── handlers/ # MCP处理器
│ │ ├── tools_handler.py # 工具处理器
│ │ ├── resources_handler.py # 资源处理器
│ │ └── prompts_handler.py # 提示词处理器
│ └── utils/ # 工具函数
│ ├── logger.py # 日志配置
│ └── patches.py # 猴子补丁
├── storage/ # 存储目录
│ ├── vector/ # 向量索引存储
│ │ └── simple/ # 本地向量存储
│ └── bm25/ # BM25索引存储
├── doc/ # 文档目录
│ ├── BM25_FEATURE_README.md # BM25功能文档
│ ├── MCP_HTTP_SERVER_README.md # HTTP服务器文档
│ └── REFACTORING_GUIDE.md # 重构指南
├── logs/ # 日志文件
├── my_knowledge_base/ # 知识库目录
├── mcp_server.py # STDIO MCP服务器
├── mcp_http_server.py # HTTP MCP服务器
├── requirements.txt # 依赖清单
├── .env # 环境变量配置
├── .gitignore # Git忽略文件
└── README.md # 本文档
src/config/config.py)src/core/rag_system.py)src/embeddings/siliconflow_embedding.py)src/tokenizers/jieba_tokenizer.py)src/storage/vector_store.py)
src/storage/bm25_store.py)
src/mcp/handlers/)from src.core import RAGSystem
# 创建RAG系统实例
rag = RAGSystem()
# 构建索引
success = rag.build_index("./my_knowledge_base")
# 查询(使用默认混合模式)
result = rag.query("什么是RAG技术?")
print(result['answer'])
# 查看源文档
for source in result['sources']:
print(f"评分: {source['score']}")
print(f"内容: {source['text']}")
print(f"元数据: {source['metadata']}")
from src.core import RAGSystem
from src.config import Config
# 创建RAG系统
rag = RAGSystem(config=Config)
# 使用不同检索模式查询
result_vector = rag.query("问题", mode="vector", top_k=5)
result_bm25 = rag.query("问题", mode="bm25", top_k=5)
result_hybrid = rag.query("问题", mode="hybrid", top_k=5)
# 获取索引统计信息
stats = rag.get_index_stats()
print(f"向量索引: {stats['vector_index_exists']}")
print(f"BM25索引: {stats['bm25_index_exists']}")
print(f"检索模式: {stats['retrieval_mode']}")
# 删除索引
rag.delete_index()
build_index(data_dir, force_rebuild=False)构建知识库索引。
参数:
data_dir (str): 文档目录路径force_rebuild (bool): 是否强制重建索引返回:
bool: 构建是否成功load_index()从存储加载索引。
返回:
bool: 加载是否成功query(question, top_k=None, mode=None)查询知识库。
参数:
question (str): 用户问题top_k (int, optional): 检索的文档数量mode (str, optional): 检索模式 (vector/bm25/hybrid)返回:
dict: 包含答案和元数据的字典{
"success": bool,
"answer": str,
"sources": List[dict],
"mode": str,
"error": Optional[str]
}
get_index_stats()获取索引统计信息。
返回:
dict: 索引统计信息delete_index()删除所有索引。
返回:
bool: 删除是否成功| 参数 | 说明 | 默认值 |
|---|---|---|
DEEPSEEK_API_KEY | DeepSeek API密钥 | 必需 |
DEEPSEEK_BASE_URL | DeepSeek API地址 | https://api.deepseek.com/v1 |
SILICONFLOW_API_KEY | SiliconFlow API密钥 | 必需 |
SILICONFLOW_BASE_URL | SiliconFlow API地址 | https://api.siliconflow.cn/v1 |
| 参数 | 说明 | 默认值 |
|---|---|---|
DEEPSEEK_MODEL | LLM模型名称 | deepseek-chat |
EMBEDDING_MODEL | Embedding模型名称 | Qwen/Qwen3-Embedding-8B |
LLM_TEMPERATURE | LLM温度参数 | 0.1 |
| 参数 | 说明 | 默认值 |
|---|---|---|
RETRIEVAL_MODE | 检索模式 | hybrid |
DEFAULT_TOP_K | 检索文档数量 | 3 |
BM25_TOP_K | BM25检索数量 | 5 |
BM25_LANGUAGE | 分词语言 | chinese |
CHUNK_SIZE | 文本分块大小 | 1024 |
CHUNK_OVERLAP | 分块重叠大小 | 200 |
| 参数 | 说明 | 默认值 |
|---|---|---|
USE_QDRANT | 是否使用Qdrant | True |
QDRANT_URL | Qdrant服务地址 | - |
QDRANT_API_KEY | Qdrant API密钥 | - |
QDRANT_COLLECTION_NAME | 集合名称 | knowledge_base |
适用场景:
启动方式:
python mcp_server.py
适用场景:
启动方式:
# 开发模式
python mcp_http_server.py
# 生产模式(多worker)
uvicorn mcp_http_server:app --workers 4 --host 0.0.0.0 --port 8000
API端点:
GET / - 服务器信息GET /health - 健康检查GET /sse - SSE通信端点POST /messages - 消息发送端点GET /docs - API文档详细文档:MCP HTTP服务器使用指南
特点:
适用场景:概念性问题、语义相似查询
result = rag.query("如何提升模型性能", mode="vector")
特点:
适用场景:精确术语查找、关键词搜索
result = rag.query("BM25算法", mode="bm25")
特点:
适用场景:默认推荐、通用查询场景
result = rag.query("RAG技术的核心思想", mode="hybrid")
| 特性 | Vector | BM25 | Hybrid |
|---|---|---|---|
| 语义理解 | ✅ 强 | ❌ 弱 | ✅ 强 |
| 关键词匹配 | ❌ 弱 | ✅ 强 | ✅ 强 |
| 查询速度 | 中 | 快 | 中 |
| 准确度 | 高 | 中 | 最高 |
| 推荐指数 | ⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐⭐⭐ |
详细文档:BM25混合检索功能使用指南
本项目采用模块化设计,各模块职责清晰:
配置层 (config) → 业务层 (core) → 存储层 (storage)
↓
接口层 (mcp)
详细文档:代码重构指南
from llama_index.core.embeddings import BaseEmbedding
class CustomEmbedding(BaseEmbedding):
def _get_query_embedding(self, query: str) -> List[float]:
# 实现查询嵌入
pass
def _get_text_embedding(self, text: str) -> List[float]:
# 实现文本嵌入
pass
在 src/mcp/handlers/tools_handler.py 中:
def list_tools(self) -> list[Tool]:
return [
Tool(
name="custom_tool",
description="自定义工具描述",
inputSchema={...}
)
]
A: 建议默认使用 hybrid 混合检索模式。对于特定场景:
vectorbm25hybridA: 完全支持!系统使用 jieba 进行中文分词,在配置中设置 BM25_LANGUAGE=chinese 即可。
A: 在 .env 文件中设置 USE_QDRANT=False。
A: 检查:
logs/rag_system.logA: 两种方式:
# 方式1:强制重建
rag.build_index("./my_knowledge_base", force_rebuild=True)
# 方式2:删除后重建
rag.delete_index()
rag.build_index("./my_knowledge_base")
A: 参考 MCP HTTP服务器使用指南 中的生产部署章节。
欢迎贡献代码、报告问题或提出建议!
git checkout -b feature/AmazingFeature)git commit -m 'Add some AmazingFeature')git push origin feature/AmazingFeature)本项目采用 MIT 许可证。详见 LICENSE 文件。
如有问题或建议,请通过以下方式联系:
感谢以下开源项目:
⭐ 如果这个项目对你有帮助,请给它一个星标! ⭐
Made with ❤️ by AI Group
Download counts and popularity will appear here as the collector receives them.
| Version | Published | Direct dependencies | Open version |
|---|---|---|---|
| 1.2.1 | 12 Jan 2026 | 36 |
This describes our collected data; it is not a security assessment.
Observed since 21 Oct, 10:51 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
package:c7efbedc3aeb3c347223ea17d7cd01ef72a84d39dc2c84265d375980da418116