wesleygriffin/pdfrag

GitHub: wesleygriffin/pdfrag

一个基于 MCP 协议的 PDF 文档 RAG 服务器,提供语义分块、向量检索与关键词搜索功能,支持 AI 助手对 PDF 知识库进行精准问答。

Stars: 5 | Forks: 1

# PDF RAG MCP Server 一个为 PDF 文档提供强大 RAG(Retrieval-Augmented Generation,检索增强生成)能力的 Model Context Protocol (MCP) 服务器。该服务器使用 ChromaDB 进行向量存储,使用 sentence-transformers 生成 embeddings,并采用语义分块进行智能文本分割。 ## 功能 - ✅ **语义分块**:智能地将句子组合在一起,而不是在任意的字符限制处进行拆分 - ✅ **向量搜索**:使用 embeddings 查找语义相似的内容 - ✅ **关键词搜索**:传统的基于关键词的搜索,用于精确匹配术语 - ✅ **OCR 支持**:自动检测并对扫描件/基于图像的 PDF 进行 OCR 处理 - ✅ **来源跟踪**:为所有分块保留文档名称和页码 - ✅ **添加/删除 PDF**:轻松管理您的文档集合 - ✅ **持久化存储**:ChromaDB 将您的 embeddings 持久化到磁盘 - ✅ **多种输出格式**:获取 Markdown 或 JSON 格式的结果 - ✅ **进度报告**:在长时间操作期间提供实时反馈 ## 架构 - **Embedding 模型**:`multi-qa-mpnet-base-dot-v1`(针对问答进行了优化) - **向量数据库**:使用余弦相似度的 ChromaDB - **分块策略**:具有可配置句子分组和重叠的语义分块 - **PDF 提取**:使用 PyMuPDF 提取文本,并为扫描版 PDF 提供 OCR 回退机制 ## 安装 ### 从源码安装 1. 克隆仓库: ``` git clone cd pdfrag ``` 2. 安装包: ``` pip install -e . ``` 3. 验证安装: ``` pdfrag --help pdfrag-cli --help ``` ### NLTK 数据(自动) 服务器会在首次运行时自动下载所需的 NLTK punkt tokenizer 数据。 ### Tesseract(可选 - 用于 OCR) 如需支持扫描版 PDF,请安装 Tesseract: - **macOS:** `brew install tesseract` - **Ubuntu/Debian:** `sudo apt-get install tesseract-ocr` - **Windows:** 从 https://github.com/UB-Mannheim/tesseract/wiki 下载 当 Tesseract 可用时,服务器会自动检测扫描页面并使用 OCR。 ## 配置 ### 数据库位置 服务器将其 ChromaDB 数据库存储在可配置的位置。您可以使用 `--db-path` 命令行参数指定数据库路径: ``` # 使用默认位置 (~/.dotfiles/files/mcps/pdfrag/chroma_db) pdfrag # 使用自定义数据库位置 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 } ``` ### 字符限制 默认情况下,响应限制为 25,000 个字符。如果超出限制,结果将自动截断并显示警告消息。 ## 项目结构 ``` 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 configuration ``` ## MCP 工具 ### 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_list 列出数据库中的所有 PDF 文档。 **输入:** ``` { "response_format": "markdown" // or "json" } ``` **输出:** ``` # PDF 文档(共 2 个) ## research_paper.pdf **Document ID:** a1b2c3d4... **Chunks:** 127 **Added:** N/A ## documentation.pdf **Document ID:** e5f6g7h8... **Chunks:** 89 **Added:** N/A ``` **输出:** ``` { "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_similarity 使用语义相似度进行搜索(向量搜索)。 **输入:** ``` { "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 } ``` **输出:** ``` # 搜索结果:'machine learning techniques for text classification' Found 5 relevant chunks: ## 结果 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 Desktop 配置 编辑您的 Claude Desktop 配置文件: **macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json` **Windows:** `%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 添加配置后,重启 Claude Desktop 以加载 MCP 服务器。 ### 3. 测试连接 在 Claude Desktop 中,尝试: ``` Can you list the PDFs in the RAG database? ``` Claude 将使用 `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 } ``` ### 输出格式选择 根据用例选择格式: **Markdown**:最适合人类阅读和 Claude 的分析 **JSON**:最适合程序化处理和数据提取 ## 故障排除 ### “File not found”错误 确保您使用的是绝对路径: ``` "/home/user/documents/paper.pdf" ✅ "~/documents/paper.pdf" ❌ (needs expansion) "./paper.pdf" ❌ (relative path) ``` ### PDF 结果为空 / 扫描版 PDF 服务器会自动检测并使用 OCR 处理扫描版 PDF。如果出现有关未提取出任何文本的错误: 1. **安装 Tesseract**(如果尚未安装): - macOS: `brew install tesseract` - Ubuntu/Debian: `sudo apt-get install tesseract-ocr` - Windows: 从 https://github.com/UB-Mannheim/tesseract/wiki 下载 2. **重新尝试添加 PDF** - 对于文本极少的页面,服务器将自动使用 OCR 错误消息会提示是否需要 OCR:“ensure tesseract is installed for scanned PDFs” ### 内存不足 如果处理大型 PDF 导致内存问题: 1. 减小 `chunk_size` 以创建更多、更小的分块 2. 一次只处理一个文档 3. 增加系统交换空间 ### ChromaDB 错误 如果 ChromaDB 提示已存在集合(collections)的问题: ``` # 删除数据库目录 rm -rf ./chroma_db # 重启服务器 ``` ## 性能考量 ### Embedding 生成 首次添加文档时,将下载模型(约 400MB)。随后的操作会更快。 **典型耗时:** - 10 页 PDF:约 5-10 秒 - 100 页 PDF:约 30-60 秒 - 1000 页 PDF:约 5-10 分钟 ### 搜索性能 - **相似度搜索**:速度快(大多数查询不到 1 秒) - **关键词搜索**:对于大型集合较慢(随文档数量增加而变慢) ### 存储 - **Embeddings**:每个分块约 1.5KB(768 维向量) - **文本存储**:取决于分块大小 - **示例**:1000 个分块在 ChromaDB 中约占 1.5MB ## 最佳实践 ### 1. 整理文档 使用描述性的文件名: ``` research_ml_2024.pdf ✅ document (1).pdf ❌ ``` ### 2. 测试分块大小 不同的文档受益于不同的分块方式: ``` # 为同一文档尝试多种 chunk 大小 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 2 ``` ### 3. 使用文档过滤器 搜索特定文档时: ``` # 更专注、更快速的结果 pdf_search_similarity( query="...", document_filter="specific_doc_id" ) ``` ### 4. 结合搜索类型 同时使用两种搜索方法以获得全面的结果: 1. 使用语义搜索查找概念 2. 使用关键词搜索查找精确术语 ## 安全说明 - **文件访问**:服务器可以读取 Python 进程有权访问的任何 PDF - **存储**:Embeddings 和文本在 ChromaDB 中以未加密形式存储 - **无身份验证**:MCP 服务器信任客户端(Claude Desktop) 在生产环境中使用时: - 限制文件系统权限 - 使用专用的数据库目录 - 考虑对敏感文档进行加密 ## 贡献 如需扩展此服务器: 1. **添加新工具**:遵循 `@mcp.tool()` 装饰器模式 2. **自定义分块**:在 `semantic_chunking()` 函数中实现 3. **其他 Embeddings**:在初始化时替换模型 4. **元数据**:在 `pdf_add()` 中扩展 `metadatas` 字典 ## 许可证 MIT 许可证 - 详情请参阅 LICENSE 文件 ## 鸣谢 - **Anthropic**:MCP 协议和 SDK - **ChromaDB**:向量数据库 - **Sentence Transformers**:Embedding 模型 - **PyMuPDF**:PDF 文本提取和 OCR 支持 ## 支持 如有问题或疑问: 1. 查看故障排除部分 2. 查看 MCP 文档: 3. 查看 ChromaDB 文档: **使用 Model Context Protocol 搭建 ❤️**
标签:AI, MCP, PDF处理, RAG, 向量数据库, 文本检索, 自动化代码审查, 逆向工具