Spaces:
Running on Zero
Running on Zero
A newer version of the Gradio SDK is available: 6.20.0
metadata
title: PDF Parser MCP Server
emoji: ๐
colorFrom: blue
colorTo: purple
sdk: gradio
sdk_version: 4.44.0
app_file: main.py
pinned: false
PDF Parser MCP Server
A FastAPI-based PDF processing system with MCP (Model Context Protocol) integration for Claude Desktop. Upload PDFs, extract text, generate AI summaries, and interact with documents through Claude Desktop.
๐ Quick Start
๐ For detailed setup instructions, see SETUP.md
1. Install Dependencies
# Create virtual environment
uv venv
source .venv/bin/activate # Unix
# or .venv\Scripts\activate # Windows
# Install all dependencies
uv sync
uv pip install torch torchvision transformers docling-core pdf2image pillow
2. Setup Environment
# Create .env file
touch .env # Create manually on Windows
# Add your Anthropic API key to .env
ANTHROPIC_API_KEY=your_actual_api_key_here
MAX_TOKENS=180000
CHUNK_SIZE=8000
3. Start the System
# Start FastAPI server with auto-reload
uvicorn main:app --reload --host 0.0.0.0 --port 8000
# Test the system
python test_smoldocling.py
4. Configure MCP Server
# Start MCP server (separate terminal)
python mcp_main.py
4. Configure Claude Desktop
Open Claude Desktop configuration:
- Windows:
%APPDATA%\Claude\claude_desktop_config.json - macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Linux:
~/.config/claude/claude_desktop_config.json
- Windows:
Add the server configuration:
{
"mcpServers": {
"pdf-parser": {
"command": "uv",
"args": ["--directory", "/path/to/your/pdf-parser", "run", "mcp_main.py"],
"cwd": "/path/to/your/pdf-parser"
}
}
}
- Update the paths to match your project location
- Restart Claude Desktop
5. Upload and Process PDFs
# Upload a PDF
curl -X POST "http://localhost:8000/upload-pdf/" -F "file=@your_document.pdf"
# Check status
curl "http://localhost:8000/status/{file_id}"
# List documents
curl "http://localhost:8000/documents/"
6. Use with Claude Desktop
Once configured, you can interact with your PDFs through Claude Desktop:
You: "List all my documents"
Claude: [Shows all processed PDFs with IDs and status]
You: "What is the summary of document abc-123?"
Claude: [Provides detailed summary of the document]
You: "Search for 'financial projections' in all documents"
Claude: [Searches and shows relevant sections]
You: "What are the key findings in document xyz-456?"
Claude: [Analyzes and provides key insights]
๐ง System Architecture
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ Claude โ โ MCP Server โ โ FastAPI โ
โ Desktop โโโโโโค (@mcp.tool) โโโโโโค Server โ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ โ
โ โ
โผ โผ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ Document โ โ SmolDocling โ
โ Storage โ โ + PyMuPDF โ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ โ
โ โ
โผ โผ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ Anthropic โ โ Smart โ
โ Claude API โ โ Chunking โ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
๐ Complete Workflow Pipeline
Visual Overview
graph TD
A["๐ PDF Upload"] --> B["๐ File Validation"]
B --> C["๐พ Save to uploads/"]
C --> D["๐ Background Processing"]
D --> E["๐ผ๏ธ PDF โ Images<br/>(pdf2image)"]
E --> F["๐ค SmolDocling Processing<br/>(Vision-Language Model)"]
F --> G["๐ DocTags Generation<br/>(Layout + Structure)"]
G --> H["โ๏ธ Text Extraction<br/>(Markdown Format)"]
H --> I["๐งฎ Token Analysis<br/>(tiktoken)"]
I --> J["๐ฆ Smart Chunking<br/>(8K tokens max)"]
J --> K["๐ฏ Claude 3.5 Sonnet<br/>(Summarization)"]
K --> L["๐พ Storage.json<br/>(Document + Chunks + Summary)"]
L --> M["๐ MCP Server Update"]
M --> N["๐ฅ๏ธ Claude Desktop<br/>(Tools Available)"]
N --> O["๐ฌ User Queries"]
O --> P["๐ ๏ธ MCP Tools<br/>(list, search, summarize)"]
P --> Q["๐ฏ Intelligent Responses"]
%% Fallback path
F -.->|"๐ Fallback"| R["๐ PyMuPDF<br/>(Traditional OCR)"]
R -.-> H
Phase 1: Document Upload & Initial Processing
๐ PDF Upload (FastAPI)
โ
๐ File Validation (.pdf extension)
โ
๐พ Save to uploads/ directory with UUID
โ
๐ Background Processing Initiated
Phase 2: Advanced Text Extraction (SmolDocling)
๐ PDF File
โ
๐ผ๏ธ PDF โ Images (pdf2image)
โ โโโ Page 1.png
โ โโโ Page 2.png
โ โโโ Page N.png
โ
๐ค SmolDocling Processing (per page)
โ โโโ Vision-Language Model Analysis
โ โโโ Document Structure Recognition
โ โโโ Table/Code/Formula Detection
โ โโโ DocTags Generation
โ
๐ DocTags โ Structured Text
โ โโโ Layout Preservation
โ โโโ Hierarchy Maintenance
โ โโโ Content Organization
โ
๐ Consolidated Text Output
โโโ Page 1 Content
โโโ Page 2 Content
โโโ Page N Content
๐ FALLBACK: If SmolDocling fails โ PyMuPDF extraction
Phase 3: Intelligent Chunking
๐ Complete Document Text
โ
๐งฎ Token Analysis (tiktoken)
โ โโโ Total token count calculation
โ โโโ Per-page token assessment
โ โโโ Chunking strategy determination
โ
โ๏ธ Smart Chunking Process
โ โโโ Respect page boundaries
โ โโโ Split oversized pages intelligently
โ โโโ Maintain context windows
โ โโโ Preserve document structure
โ
๐ฆ Chunk Generation
โ โโโ Chunk 1 (8K tokens max)
โ โโโ Chunk 2 (8K tokens max)
โ โโโ Chunk N (remaining content)
โ
๐พ Store chunks with metadata
Phase 4: AI-Powered Summarization
๐ฆ Document Chunks
โ
๐ฏ Summarization Strategy Selection
โโโ Single Chunk โ Direct summarization
โโโ Multiple Chunks โ Hierarchical approach
โ
๐ค Claude 3.5 Sonnet Processing
โ โโโ Individual chunk summaries
โ โโโ Cross-chunk analysis
โ โโโ Overall document synthesis
โ โโโ Key insights extraction
โ
๐ Summary Generation
โ โโโ Overall summary
โ โโโ Per-chunk summaries
โ โโโ Key findings
โ โโโ Important details
Phase 5: Storage & Indexing
๐ Processed Document Data
โ
๐พ Storage.json Update
โ โโโ Document metadata
โ โโโ Extracted text
โ โโโ Chunk information
โ โโโ Summary data
โ โโโ Processing timestamps
โ
๐ MCP Server Synchronization
โ โโโ Update document registry
โ โโโ Enable Claude Desktop access
โ โโโ Prepare for querying
โ
โ
Processing Complete
Phase 6: Query & Interaction (Claude Desktop)
๐ฌ User Query (Claude Desktop)
โ
๐ ๏ธ MCP Tool Selection
โ โโโ list_documents()
โ โโโ get_document_summary()
โ โโโ get_document_content()
โ โโโ search_documents()
โ โโโ answer_question()
โ
๐ Data Retrieval
โ โโโ Document lookup
โ โโโ Content extraction
โ โโโ Context preparation
โ โโโ Response formatting
โ
๐ฏ Intelligent Response
โ โโโ Contextual answers
โ โโโ Document citations
โ โโโ Relevant excerpts
โ โโโ Follow-up suggestions
๐ฏ Key Processing Features
SmolDocling Advantages
- ๐ง Intelligent OCR: Understands document layout and structure
- ๐ Table Recognition: Preserves table formatting and relationships
- ๐ป Code Detection: Maintains code block formatting and syntax
- ๐ข Formula Processing: Handles mathematical expressions correctly
- ๐ Layout Awareness: Preserves document hierarchy and spacing
- ๐ผ๏ธ Figure Classification: Identifies and categorizes visual elements
Robust Error Handling
- ๐ Automatic Fallback: SmolDocling โ PyMuPDF if needed
- โก Performance Optimization: GPU acceleration when available
- ๐พ Memory Management: Efficient processing for large documents
- ๐ก๏ธ Error Recovery: Graceful handling of processing failures
Scalability Features
- ๐ Background Processing: Non-blocking document processing
- ๐ฆ Efficient Chunking: Token-aware content splitting
- ๐ Fast Search: Optimized text search across documents
- ๐จ Quick Retrieval: Instant access to processed content
๐ Features
- Multi-page PDF Support: Handle 70-80+ page documents
- Advanced Text Extraction: Uses SmolDocling (256M parameter vision-language model) for intelligent document understanding with PyMuPDF fallback
- Layout-Aware Processing: Preserves document structure, tables, code blocks, formulas, and formatting
- AI Summarization: Claude 3.5 Sonnet generates comprehensive summaries
- Token-aware Chunking: Automatically splits large documents respecting token limits
- MCP Integration: Seamless Claude Desktop integration with @mcp.tool() decorators
- Background Processing: Asynchronous PDF processing
- Search & Query: Full-text search across all documents
- RESTful API: Complete REST API for programmatic access
๐ค SmolDocling Integration
This project now uses SmolDocling, a compact 256M parameter vision-language model for advanced document understanding:
Why SmolDocling?
- Better Text Recognition: Understands document layout, tables, code blocks, and mathematical formulas
- Structure Preservation: Maintains document hierarchy and formatting
- Compact Model: Only 256M parameters, efficient for local processing
- Multi-Modal: Processes documents as images for better OCR accuracy
How It Works
- PDF to Images: Converts PDF pages to images using pdf2image
- SmolDocling Processing: Each page is processed by the vision-language model
- DocTags Generation: Creates structured markup preserving layout and content
- Text Extraction: Converts DocTags to clean text for further processing
- Fallback: Automatically falls back to PyMuPDF if SmolDocling fails
Requirements
- GPU Recommended: CUDA-compatible GPU for optimal performance
- CPU Fallback: Works on CPU but slower processing
- Memory: ~2GB GPU memory or 4GB RAM for CPU processing
๐ ๏ธ MCP Tools Available in Claude Desktop
| Tool | Description | Usage |
|---|---|---|
list_documents |
List all processed PDFs | "List my documents" |
get_document_summary |
Get AI-generated summary | "Summarize document abc-123" |
get_document_content |
Get full or chunked content | "Show content of document xyz-456" |
search_documents |
Search across all documents | "Search for 'budget' in all docs" |
get_document_metadata |
Get document metadata | "Show metadata for document abc-123" |
answer_question |
Answer questions about documents | "What are the main conclusions?" |
๐ Technical Details
PDF Processing
- Library: PyMuPDF (fitz) for robust text extraction
- Multi-page: Handles documents with 70-80+ pages efficiently
- Structure: Preserves page boundaries and formatting
Text Chunking
- Token Counting: Uses tiktoken for accurate token counting
- Smart Splitting: Respects page boundaries when possible
- Large Page Handling: Splits oversized pages intelligently
- Token Limits: Configurable limits (default: 180k tokens)
AI Integration
- Model: Claude 3.5 Sonnet (claude-3-5-sonnet-20241022)
- Hierarchical Summarization: Multi-level summaries for large documents
- Context-aware: Maintains context across chunks
๐ Project Structure
pdf-parser/
โโโ main.py # FastAPI server (uvicorn main:app --reload)
โโโ mcp_main.py # MCP server entry point (uv run mcp install)
โโโ mcp_server.py # MCP server with @mcp.tool() decorators
โโโ pdf_processor.py # PDF text extraction & chunking
โโโ anthropic_client.py # Anthropic API integration
โโโ pyproject.toml # Project dependencies & MCP config
โโโ .env.example # Environment variables template
โโโ dev_commands.md # Development commands reference
โโโ claude_desktop_config.json # Claude Desktop configuration
โโโ start_system.py # System setup helper (optional)
โโโ README.md # This file
๐จ Troubleshooting
Common Issues
- Import Errors: Run
uv syncto install dependencies - API Key Missing: Add
ANTHROPIC_API_KEYto.envfile - MCP Connection: Check Claude Desktop configuration path
- File Upload: Ensure sufficient disk space and permissions
Debug Steps
# Check system status
python start_system.py
# Test API endpoint
curl http://localhost:8000/health
# Check MCP server
python start_system.py mcp
๐ License
MIT License - See LICENSE file for details.
๐ค Contributing
- Fork the repository
- Create your feature branch
- Commit your changes
- Push to the branch
- Create a Pull Request
Ready to process your PDFs with AI power! ๐