Skip to main content
Glama
andr3medeiros

PDF Manipulation MCP Server

pdf_extract_images

Extract all images from PDF files for reuse in other documents or projects. Specify the PDF path and optional output directory to save images.

Instructions

Extract all images from a PDF.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pdf_pathYes
output_dirNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The core handler function decorated with @mcp.tool(), which both defines the tool logic and registers it with the FastMCP server. It extracts all images from each page of the input PDF using PyMuPDF, saves them as PNG files in a specified or auto-generated output directory, and returns the paths.
    @mcp.tool()
    async def pdf_extract_images(
        pdf_path: str,
        output_dir: Optional[str] = None
    ) -> str:
        """Extract all images from a PDF."""
        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:
            # Open PDF document
            doc = fitz.open(pdf_path)
            
            # Determine output directory
            if not output_dir:
                pdf_file = Path(pdf_path)
                output_dir = str(pdf_file.parent / f"{pdf_file.stem}_images")
            
            # Create output directory if it doesn't exist
            os.makedirs(output_dir, exist_ok=True)
            
            extracted_images = []
            
            # Extract images from each page
            for page_num in range(len(doc)):
                page = doc[page_num]
                image_list = page.get_images()
                
                for img_index, img in enumerate(image_list):
                    # Get image data
                    xref = img[0]
                    pix = fitz.Pixmap(doc, xref)
                    
                    # Skip if image is too small or invalid
                    if pix.n - pix.alpha < 4:  # GRAY or RGB
                        img_name = f"page_{page_num + 1}_img_{img_index + 1}.png"
                        img_path = os.path.join(output_dir, img_name)
                        pix.save(img_path)
                        extracted_images.append(img_path)
                    
                    pix = None  # Free memory
            
            doc.close()
            
            if not extracted_images:
                return "No images found in the PDF."
            
            return f"Successfully extracted {len(extracted_images)} images to: {output_dir}\nImages: {', '.join(extracted_images)}"
            
        except Exception as e:
            return f"Error extracting images from PDF: {str(e)}"
  • Helper function used by pdf_extract_images to validate that the input file is a valid PDF before processing.
    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
  • The @mcp.tool() decorator registers the function as an MCP tool with the FastMCP server instance.
    @mcp.tool()
    async def pdf_extract_images(
        pdf_path: str,
        output_dir: Optional[str] = None
    ) -> str:
        """Extract all images from a PDF."""
        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:
            # Open PDF document
            doc = fitz.open(pdf_path)
            
            # Determine output directory
            if not output_dir:
                pdf_file = Path(pdf_path)
                output_dir = str(pdf_file.parent / f"{pdf_file.stem}_images")
            
            # Create output directory if it doesn't exist
            os.makedirs(output_dir, exist_ok=True)
            
            extracted_images = []
            
            # Extract images from each page
            for page_num in range(len(doc)):
                page = doc[page_num]
                image_list = page.get_images()
                
                for img_index, img in enumerate(image_list):
                    # Get image data
                    xref = img[0]
                    pix = fitz.Pixmap(doc, xref)
                    
                    # Skip if image is too small or invalid
                    if pix.n - pix.alpha < 4:  # GRAY or RGB
                        img_name = f"page_{page_num + 1}_img_{img_index + 1}.png"
                        img_path = os.path.join(output_dir, img_name)
                        pix.save(img_path)
                        extracted_images.append(img_path)
                    
                    pix = None  # Free memory
            
            doc.close()
            
            if not extracted_images:
                return "No images found in the PDF."
            
            return f"Successfully extracted {len(extracted_images)} images to: {output_dir}\nImages: {', '.join(extracted_images)}"
            
        except Exception as e:
            return f"Error extracting images from PDF: {str(e)}"

Schema Changelog

Changes observed during successful MCP inspections.

  1. Changed1 schema field changedv1.0.0
    • addedInput schema / title
      Added value: +"pdf_extract_imagesArguments"
  2. First observed

TDQS

C2.9/5.0
Behavior2/5

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

With no annotations, the description carries the full burden. It merely restates the function without disclosing behaviors such as file output format, handling of output_dir, overwrite behavior, or error cases. This is minimal disclosure.

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?

A single concise sentence that front-loads the action and object. No filler or redundancy.

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

Completeness2/5

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

For a tool with two parameters and no annotation coverage, this description is too sparse. It omits crucial context such as how output_dir behaves when null, what image formats are produced, and whether the tool creates the output directory. The presence of an output schema may compensate, but the description itself does not provide enough operational detail.

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

Parameters1/5

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

Schema coverage is 0% and the description does not explain either parameter. pdf_path and output_dir are left undefined; the description mentions only 'a PDF' and not the arguments, so the agent receives no semantic guidance beyond parameter names.

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 'Extract all images from a PDF' uses a specific verb and resource, clearly distinguishing this from sibling tools which perform add/merge/split operations. It unambiguously states the tool's function.

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?

No guidance is provided on when to use this tool over alternatives. The description does not mention prerequisites, typical use cases, or exclusions, leaving the agent to infer usage solely from the tool name.

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