Skip to main content
Glama

extract_images

Extract images from Word documents by providing a file path, optionally saving to a directory or returning base64 data.

Instructions

Extract all images from a Word document.

Args: filepath: Path to the document output_dir: Directory to save extracted images (optional) return_base64: If True, return images as base64 encoded strings

Returns: Dictionary with extracted images info and optionally base64 data

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filepathYes
output_dirNo
return_base64No

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The 'extract_images' tool implementation, including the @app.tool() decorator and the core logic for extracting and optionally saving or base64-encoding images from a Word document.
    @app.tool()
    def extract_images(
        filepath: str,
        output_dir: Optional[str] = None,
        return_base64: bool = False,
    ) -> dict[str, Any]:
        """
        Extract all images from a Word document.
    
        Args:
            filepath: Path to the document
            output_dir: Directory to save extracted images (optional)
            return_base64: If True, return images as base64 encoded strings
    
        Returns:
            Dictionary with extracted images info and optionally base64 data
        """
        import base64
    
        logger.info("Extracting images", extra={"tool": "extract_images", "filepath": filepath})
    
        try:
            doc = safe_open_document(filepath)
            extracted = []
            image_index = 0
    
            for rel in doc.part.rels.values():
                if "image" in rel.target_ref:
                    image_part = rel.target_part
                    image_data = image_part.blob
                    filename = Path(image_part.partname).name
                    content_type = image_part.content_type
    
                    image_info = {
                        "index": image_index,
                        "filename": filename,
                        "content_type": content_type,
                        "size_bytes": len(image_data),
                    }
    
                    # Save to output directory if specified
                    if output_dir:
                        out_path = normalize_path(output_dir)
                        out_path.mkdir(parents=True, exist_ok=True)
                        image_file = out_path / filename
                        image_file.write_bytes(image_data)
                        image_info["saved_path"] = str(image_file)
    
                    # Return base64 if requested
                    if return_base64:
                        image_info["base64"] = base64.b64encode(image_data).decode("utf-8")
    
                    extracted.append(image_info)
                    image_index += 1
    
            logger.info(f"Extracted {len(extracted)} images", extra={"filepath": filepath})
    
            return {
                "status": "success",
                "filepath": filepath,
                "images": extracted,
                "count": len(extracted),
            }
        except DocxMcpError as e:
            logger.warning(e.message, extra={"tool": "extract_images", "error_code": e.error_code})
            return {"status": "error", "error": e.message, "error_code": e.error_code}
        except Exception as e:
            logger.error(f"Unexpected error extracting images: {str(e)}")
            return {"status": "error", "error": str(e)}
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 lacks critical behavioral details. It mentions optional saving to a directory and base64 return, but doesn't disclose error handling (e.g., invalid file paths), performance characteristics, what happens if output_dir is null, or whether extraction modifies the original document. This leaves significant gaps for an agent.

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

Conciseness4/5

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

The description is well-structured with a clear purpose statement followed by Args and Returns sections. Every sentence adds value, though the 'Args' and 'Returns' labels could be slightly more integrated. It's appropriately sized for a tool with three parameters.

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 no annotations, 0% schema coverage, but an output schema exists, the description is moderately complete. It covers the core purpose and parameters adequately, but lacks behavioral context (e.g., error cases, side effects) and doesn't fully compensate for the missing annotation coverage. The output schema reduces the need to detail return values, but overall completeness is just adequate.

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 provides clear semantic meaning for all three parameters: filepath identifies the source, output_dir specifies where to save images, and return_base64 controls return format. This adds substantial value beyond the bare schema types, though it doesn't detail path formats or directory creation behavior.

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 ('extract all images') and resource ('from a Word document'), distinguishing it from sibling tools like 'list_images' (which likely lists without extracting) or 'insert_image' (which adds rather than extracts). The verb 'extract' is precise and unambiguous.

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 versus alternatives like 'list_images' or other document processing tools. The description only states what it does, not when it's appropriate or what prerequisites might exist (e.g., file accessibility).

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/Andrew82106/LLM_Docx_Agent_MCP'

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