Skip to main content
Glama
GongRzhe

Office Word MCP Server

add_picture

Insert images into Word documents by specifying file paths and optional dimensions to enhance document content.

Instructions

Add an image to a Word document.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameYes
image_pathYes
widthNo

Implementation Reference

  • Core handler function that implements the logic to add a picture to a Word document. Includes comprehensive validation for file existence, writability, image size, and detailed error handling. Uses python-docx Document.add_picture() at lines 264 and 266.
    async def add_picture(filename: str, image_path: str, width: Optional[float] = None) -> str:
        """Add an image to a Word document.
        
        Args:
            filename: Path to the Word document
            image_path: Path to the image file
            width: Optional width in inches (proportional scaling)
        """
        filename = ensure_docx_extension(filename)
        
        # Validate document existence
        if not os.path.exists(filename):
            return f"Document {filename} does not exist"
        
        # Get absolute paths for better diagnostics
        abs_filename = os.path.abspath(filename)
        abs_image_path = os.path.abspath(image_path)
        
        # Validate image existence with improved error message
        if not os.path.exists(abs_image_path):
            return f"Image file not found: {abs_image_path}"
        
        # Check image file size
        try:
            image_size = os.path.getsize(abs_image_path) / 1024  # Size in KB
            if image_size <= 0:
                return f"Image file appears to be empty: {abs_image_path} (0 KB)"
        except Exception as size_error:
            return f"Error checking image file: {str(size_error)}"
        
        # Check if file is writeable
        is_writeable, error_message = check_file_writeable(abs_filename)
        if not is_writeable:
            return f"Cannot modify document: {error_message}. Consider creating a copy first or creating a new document."
        
        try:
            doc = Document(abs_filename)
            # Additional diagnostic info
            diagnostic = f"Attempting to add image ({abs_image_path}, {image_size:.2f} KB) to document ({abs_filename})"
            
            try:
                if width:
                    doc.add_picture(abs_image_path, width=Inches(width))
                else:
                    doc.add_picture(abs_image_path)
                doc.save(abs_filename)
                return f"Picture {image_path} added to {filename}"
            except Exception as inner_error:
                # More detailed error for the specific operation
                error_type = type(inner_error).__name__
                error_msg = str(inner_error)
                return f"Failed to add picture: {error_type} - {error_msg or 'No error details available'}\nDiagnostic info: {diagnostic}"
        except Exception as outer_error:
            # Fallback error handling
            error_type = type(outer_error).__name__
            error_msg = str(outer_error)
            return f"Document processing error: {error_type} - {error_msg or 'No error details available'}"
  • MCP tool registration within register_tools() function using @mcp.tool() decorator. The function signature provides type hints for schema, docstring describes the tool, and it delegates to the core implementation in content_tools.
    @mcp.tool()
    def add_picture(filename: str, image_path: str, width: float = None):
        """Add an image to a Word document."""
        return content_tools.add_picture(filename, image_path, width)
  • Tool schema defined by function parameters (filename: str required, image_path: str required, width: float optional), type annotations, and docstring description used by MCP framework.
    @mcp.tool()
    def add_picture(filename: str, image_path: str, width: float = None):
        """Add an image to a Word document."""
        return content_tools.add_picture(filename, image_path, width)
  • Re-exports the add_picture function from content_tools.py for convenient imports in main.py.
    from word_document_server.tools.content_tools import (
        add_heading, add_paragraph, add_table, add_picture,
        add_page_break, add_table_of_contents, delete_paragraph,
        search_and_replace
    )

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/GongRzhe/Office-Word-MCP-Server'

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