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)}"
Behavior2/5

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

No annotations are provided, so the description carries full burden for behavioral disclosure. 'Extract' implies a read operation that doesn't modify the PDF, but it doesn't specify whether images are saved to disk, returned as data, require specific permissions, or have rate limits. For a tool with 2 parameters and no annotation coverage, this is inadequate.

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 a single, efficient sentence with zero wasted words—it directly states the tool's function without unnecessary elaboration. It's appropriately sized and front-loaded, making it easy to parse quickly.

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 has an output schema (which should cover return values), 2 parameters with 0% schema coverage, and no annotations, the description is minimally complete. It states what the tool does but lacks details on behavior, parameters, and usage context, making it adequate only with support from the output schema.

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

Parameters3/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, but it adds no parameter information beyond what's implied by the tool name. It doesn't explain what pdf_path expects (e.g., file path, URL), what output_dir does (e.g., directory for saving images, null for in-memory), or format details. Baseline 3 is given due to low coverage, but minimal value is added.

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 verb ('Extract') and resource ('all images from a PDF'), making the purpose immediately understandable. However, it doesn't differentiate from sibling tools like pdf_add_image or pdf_get_info, which also involve PDF images in different ways, so it doesn't reach the highest clarity level.

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. With siblings like pdf_add_image (for adding images) and pdf_get_info (which might include image metadata), there's no indication of when extraction is appropriate versus other operations, leaving usage context unclear.

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/andr3medeiros/pdf-manipulation-mcp-server'

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