Skip to main content
Glama

convert_to_pdf

Convert multiple image files into a single PDF document with optional title and file sorting.

Instructions

Convert a list of images to a PDF document.

Args:
    image_paths: List of image file paths to convert
    output_path: Path for the output PDF file
    title: Optional title for the PDF document
    sort_files: Whether to sort files by name before conversion

Returns:
    JSON string with conversion results.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
image_pathsYes
output_pathYes
titleNo
sort_filesNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The primary handler for the 'convert_to_pdf' tool, registered via @mcp.tool(). Handles input validation, delegates to PDFConverter for conversion, and returns JSON results.
    @mcp.tool()
    async def convert_to_pdf(
        image_paths: List[str],
        output_path: str,
        title: Optional[str] = None,
        sort_files: bool = True
    ) -> str:
        """
        Convert a list of images to a PDF document.
        
        Args:
            image_paths: List of image file paths to convert
            output_path: Path for the output PDF file
            title: Optional title for the PDF document
            sort_files: Whether to sort files by name before conversion
        
        Returns:
            JSON string with conversion results.
        """
        try:
            # Validate images first
            pc = get_pdf_converter()
            validation = pc.validate_images_for_pdf(image_paths)
            
            if not validation["valid_images"]:
                return json.dumps({
                    "status": "error",
                    "error": "No valid images found for conversion",
                    "validation": validation
                })
            
            # Convert to PDF
            pdf_path = pc.images_to_pdf(
                validation["valid_images"],
                output_path,
                sort_files=sort_files,
                title=title
            )
            
            pdf_info = pc.get_pdf_info(pdf_path)
            
            result = {
                "status": "success",
                "input_images": len(image_paths),
                "valid_images": len(validation["valid_images"]),
                "output_pdf": pdf_path,
                "pdf_info": pdf_info,
                "validation": validation
            }
            
            return json.dumps(result, indent=2)
            
        except Exception as e:
            logger.error(f"Failed to convert to PDF: {e}")
            return json.dumps({
                "status": "error",
                "error": str(e),
                "input_images": len(image_paths) if image_paths else 0,
                "output_pdf": output_path
            })
  • Core helper method implementing the image-to-PDF conversion using img2pdf, filtering and sorting valid images before conversion.
    def images_to_pdf(self, image_paths: List[str], output_path: str, 
                     sort_files: bool = True, title: Optional[str] = None) -> str:
        """
        Convert a list of images to a single PDF document.
        
        Args:
            image_paths: List of image file paths
            output_path: Output PDF file path
            sort_files: Whether to sort files by name
            title: PDF document title (optional)
        
        Returns:
            Path to created PDF file
        """
        try:
            # Filter existing files with supported formats
            valid_images = []
            for path in image_paths:
                if os.path.exists(path):
                    ext = Path(path).suffix.lower()
                    if ext in self.supported_formats:
                        valid_images.append(path)
                    else:
                        logger.warning(f"Unsupported format: {path}")
                else:
                    logger.warning(f"File not found: {path}")
            
            if not valid_images:
                raise ValueError("No valid images found")
            
            # Sort files if requested
            if sort_files:
                valid_images.sort()
            
            logger.info(f"Converting {len(valid_images)} images to PDF")
            
            # Create output directory if needed
            output_dir = os.path.dirname(output_path)
            if output_dir:  # Only create directory if path has a directory component
                os.makedirs(output_dir, exist_ok=True)
            
            # Convert images to PDF
            with open(output_path, "wb") as f:
                f.write(img2pdf.convert(
                    valid_images,
                    title=title or "Auto-Snap Captured Document"
                ))
            
            logger.info(f"PDF created: {output_path}")
            return output_path
            
        except Exception as e:
            logger.error(f"Failed to convert images to PDF: {e}")
            raise
  • Helper method for validating input images before PDF conversion, checks existence, format, and image integrity using PIL.
    def validate_images_for_pdf(self, image_paths: List[str]) -> dict:
        """
        Validate images before PDF conversion.
        
        Args:
            image_paths: List of image file paths
        
        Returns:
            Dictionary with validation results
        """
        results = {
            'valid_images': [],
            'invalid_images': [],
            'missing_files': [],
            'unsupported_formats': [],
            'total_size_mb': 0
        }
        
        for path in image_paths:
            if not os.path.exists(path):
                results['missing_files'].append(path)
                continue
            
            ext = Path(path).suffix.lower()
            if ext not in self.supported_formats:
                results['unsupported_formats'].append(path)
                continue
            
            try:
                # Try to open image to validate
                with Image.open(path) as img:
                    img.verify()
                
                file_size = os.path.getsize(path)
                results['total_size_mb'] += file_size / (1024 * 1024)
                results['valid_images'].append(path)
                
            except Exception as e:
                logger.warning(f"Invalid image {path}: {e}")
                results['invalid_images'].append(path)
        
        results['total_size_mb'] = round(results['total_size_mb'], 2)
        
        logger.info(f"Validation: {len(results['valid_images'])} valid, "
                   f"{len(results['invalid_images'])} invalid, "
                   f"{len(results['missing_files'])} missing, "
                   f"{len(results['unsupported_formats'])} unsupported")
        
        return results
  • Helper method to retrieve metadata about the generated PDF file, such as size and existence.
    def get_pdf_info(self, pdf_path: str) -> dict:
        """
        Get basic information about a PDF file.
        
        Args:
            pdf_path: Path to PDF file
        
        Returns:
            Dictionary with PDF information
        """
        try:
            file_size = os.path.getsize(pdf_path)
            
            info = {
                'path': pdf_path,
                'size_bytes': file_size,
                'size_mb': round(file_size / (1024 * 1024), 2),
                'exists': os.path.exists(pdf_path)
            }
            
            return info
            
        except Exception as e:
            logger.error(f"Failed to get PDF info for {pdf_path}: {e}")
            return {'path': pdf_path, 'error': str(e)}
  • server.py:303-303 (registration)
    The @mcp.tool() decorator registers the convert_to_pdf function as an MCP tool.
    @mcp.tool()
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden but only states basic functionality. It doesn't disclose behavioral traits such as file format support, error handling, permissions needed, whether it overwrites existing files, or performance considerations. This is inadequate for a tool with 4 parameters and file operations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is front-loaded with the core purpose, followed by a structured Args/Returns section. Every sentence adds value—no fluff or repetition. It's appropriately sized for the tool's complexity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given 4 parameters, no annotations, and an output schema (which covers return values), the description is partially complete. It explains parameters well but lacks behavioral context (e.g., side effects, error cases). The output schema reduces need for return details, but gaps remain in usage and transparency.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It adds meaningful context for all 4 parameters: 'image_paths' as list of file paths, 'output_path' for the PDF, 'title' as optional, and 'sort_files' for ordering. This goes beyond the bare schema, though it lacks format details (e.g., image types).

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Convert a list of images to a PDF document'), identifies the resource ('images'), and distinguishes from siblings like 'directory_to_pdf' (which processes directories) or 'process_images' (which might not output PDFs). The verb 'convert' is precise and the scope is well-defined.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives like 'directory_to_pdf' (for directories) or 'full_document_workflow' (which might include conversion). It lacks explicit when/when-not instructions or named alternatives, leaving usage context implied at best.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/PovedaAqui/auto-snap-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server