集成MCP的RAG服务器
与Google AI Studio集成的Retrieval-AugedGeneration(RAG)系统,具有REST API和模型上下文协议(MCP)服务器。
特性
核心能力
- 文档存储:上传和存储文本(.txt)和Markdown(.md)文档
- 分层分块:保留文档层次结构的markdown结构感知分块
- 矢量搜索:使用Qdrant矢量数据库进行高效的相似性搜索
- 谷歌人工智能集成:使用Google AI Studio进行嵌入(text-embedding-004)和生成(gemini-1.5-flash)
- REST API:基于FastAPI的REST API,带有自动OpenAPI文档
- MCP服务器:用于与Claude和其他MCP客户端无缝集成的模型上下文协议服务器
- OpenAI兼容的API:支持OpenAI兼容的聊天完成,用于web UI集成
- 编码索引:使用语义理解对源代码库进行索引和搜索
- 智能查询路由:自动查询分类和路由到适当的检索方法
高级功能
- 基于标签的组织:使用多个标签组织文档,便于分类
- 节感知检索:查询文档的特定部分(例如,“安装>先决条件”)
- Markdown结构保存:使用面包屑路径自动提取标题层次结构
- 上下文增强答案:LLM接收部分上下文以获得更准确的响应
- 灵活过滤:在查询过程中按标签和/或节路径筛选文档
- 文件结构API:探索目录和章节组织
- GitHub集成:从GitHub URL解析和提取内容
- 参考如下:自动遵循文档参考以获得全面答案
- 多模式检索:在标准、增强或智能查询模式之间进行选择
- 速率限制:API端点的内置速率限制
项目结构
mcp-rag-docs/
config/
__init__.py
settings.py # Configuration and settings
rag_server/
__init__.py
models.py # Pydantic models for API
openai_api.py # OpenAI-compatible API endpoints
openai_models.py # OpenAI API models
rag_system.py # Core RAG system logic
server.py # FastAPI server
smart_query.py # Smart query routing
mcp_server/
__init__.py
server.py # MCP server implementation
utils/
__init__.py
code_indexer.py # Source code indexing
code_index_store.py # Code index storage
document_processor.py # Document processing
embeddings.py # Google AI embeddings
frontmatter_parser.py # YAML frontmatter parsing
github_parser.py # GitHub URL parsing
google_api_client.py # Google AI API client
hierarchical_chunker.py # Hierarchical document chunking
markdown_parser.py # Markdown parsing
query_classifier.py # Query type classification
rate_limit_store.py # Rate limiting
reference_extractor.py # Extract doc references
retrieval_router.py # Multi-mode retrieval routing
source_extractor.py # Extract source code snippets
text_chunker.py # Text chunking utility
vector_store.py # Qdrant vector store wrapper
build_code_index.py # Build code index from repository
check_github_urls.py # Validate GitHub URLs
check_status.py # System status checker
example_usage.py # Example usage scripts
ingest_docs.py # Document ingestion utility
main.py # Main entry point
.env.example # Example environment variables
docker-compose.yml # Docker setup for Qdrant
pyproject.toml # Project dependencies安装
先决条件
- Python 3.13或更高版本
- Google AI Studio API密钥(在这里买一个)
设置
- 克隆或导航到项目目录
- 安装依赖项
# Using pip
pip install -e .
# Or using uv (recommended)
uv pip install -e .- 配置环境变量
# Copy the example env file
cp .env.example .env
# Edit .env and add your Google API key
GOOGLE_API_KEY=your_api_key_here- 启动Qdrant(可选-使用Docker)
docker-compose up -d用法
运行FastAPI服务器
启动REST API服务器:
python -m rag_server.server服务器将在以下时间启动 http://localhost:8000.参观 http://localhost:8000/docs 用于交互式API文档。
API终点
核心终点:
- POST/文件 -上传文档
- POST/查询 -查询RAG系统(标准模式)
- POST/查询增强 -自动参照查询
- POST/智能查询 -具有自动路由功能的智能查询
- GET/文件 -列出所有文件
- 删除/文档/{doc_id} -删除文档
- 获取/统计 -获取系统统计信息
- GET/健康 -健康检查
- GET/标签 -列出所有可用标签
- GET/documents/{doc_id}/sections -获取文档结构
OpenAI兼容端点:
- POST/v1/聊天/补全 -OpenAI兼容的聊天完成
- GET/v1/型号 -列出可用型号
使用curl的示例
# Upload a document
curl -X POST "http://localhost:8000/documents" \
-F "file=@example.txt"
# Upload with tags
curl -X POST "http://localhost:8000/documents" \
-F "file=@dagster-docs.md" \
-F "tags=dagster,python,orchestration"
# Query the RAG system
curl -X POST "http://localhost:8000/query" \
-H "Content-Type: application/json" \
-d '{"question": "What is the main topic of the documents?", "top_k": 5}'
# Smart query with automatic routing
curl -X POST "http://localhost:8000/smart-query" \
-H "Content-Type: application/json" \
-d '{"question": "How do I create a Dagster asset?"}'
# OpenAI-compatible chat completion
curl -X POST "http://localhost:8000/v1/chat/completions" \
-H "Content-Type: application/json" \
-d '{
"model": "rag-smart",
"messages": [{"role": "user", "content": "What is an asset in Dagster?"}],
"stream": false
}'
# List documents
curl "http://localhost:8000/documents"
# Get statistics
curl "http://localhost:8000/stats"运行MCP服务器
MCP服务器允许与Claude和其他MCP兼容客户端集成。
python -m mcp_server.serverMCP工具可用
- query_rag -用问题查询RAG系统
- query_rag_enhanced -自动参照查询
- smart_query -具有自动路由和分类功能的智能查询
- add_document -将文档添加到RAG系统
- list_文档 -列出所有存储的文档
- 删除文档 -按ID删除文档
- get_rag_stats -获取系统统计信息
- 获取标签 -列出所有可用标签
- get_document_structure -获取文档目录
与Claude Desktop一起使用
添加到您的Claude Desktop配置(claude_desktop_config.json):
{
"mcpServers": {
"rag": {
"command": "uv",
"args": [
"--directory",
"/path/to/mcp-rag-docs",
"run",
"python",
"-m",
"mcp_server.server"
]
}
}
}看 快速启动.md 获取快速设置指南。
配置
所有配置均通过环境变量(定义于 .env):
| 变量 | 描述 | 默认值 |
|---|---|---|
GOOGLE_API_KEY | Google AI Studio API密钥 | (必需) |
CHUNK_SIZE | 文本块大小(字符) | 1000 |
CHUNK_OVERLAP | 块之间的重叠 | 200 |
TOP_K_RESULTS | 要检索的块数 | 5 |
QDRANT_PATH | Qdrant存储路径 | 。/qdrant_存储 |
QDRANT_COLLECTION_NAME | Qdrant集合名称 | 文档 |
FASTAPI_HOST | FastAPI服务器主机 | 0.0.0.0 |
FASTAPI_PORT | FastAPI服务器端口 | 8000 |
EMBEDDING_MODEL | 谷歌嵌入模型 | text-embedding-004 |
LLM_MODEL | 谷歌LLM模型 | 双子座-1.5-flash |
建筑
文档处理管道
- 上传 -用户上传.txt或.md文件
- 处理 -读取文档并提取元数据(包括frontmatter)
- 分块 -文本使用分层分块进行标记,或使用标准分块进行文本分割
- 嵌入 -使用Google AI嵌入将每个块转换为向量
- 存储 -矢量和元数据存储在Qdrant中
查询管道
标准查询
- 查询 -用户提交问题
- 嵌入 -问题转换为向量
- 检索 -从Qdrant中检索到类似的块
- 生成 -为Google AI Studio模型提供上下文
- 响应 -生成答案并返回来源
智能查询
- 分类 -查询被分类(文档、代码、概念等)
- 路由 -自动选择最佳检索策略
- 多源 -可以结合文档搜索、代码搜索和直接答案
- 合成 -从多个来源生成全面的答案
编码索引
该系统可以对源代码存储库进行索引:
# Build code index
python build_code_index.py /path/to/repo
# Query code through the API or MCP server代码索引为:
- 类和函数定义
- 文档字符串和注释
- 文件结构和导入
- 自然语言查询的语义嵌入
发展
运行测试
# Install test dependencies
pip install pytest pytest-asyncio httpx
# Run tests
pytest
# Run specific test files
pytest test_openai_api.py
pytest test_mcp_integration.py代码的风格
该项目遵循Python的最佳实践,使用类型提示和文档字符串。
故障排除
常见问题
问题: GOOGLE_API_KEY not found
- 解决方案:确保您已创建
.env文件并添加您的Google API密钥
问题: Unsupported file type
- 解决方案:仅支持.txt和.md文件。先转换其他格式。
问题: Collection already exists 错误
- 解决方案:删除
qdrant_storage/重置数据库的目录
问题:MCP服务器未连接
- 解决方案:检查MCP配置中的路径是否正确,以及
.env文件位于项目根目录中
高级用法
基于标签的组织
使用标签组织文档,便于分类和过滤:
# Upload document with tags
curl -X POST "http://localhost:8000/documents" \
-F "file=@dagster-docs.md" \
-F "tags=dagster,python,orchestration"
# List all available tags
curl "http://localhost:8000/tags"
# Query only dagster-related documents
curl -X POST "http://localhost:8000/query" \
-H "Content-Type: application/json" \
-d '{"question": "How do I create a pipeline?", "tags": ["dagster"]}'
# List documents filtered by tags
curl "http://localhost:8000/documents?tags=dagster,python"分层文档结构
对于标记文档,系统会自动保留标题层次结构:
# Get document structure (table of contents)
curl "http://localhost:8000/documents/{doc_id}/sections"
# Query specific section
curl -X POST "http://localhost:8000/query" \
-H "Content-Type: application/json" \
-d '{"question": "What are the prerequisites?", "section_path": "Installation > Prerequisites"}'节感知查询
生成答案时,系统包括部分上下文:
# Example: Markdown document structure
# Installation
# Prerequisites
# Python Version
# Setup Steps
# When you query about "Python version requirements"
# The system will:
# 1. Retrieve relevant chunks from "Installation > Prerequisites > Python Version"
# 2. Include section path in context sent to LLM
# 3. Cite sources with full section paths智能查询模式
系统支持三种查询模式:
- 标准 (
/query)-基本矢量搜索和检索 - 增强 (
/query-enhanced)-自动遵循文档参考 - 聪明的 (
/smart-query)-自动分类和路由
使用与OpenAI兼容的API访问不同的模式:
# Standard mode
curl -X POST "http://localhost:8000/v1/chat/completions" \
-H "Content-Type: application/json" \
-d '{"model": "rag-standard", "messages": [{"role": "user", "content": "What is Dagster?"}]}'
# Enhanced mode with reference following
curl -X POST "http://localhost:8000/v1/chat/completions" \
-H "Content-Type: application/json" \
-d '{"model": "rag-enhanced", "messages": [{"role": "user", "content": "What is Dagster?"}]}'
# Smart mode with automatic routing
curl -X POST "http://localhost:8000/v1/chat/completions" \
-H "Content-Type: application/json" \
-d '{"model": "rag-smart", "messages": [{"role": "user", "content": "What is Dagster?"}]}'MCP工具
MCP服务器为Claude和其他MCP客户端提供了增强的工具:
query_rag -使用可选标签和部分过滤进行查询
{
"question": "How do I deploy?",
"tags": ["dagster"],
"section_path": "Deployment"
}smart_query -具有自动路由功能的智能查询
{
"question": "What is an asset and how do I use it?"
}add_document -带标签上传
{
"file_path": "/path/to/doc.md",
"tags": ["dagster", "docs"]
}获取标签 -列出所有标签
get_document_structure -获取目录
{
"doc_id": "abc123"
}API 参考
增强的端点
POST/文件
- 主体:
file(多部分),tags(逗号分隔字符串) - 响应:带有标签和块计数的文档信息
POST/查询
- 主体:
{"question": "...", "tags": [...], "section_path": "..."} - 回复:使用了解部分信息的来源进行回答
POST/智能查询
- 主体:
{"question": "..."} - 响应:智能答案,自动路由和分类
GET/标签
- 答复:
{"tags": [...], "total": N}
GET/documents/{doc_id}/sections
- 响应:具有节层次结构的文档结构
GET/文件?tags=tag1,tag2
- 按标签筛选的查询
- 回复:匹配文件列表
POST/v1/聊天/补全
- OpenAI兼容的聊天完成端点
- 支持型号:
rag-standard,rag-enhanced,rag-smart - 支持流媒体
stream: true
GET/v1/型号
- 列出可用的RAG型号
其他文件
- 快速启动.md -MCP集成快速设置指南
- MCP_SETUP.md -详细的MCP服务器设置
- OPENAI_API_GUIDE.md -与OpenAI兼容的API文档
- 查询_查询_GUIDE.md -智能查询路由指南
- MULTI_MODE_RETRIEVAL_GUIDE.md -多模式检索文档
- CODE_INDEX_GUIDE.md -代码索引和搜索指南
- 费率_限制.md -速率限制配置
- 测试_验证.md -测试覆盖率和测试指南
许可证
MIT许可证
贡献
欢迎投稿!请随时提交拉取请求。
致谢
- 用于嵌入和LLM功能的Google AI Studio
- 矢量数据库Qdrant
- 用于REST API框架的FastAPI
- 模型上下文协议的拟人MCP
