Skip to main content
Glama

directory_to_pdf

Convert images from a directory into a single PDF document with optional title and file pattern matching.

Instructions

Convert all images in a directory to a PDF document.

Args:
    image_dir: Directory containing images
    output_path: Path for the output PDF file
    title: Optional title for the PDF document
    pattern: File pattern to match (default: all files)

Returns:
    JSON string with conversion results.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
image_dirYes
output_pathYes
titleNo
patternNo*

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • MCP tool handler for 'directory_to_pdf'. This is the primary entry point for the tool, decorated with @mcp.tool(). It resolves the PDFConverter instance and calls its directory_to_pdf method, then returns JSON results.
    @mcp.tool()
    async def directory_to_pdf(
        image_dir: str,
        output_path: str,
        title: Optional[str] = None,
        pattern: str = "*"
    ) -> str:
        """
        Convert all images in a directory to a PDF document.
        
        Args:
            image_dir: Directory containing images
            output_path: Path for the output PDF file
            title: Optional title for the PDF document
            pattern: File pattern to match (default: all files)
        
        Returns:
            JSON string with conversion results.
        """
        try:
            pc = get_pdf_converter()
            pdf_path = pc.directory_to_pdf(
                image_dir=image_dir,
                output_path=output_path,
                pattern=pattern,
                title=title
            )
            
            pdf_info = pc.get_pdf_info(pdf_path)
            
            result = {
                "status": "success",
                "input_directory": image_dir,
                "pattern": pattern,
                "output_pdf": pdf_path,
                "pdf_info": pdf_info
            }
            
            return json.dumps(result, indent=2)
            
        except Exception as e:
            logger.error(f"Failed to convert directory to PDF: {e}")
            return json.dumps({
                "status": "error",
                "error": str(e),
                "input_directory": image_dir,
                "output_pdf": output_path
            })
  • Core helper method in PDFConverter class that implements the directory-to-PDF conversion logic. It discovers image files matching the pattern in the directory, sorts them, and delegates to images_to_pdf for the actual conversion.
    def directory_to_pdf(self, image_dir: str, output_path: str, 
                        pattern: str = "*", title: Optional[str] = None) -> str:
        """
        Convert all images in a directory to PDF.
        
        Args:
            image_dir: Directory containing images
            output_path: Output PDF file path
            pattern: File pattern to match (default: *)
            title: PDF document title (optional)
        
        Returns:
            Path to created PDF file
        """
        try:
            image_paths = []
            
            # Find all image files in directory
            logger.info(f"Searching for images in {image_dir} with pattern '{pattern}'")
            
            # Check if pattern already includes an extension
            if pattern.endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.PNG', '.JPG', '.JPEG', '.BMP', '.TIFF')):
                # Pattern already has extension, use as-is
                image_paths.extend(Path(image_dir).glob(pattern))
                logger.info(f"Using pattern with existing extension: {pattern}")
            else:
                # Pattern doesn't have extension, append supported formats
                for ext in self.supported_formats:
                    glob_pattern = f"{pattern}{ext}"
                    found_files = list(Path(image_dir).glob(glob_pattern))
                    image_paths.extend(found_files)
                    logger.debug(f"Pattern '{glob_pattern}' found {len(found_files)} files")
                    
                    # Also check uppercase extensions
                    glob_pattern_upper = f"{pattern}{ext.upper()}"
                    found_files_upper = list(Path(image_dir).glob(glob_pattern_upper))
                    image_paths.extend(found_files_upper)
                    logger.debug(f"Pattern '{glob_pattern_upper}' found {len(found_files_upper)} files")
            
            image_paths = [str(p) for p in sorted(image_paths)]
            logger.info(f"Total image files found: {len(image_paths)}")
            
            if not image_paths:
                raise ValueError(f"No image files found in {image_dir}")
            
            logger.info(f"Found {len(image_paths)} images in {image_dir}")
            
            return self.images_to_pdf(image_paths, output_path, sort_files=True, title=title)
            
        except Exception as e:
            logger.error(f"Failed to convert directory {image_dir} to PDF: {e}")
            raise
  • server.py:365-365 (registration)
    The @mcp.tool() decorator registers the directory_to_pdf function as an MCP tool. Note: included separately for clarity, but part of the handler block.
    @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 for behavioral disclosure. It states what the tool does but doesn't describe important behavioral aspects: whether it overwrites existing files at output_path, what image formats are supported, error handling for non-image files, memory/performance characteristics, or authentication requirements. The mention of 'JSON string with conversion results' is helpful but insufficient for a mutation tool with zero annotation coverage.

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 perfectly structured and concise. It begins with a clear purpose statement, then provides organized parameter explanations in bullet-point style, and ends with return value information. Every sentence earns its place with no redundant information or unnecessary elaboration.

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 the tool's moderate complexity (directory processing with pattern matching), zero annotation coverage, and the presence of an output schema (implied by 'Returns: JSON string'), the description is minimally adequate. It covers the basic operation and parameters but lacks important context about file system interactions, error conditions, and performance characteristics that would be needed for robust agent usage.

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?

The description provides meaningful semantic context for all 4 parameters beyond what the schema offers (0% coverage). It explains that 'image_dir' contains images to convert, 'output_path' is for the resulting PDF, 'title' is optional for the PDF document, and 'pattern' matches files with a default of 'all files'. This compensates well for the schema's lack of descriptions, though it could provide more detail about pattern syntax and supported image formats.

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

Purpose4/5

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

The description clearly states the tool's purpose with a specific verb ('Convert') and resource ('all images in a directory to a PDF document'). It distinguishes from sibling tools like 'convert_to_pdf' by specifying directory-level conversion rather than individual file conversion. However, it doesn't explicitly differentiate from 'process_images' which might have overlapping functionality.

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 'convert_to_pdf' or 'process_images'. It mentions the basic functionality but offers no context about prerequisites, performance considerations, or scenarios where this tool is preferred over other image/PDF conversion tools in the sibling list.

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