PDF RAG MCP服务器
一种模型上下文协议(MCP)服务器,为PDF提供强大的RAG(检索增强生成)功能 文件。该服务器使用ChromaDB进行向量存储,使用句子变换器进行嵌入,使用语义分块进行 智能文本分割。
特性
- ✅ 语义分块:智能地将句子组合在一起,而不是在任意字符限制下拆分
- ✅ 矢量搜索:使用嵌入查找语义相似的内容
- ✅ 关键字搜索:传统的基于关键字的精确术语搜索
- ✅ OCR支持:对扫描/基于图像的PDF进行自动检测和OCR处理
- ✅ 来源追踪:维护所有块的文档名称和页码
- ✅ 添加/删除PDF:轻松管理您的文档收藏
- ✅ 永久存储:ChromaDB将嵌入内容保存到磁盘
- ✅ 多种输出格式:获取Markdown或JSON格式的结果
- ✅ 进度报告:长时间操作期间的实时反馈
建筑
- 嵌入模型:
multi-qa-mpnet-base-dot-v1(针对问答进行了优化) - 向量数据库:具有余弦相似性的ChromaDB
- 分块策略:具有可配置句子分组和重叠的语义组块
- PDF提取:PyMuPDF用于文本提取,OCR回退用于扫描PDF
安装
来源
- 克隆存储库:
git clone
cd pdfrag- 安装软件包:
pip install -e .- 验证安装:
pdfrag --help
pdfrag-cli --helpNLTK数据(自动)
服务器在第一次运行时自动下载所需的NLTK punkt标记器数据。
Tesseract(可选-用于OCR)
如需扫描PDF支持,请安装Tesseract:
- macOS:
brew install tesseract - Ubuntu/Debian:
sudo apt-get install tesseract-ocr - 窗户: 下载自https://github.com/UB-Mannheim/tesseract/wiki
服务器会自动检测扫描的页面,并在Tesseract可用时使用OCR。
配置
数据库位置
服务器将其ChromaDB数据库存储在可配置的位置。您可以使用以下命令指定数据库路径 --db-path 命令行参数:
# Use default location (~/.dotfiles/files/mcps/pdfrag/chroma_db)
pdfrag
# Use custom database location
pdfrag --db-path /path/to/your/database分块参数
默认分块设置:
- 组块大小:每块3个句子
- 重叠:块之间有1个句子重叠
添加PDF时可以自定义这些内容:
{
"pdf_path": "/path/to/document.pdf",
"chunk_size": 5, # Use 5 sentences per chunk
"overlap": 2 # 2 sentences overlap
}字符限制
默认情况下,响应限制为25000个字符。如果超过,结果将自动截断并发出警告 消息。
项目结构
pdfrag/
├── src/pdfrag/ # Main package
│ ├── server.py # FastMCP server with 5 tools
│ ├── database.py # ChromaDB interface
│ ├── embeddings.py # Embedding generation
│ ├── pdf.py # PDF text extraction
│ ├── chunking.py # Semantic chunking
│ └── cli.py # MCP CLI tool
├── tests/ # Test suite
├── docs/ # Documentation
├── examples/ # Configuration examples
└── pyproject.toml # Package configurationMCP工具
1.pdf_add
将PDF文档添加到RAG数据库。
输入:
{
"pdf_path": "/absolute/path/to/document.pdf",
"chunk_size": 3, // optional, default: 3
"overlap": 1 // optional, default: 1
}输出:
{
"status": "success",
"message": "Successfully added 'document.pdf' to the database",
"document_id": "a1b2c3d4...",
"filename": "document.pdf",
"pages": 15,
"chunks": 127,
"chunk_size": 3,
"overlap": 1
}示例用例:
- 添加研究论文以供参考
- 编制文件索引
- 建立可搜索的知识库
2.pdf_remove
从数据库中删除PDF文档。
输入:
{
"document_id": "a1b2c3d4..." // Get from pdf_list
}输出:
{
"status": "success",
"message": "Successfully removed 'document.pdf' from the database",
"document_id": "a1b2c3d4...",
"removed_chunks": 127
}3.pdf列表
列出数据库中的所有PDF文档。
输入:
{
"response_format": "markdown" // or "json"
}输出(Markdown):
# PDF Documents (2 total)
## research_paper.pdf
**Document ID:** a1b2c3d4...
**Chunks:** 127
**Added:** N/A
## documentation.pdf
**Document ID:** e5f6g7h8...
**Chunks:** 89
**Added:** N/A输出(JSON):
{
"count": 2,
"documents": [
{
"document_id": "a1b2c3d4...",
"filename": "research_paper.pdf",
"chunk_count": 127
},
{
"document_id": "e5f6g7h8...",
"filename": "documentation.pdf",
"chunk_count": 89
}
]
}4.pdf_search_相似性
使用语义相似性进行搜索(向量搜索)。
输入:
{
"query": "machine learning techniques for text classification",
"top_k": 5, // optional, default: 5
"document_filter": null, // optional, search specific doc
"response_format": "markdown" // optional, default: markdown
}输出(Markdown):
# Search Results for: 'machine learning techniques for text classification'
Found 5 relevant chunks:
## Result 1
**Document:** research_paper.pdf
**Page:** 7
**Similarity Score:** 0.8754
**Content:**
Machine learning approaches to text classification have evolved significantly...
---使用案例:
- 在没有确切关键字的情况下查找相关信息
- 发现相关概念
- 文件问答
5.pdf_search_keywords
使用关键字匹配进行搜索。
输入:
{
"keywords": "neural network backpropagation",
"top_k": 5, // optional, default: 5
"document_filter": null, // optional
"response_format": "markdown" // optional, default: markdown
}输出: 类似于 pdf_search_similarity,但按关键字出现次数排名。
使用案例:
- 查找特定的技术术语
- 准确定位短语或术语
- 验证文档中是否存在关键字
使用Claude Desktop
1.添加到Claude桌面配置
编辑您的Claude Desktop配置文件:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json 窗户: %APPDATA%\Claude\claude_desktop_config.json
添加服务器:
{
"mcpServers": {
"pdf-rag": {
"command": "pdfrag",
"args": ["--db-path", "/path/to/your/chroma_db"],
"env": {
"PYTHONUNBUFFERED": "1"
}
}
}
}看 examples/claude_desktop_config.json 举一个完整的例子。
2.重新启动克劳德桌面
添加配置后,重新启动Claude Desktop以加载MCP服务器。
3.测试连接
在Claude Desktop中,尝试:
Can you list the PDFs in the RAG database?克劳德将使用 pdf_list 显示可用文档的工具。
示例工作流程
建立研究数据库
1. Add documents:
"Add these PDFs to the database: /research/paper1.pdf, /research/paper2.pdf"
2. Search for concepts:
"Search for information about 'gradient descent optimization' in the database"
3. Find specific terms:
"Search for the keyword 'convolutional neural network' and show me the pages"文件问答
1. Add documentation:
"Add this user manual: /docs/product_manual.pdf"
2. Ask questions:
"How do I configure the network settings according to the manual?"
3. Find references:
"Which page discusses troubleshooting connection errors?"知识库管理
1. List documents:
"Show me all documents in the RAG database"
2. Remove outdated docs:
"Remove the document with ID a1b2c3d4..."
3. Search across all:
"Search all documents for information about API authentication"高级配置
定制块状尺寸
对于不同的文档类型:
技术文档 (代码、API):
- 小块(2-3个句子)
- 最小重叠(0-1个句子)
- 保留代码结构
叙述性文件 (文章、书籍):
- 大块(5-7句)
- 更多重叠(2-3句话)
- 保持上下文流
科学论文:
- 中组块(3-5个句子)
- 中度重叠(1-2句)
- 平衡细节和背景
文档筛选
在特定文档中搜索:
{
"query": "data preprocessing",
"document_filter": "a1b2c3d4..." // Only search this doc
}输出格式选择
根据用例选择格式:
标记语言最适合人类阅读,克劳德的分析 JSON:最适合程序化处理、数据提取
故障排除
“找不到文件”错误
确保您使用的是绝对路径:
"/home/user/documents/paper.pdf" ✅
"~/documents/paper.pdf" ❌ (needs expansion)
"./paper.pdf" ❌ (relative path)空PDF结果/扫描的PDF
服务器使用OCR自动检测和处理扫描的PDF。如果你收到一个关于没有提取文本的错误:
- 安装Tesseract (如果尚未安装):
- macOS: brew install tesseract - Ubuntu/Debian: sudo apt-get install tesseract-ocr - Windows:从下载https://github.com/UB-Mannheim/tesseract/wiki
- 重新尝试添加PDF -服务器将自动对文本最少的页面使用OCR
错误消息将指示是否需要OCR:“确保为扫描的PDF安装了tesseract”
内存不足
如果处理大型PDF会导致内存问题:
- 减少
chunk_size创建更多更小的块 - 一次处理一个文档
- 增加系统交换空间
ChromaDB错误
如果ChromaDB投诉现有收藏:
# Remove the database directory
rm -rf ./chroma_db
# Restart the server性能注意事项
嵌入生成
第一次添加文档时,将下载模型(~400MB)。后续操作更快。
典型时间:
- 10页PDF:约5-10秒
- 100页PDF:约30-60秒
- 1000页PDF:约5-10分钟
搜索性能
- 相似性搜索:快速(大多数查询小于1秒)
- 关键字搜索:大型收藏的速度较慢(与文档数量成比例)
存储
- 嵌入:每块约1.5KB(768个维度向量)
- 文本存储:取决于块大小
- 示例:ChromaDB中1000个块≈1.5MB
最佳实践
1.整理文件
使用描述性文件名:
research_ml_2024.pdf ✅
document (1).pdf ❌2.试块尺寸
不同的文档受益于不同的组块:
# Try multiple chunk sizes for the same document
pdf_add(path="doc.pdf", chunk_size=3, overlap=1) # Test 1
pdf_remove(document_id="...") # Remove
pdf_add(path="doc.pdf", chunk_size=5, overlap=2) # Test 23.使用文档筛选器
搜索特定文档时:
# More focused, faster results
pdf_search_similarity(
query="...",
document_filter="specific_doc_id"
)4.组合搜索类型
使用这两种搜索方法可获得全面的结果:
- 概念的语义搜索
- 关键字搜索精确术语
安全说明
- 文件访问:服务器可以读取Python进程可以访问的任何PDF
- 存储:嵌入和文本以未加密的方式存储在ChromaDB中
- 无身份验证:MCP服务器信任客户端(Claude Desktop)
用于生产用途:
- 限制文件系统权限
- 使用专用数据库目录
- 考虑对敏感文档进行加密
贡献
要扩展此服务器,请执行以下操作:
- 添加新工具:遵循
@mcp.tool()装饰图案 - 定制拼块:实施
semantic_chunking()函数 - 附加嵌入:初始化时交换模型
- 元数据:扩展
metadatasdict inpdf_add()
许可证
MIT许可证-有关详细信息,请参阅许可证文件
致谢
- Anthropic:MCP协议和SDK
- 色度数据库:矢量数据库
- 句子转换器:嵌入模型
- PyMuPDF:PDF文本提取和OCR支持
支持
对于问题或疑问:
- 检查故障排除部分
- 审查MCP文件:https://modelcontextprotocol.io
- 查看ChromaDB文档:https://docs.trychroma.com
______________________________________________________________________
内置于❤️ 使用模型上下文协议
