npm package: @hole-foundation/mcp-server-pdf
Description: MCP server for PDF processing with Ghostscript - merge, split, and optimize PDFs for legal exhibits
Latest version: 0.1.0

# MCP PDF Server - Ghostscript-based PDF Processing

A production-grade MCP (Model Context Protocol) server for advanced PDF processing using Ghostscript. Designed for legal document management with tools for merging, splitting, optimizing, and compressing PDFs into exhibit-ready formats.

**Made by** [The HOLE Foundation](https://theholefoundation.org)

## Features

✨ **PDF Optimization** - Reduce file size while maintaining quality
📄 **Merge PDFs** - Combine multiple documents with optional bookmarking
✂️ **Split PDFs** - Extract individual pages or page ranges with custom naming
🔐 **Compression** - Aggressive compression optimized for legal filing (150 DPI)
⚡ **Fast Processing** - Leverages Ghostscript for high-performance operations
📊 **Legal-Ready Output** - Meets document exhibit requirements

## Installation

### Prerequisites

- Node.js 18+
- Ghostscript installed and available in PATH

#### Install Ghostscript

**macOS** (with Homebrew):
```bash
brew install ghostscript
```

**Linux** (Debian/Ubuntu):
```bash
sudo apt-get install ghostscript
```

**Linux** (RedHat/CentOS):
```bash
sudo yum install ghostscript
```

**Windows**:
Download from [ghostscript.com](https://www.ghostscript.com/download/gsdnld.html)

### Install MCP PDF Server

Via npm:
```bash
npm install @hole-foundation/mcp-pdf-server
```

Or globally:
```bash
npm install -g @hole-foundation/mcp-pdf-server
```

## Quick Start

### As an MCP Server (for Claude, IDE integrations)

Configure in your Claude Code settings or IDE:

```json
{
  "mcp-pdf-server": {
    "command": "mcp-pdf-server",
    "args": ["server"]
  }
}
```

### Command Line

#### Optimize a PDF

```bash
mcp-pdf-server optimize input.pdf output.pdf --compression medium
```

Options:
- `--compression low|medium|high` - Compression intensity (default: medium)
- `--preserve-images` - Keep original image quality

#### Merge PDFs

```bash
mcp-pdf-server merge combined.pdf doc1.pdf doc2.pdf doc3.pdf --bookmarks
```

Options:
- `--bookmarks` - Create bookmarks for each merged document

#### Split PDF

```bash
# Extract all pages individually
mcp-pdf-server split document.pdf ./pages

# Extract specific page ranges
mcp-pdf-server split document.pdf ./pages --range 1-5,10-15

# Custom output pattern
mcp-pdf-server split document.pdf ./pages --all --pattern "doc_%03d.pdf"
```

Options:
- `--range <range>` - Page range (e.g., "1-5,7,10-15") - if not specified, extracts all
- `--pattern <pattern>` - Output filename pattern (default: page_%03d.pdf)

#### Compress PDF

```bash
mcp-pdf-server compress input.pdf output.pdf --dpi 150 --quality medium
```

Options:
- `--dpi <number>` - Target DPI for images (default: 150, minimum: 72)
- `--quality low|medium|high` - Compression quality (default: medium)
- `--keep-metadata` - Preserve PDF metadata (removed by default)

## API Usage (Programmatic)

```typescript
import {
  optimizePDF,
  mergePDFs,
  splitPDF,
  compressPDF,
} from '@hole-foundation/mcp-pdf-server';

// Optimize a PDF
const result = await optimizePDF('input.pdf', 'output.pdf', {
  compressionLevel: 'high',
  preserveImages: false,
});

// Merge PDFs
const merged = await mergePDFs(
  ['doc1.pdf', 'doc2.pdf', 'doc3.pdf'],
  'combined.pdf',
  { bookmarkPages: true }
);

// Split PDF
const split = await splitPDF('document.pdf', './pages', {
  splitType: 'range',
  pageRange: '1-5,10-15',
  outputPattern: 'page_%03d.pdf',
});

// Compress for legal filing
const compressed = await compressPDF('input.pdf', 'output.pdf', {
  targetDpi: 150,
  removeMetadata: true,
  quality: 'medium',
});
```

## Configuration

### Environment Variables

```bash
# Path to Ghostscript binary (auto-detected if not set)
GHOSTSCRIPT_PATH=/usr/bin/gs

# Maximum file size allowed (bytes)
MAX_FILE_SIZE=500000000

# Temporary directory for processing
TEMP_DIR=/tmp

# Debug mode
DEBUG=false
```

### dotenvx Integration

This server integrates with [dotenvx](https://dotenvx.sh) for secrets management. Add to `.env.enc`:

```
GHOSTSCRIPT_API_KEY=your_key_here
```

Load with:
```bash
dotenvx run -- mcp-pdf-server server
```

## MCP Tools

### Tool: `optimize_pdf`

Optimize a PDF for size and quality, suitable for legal exhibits.

**Parameters:**
- `input_path` (string, required) - Path to PDF file
- `output_path` (string, required) - Output path for optimized PDF
- `compression_level` (string, default: "medium") - low|medium|high
- `preserve_images` (boolean, default: false) - Keep original image quality

**Returns:** Operation result with file sizes and compression ratio

### Tool: `merge_pdfs`

Merge multiple PDF files into a single document.

**Parameters:**
- `input_paths` (array, required) - Array of PDF file paths
- `output_path` (string, required) - Output path for merged PDF
- `bookmark_pages` (boolean, default: false) - Create bookmarks

**Returns:** Operation result with merged file info

### Tool: `split_pdf`

Split a PDF into separate documents by page or range.

**Parameters:**
- `input_path` (string, required) - Path to PDF file
- `output_dir` (string, required) - Directory for split files
- `split_type` (string, default: "all") - all|range
- `page_range` (string) - Page range for split_type=range
- `output_pattern` (string) - Filename pattern

**Returns:** Array of output files with operation details

### Tool: `compress_pdf`

Aggressively compress PDF for legal filing requirements.

**Parameters:**
- `input_path` (string, required) - Path to PDF file
- `output_path` (string, required) - Output path
- `target_dpi` (number, default: 150) - Target DPI (min: 72)
- `remove_metadata` (boolean, default: true) - Remove metadata
- `quality` (string) - low|medium|high

**Returns:** Compression result with ratio and file sizes

## Legal Document Guidelines

For legal documents and court filings:

1. **DPI Settings**: Use 150 DPI for text-heavy documents, 200 DPI for scans
2. **Compression**: Use "medium" or "high" for filing, "low" for archival
3. **Metadata Removal**: Enable by default for privacy (unless e-discovery needed)
4. **File Size Limits**: Most court systems accept up to 50MB; this server maintains exhibits under 20MB
5. **Quality Preservation**: Text remains OCR-readable at 72+ DPI

## Performance

- **Merge**: ~100 pages/sec
- **Split**: ~200 pages/sec
- **Optimize**: ~50 pages/sec
- **Compress**: ~30 pages/sec

Actual performance varies based on PDF complexity and system resources.

## Docker / Cloudflare Containers

Build and deploy:

```bash
# Build Docker image
docker build -t mcp-pdf-server .

# Run locally
docker run -p 3000:3000 mcp-pdf-server

# Deploy to Cloudflare Containers
wrangler deploy
```

See [DEPLOYMENT.md](./docs/DEPLOYMENT.md) for detailed Cloudflare Containers setup.

## Testing

```bash
# Run all tests
npm test

# Run with coverage
npm run test:coverage

# Run specific test suite
npm run test:unit
npm run test:integration
npm run test:e2e
```

## Contributing

We welcome contributions! Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.

## Security

- Input validation on all file paths
- Runs in isolated Ghostscript process
- Temporary files cleaned up automatically
- Non-root user in Docker
- No external network calls

For security concerns, see [SECURITY.md](./SECURITY.md)

## Troubleshooting

### "Ghostscript not found"

Ensure Ghostscript is installed and in your PATH:
```bash
which gs
```

### "Permission denied" errors

Ensure the output directory is writable:
```bash
chmod 755 /output/directory
```

### Large file processing

For files >100MB, consider splitting first or increasing system memory:
```bash
mcp-pdf-server split huge.pdf ./parts --range 1-50
mcp-pdf-server split huge.pdf ./parts --range 51-100
```

## License

MIT - See [LICENSE](./LICENSE) for details

## Support

- GitHub Issues: [Report bugs](https://github.com/The-HOLE-Foundation/mcp-server-pdf/issues)
- Documentation: [Full docs](./docs/README.md)
- HOLE Foundation: [theholefoundation.org](https://theholefoundation.org)

## Acknowledgments

Built on top of:
- [Ghostscript](https://www.ghostscript.com/) - PDF rendering engine
- [Model Context Protocol](https://modelcontextprotocol.io/) - MCP specification
- [The HOLE Foundation](https://theholefoundation.org) - Transparency & FOIA tools

---

**Made with ❤️ for legal transparency and document access**