pdf_merge_files
Combine multiple PDF documents into a single file for easier organization and sharing.
Instructions
Merge multiple PDF files into one combined PDF.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| pdf_paths | Yes | ||
| output_path | No |
Implementation Reference
- The core handler function for the 'pdf_merge_files' tool. It validates input PDF files, merges them using PyMuPDF's fitz library by creating a new document and inserting pages from each input PDF, generates an output filename if not provided, and saves the merged PDF. The @mcp.tool() decorator registers it with FastMCP.@mcp.tool() async def pdf_merge_files( pdf_paths: List[str], output_path: Optional[str] = None ) -> str: """Merge multiple PDF files into one combined PDF.""" # Validate all PDF files for pdf_path in pdf_paths: if not os.path.exists(pdf_path): return f"Error: PDF file not found: {pdf_path}" if not validate_pdf_file(pdf_path): return f"Error: Invalid PDF file: {pdf_path}" try: # Create new document for merging merged_doc = fitz.open() # Merge all PDFs for pdf_path in pdf_paths: doc = fitz.open(pdf_path) merged_doc.insert_pdf(doc) doc.close() # Determine output path if not output_path: output_path = generate_output_filename(pdf_paths[0], "merged") # Save merged PDF merged_doc.save(output_path) merged_doc.close() return f"Successfully merged {len(pdf_paths)} PDFs. Output saved to: {output_path}" except Exception as e: return f"Error merging PDFs: {str(e)}"
- Utility function used by pdf_merge_files (and other tools) to check if a given file path points to a valid PDF by attempting to open it with fitz.def validate_pdf_file(pdf_path: str) -> bool: """Validate that the file is a valid PDF.""" try: doc = fitz.open(pdf_path) doc.close() return True except Exception: return False
- Utility function used by pdf_merge_files to generate a timestamped output filename based on the first input PDF path to prevent overwriting original files.def generate_output_filename(input_path: str, suffix: str = "modified") -> str: """Generate a new filename with timestamp to avoid overwriting originals.""" path = Path(input_path) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") return str(path.parent / f"{path.stem}_{suffix}_{timestamp}{path.suffix}")