insert_image
Add images to Word documents by specifying file paths and optional dimensions to enhance document content with visual elements.
Instructions
Insert an image into a document.
Args: filepath: Path to the document image_path: Path to the image file to insert width: Image width in inches (optional) height: Image height in inches (optional)
Returns: Dictionary with status
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| filepath | Yes | ||
| image_path | Yes | ||
| width | No | ||
| height | No |
Implementation Reference
- src/docx_mcp/server.py:866-925 (handler)The `insert_image` function is defined and registered as an MCP tool using the `@app.tool()` decorator in `src/docx_mcp/server.py`. It handles the logic of validating the image path, opening the Word document, adding the image to a new paragraph, and saving the document.
def insert_image( filepath: str, image_path: str, width: Optional[float] = None, height: Optional[float] = None, ) -> dict[str, Any]: """ Insert an image into a document. Args: filepath: Path to the document image_path: Path to the image file to insert width: Image width in inches (optional) height: Image height in inches (optional) Returns: Dictionary with status """ logger.info("Inserting image", extra={"tool": "insert_image", "filepath": filepath}) try: # Validate image file exists if image_path.endswith(('.docx', '.doc', '.dotx', '.dot')): image_file = validate_docx_file(image_path) else: image_file = Path(image_path) if not image_file.exists(): raise DocxFileNotFoundError(image_path) doc = safe_open_document(filepath) # Add paragraph with image last_paragraph = doc.add_paragraph() run = last_paragraph.add_run() # Insert image with optional sizing if width and height: run.add_picture(str(image_file), width=Inches(width), height=Inches(height)) elif width: run.add_picture(str(image_file), width=Inches(width)) elif height: run.add_picture(str(image_file), height=Inches(height)) else: run.add_picture(str(image_file)) safe_save_document(doc, filepath) logger.info("Image inserted successfully", extra={"filepath": filepath}) return { "status": "success", "filepath": filepath, "image": image_path, "message": "Image inserted successfully", } except DocxMcpError as e: logger.warning(e.message, extra={"tool": "insert_image", "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 inserting image: {str(e)}") return {"status": "error", "error": str(e)}