Skip to main content
Glama

convert_document

Convert Microsoft Office documents (Word, Excel, PowerPoint) to Markdown format with image extraction and optimization for Claude to read and process.

Instructions

Convert Office documents to Markdown format for Claude to read.

Supported formats:

  • Word: .docx, .doc

  • Excel: .xlsx, .xls (converts each sheet to a Markdown table)

  • PowerPoint: .pptx, .ppt (extracts text and images from slides)

Features:

  • Text extraction with formatting (headings, bold, italic, lists, tables)

  • Image extraction and optimization (auto-compressed for efficiency)

  • Speaker notes extraction from PowerPoint

  • Multi-sheet support for Excel

Images are automatically optimized (WebP format, max 1920x1080) to reduce size while maintaining readability for Claude.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYesAbsolute path to the Office document. Supported: .docx, .doc, .xlsx, .xls, .pptx, .ppt
extract_imagesNoWhether to extract and include images (default: true)
image_formatNoHow to handle images: 'file' saves to disk (recommended), 'base64' embeds in markdown, 'both' does bothfile
output_nameNoCustom name for the output (without extension). If not provided, generates from filename.

Implementation Reference

  • The main handler for the 'convert_document' tool within the @server.call_tool() function. It validates input parameters, calls OfficeConverter.convert_file(), processes the result, and returns a JSON summary with paths and preview.
    async def call_tool(name: str, arguments: dict[str, Any]) -> list[TextContent]:
        """Handle tool calls."""
        try:
            converter = get_converter()
            cache_notice = get_cache_location_notice(converter)
    
            if name == "convert_document":
                file_path = arguments.get("file_path")
                if not file_path:
                    return [TextContent(
                        type="text",
                        text=json.dumps({"error": "file_path is required"}, ensure_ascii=False)
                    )]
    
                extract_images = arguments.get("extract_images", True)
                image_format = arguments.get("image_format", "file")
                output_name = arguments.get("output_name")
    
                result = converter.convert_file(
                    file_path=file_path,
                    extract_images=extract_images,
                    image_format=image_format,
                    output_name=output_name,
                )
    
                # Return summary with markdown preview
                response = {
                    "status": "success",
                    "file_type": result.get("file_type", "unknown"),
                    "cache_location": str(converter.cache_dir),
                    "output_path": result["output_path"],
                    "conversion_dir": result["conversion_dir"],
                    "images_extracted": len(result["images"]),
                    "image_paths": result["images"],
                    "metadata": result["metadata"],
                    "markdown_preview": result["markdown"][:2000] + "..." if len(result["markdown"]) > 2000 else result["markdown"],
                    "markdown_length": len(result["markdown"]),
                    "hint": "Use 'list_conversions' to see all cached files, or 'read_converted_markdown' to read the full content.",
                }
    
                return [TextContent(
                    type="text",
                    text=f"{cache_notice}\n\n" + json.dumps(response, ensure_ascii=False, indent=2)
                )]
  • Input schema and description for the 'convert_document' tool, defining parameters like file_path, extract_images, image_format, and output_name.
            Tool(
                name="convert_document",
                description=f"""Convert Office documents to Markdown format for Claude to read.
    
    Supported formats:
    - Word: .docx, .doc
    - Excel: .xlsx, .xls (converts each sheet to a Markdown table)
    - PowerPoint: .pptx, .ppt (extracts text and images from slides)
    
    Features:
    - Text extraction with formatting (headings, bold, italic, lists, tables)
    - Image extraction and optimization (auto-compressed for efficiency)
    - Speaker notes extraction from PowerPoint
    - Multi-sheet support for Excel
    
    Images are automatically optimized (WebP format, max 1920x1080) to reduce size
    while maintaining readability for Claude.""",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "file_path": {
                            "type": "string",
                            "description": f"Absolute path to the Office document. Supported: {supported_exts}",
                        },
                        "extract_images": {
                            "type": "boolean",
                            "description": "Whether to extract and include images (default: true)",
                            "default": True,
                        },
                        "image_format": {
                            "type": "string",
                            "enum": ["file", "base64", "both"],
                            "description": "How to handle images: 'file' saves to disk (recommended), 'base64' embeds in markdown, 'both' does both",
                            "default": "file",
                        },
                        "output_name": {
                            "type": "string",
                            "description": "Custom name for the output (without extension). If not provided, generates from filename.",
                        },
                    },
                    "required": ["file_path"],
                },
            ),
  • Registration of all tools including 'convert_document' via the @server.list_tools() decorator in the MCP server.
    @server.list_tools()
    async def list_tools() -> list[Tool]:
        """List available tools for the MCP server."""
        supported_exts = ", ".join(get_supported_extensions())
    
        return [
            Tool(
                name="convert_document",
                description=f"""Convert Office documents to Markdown format for Claude to read.
    
    Supported formats:
    - Word: .docx, .doc
    - Excel: .xlsx, .xls (converts each sheet to a Markdown table)
    - PowerPoint: .pptx, .ppt (extracts text and images from slides)
    
    Features:
    - Text extraction with formatting (headings, bold, italic, lists, tables)
    - Image extraction and optimization (auto-compressed for efficiency)
    - Speaker notes extraction from PowerPoint
    - Multi-sheet support for Excel
    
    Images are automatically optimized (WebP format, max 1920x1080) to reduce size
    while maintaining readability for Claude.""",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "file_path": {
                            "type": "string",
                            "description": f"Absolute path to the Office document. Supported: {supported_exts}",
                        },
                        "extract_images": {
                            "type": "boolean",
                            "description": "Whether to extract and include images (default: true)",
                            "default": True,
                        },
                        "image_format": {
                            "type": "string",
                            "enum": ["file", "base64", "both"],
                            "description": "How to handle images: 'file' saves to disk (recommended), 'base64' embeds in markdown, 'both' does both",
                            "default": "file",
                        },
                        "output_name": {
                            "type": "string",
                            "description": "Custom name for the output (without extension). If not provided, generates from filename.",
                        },
                    },
                    "required": ["file_path"],
                },
            ),
            Tool(
                name="read_converted_markdown",
                description="""Read the content of a previously converted markdown file.
    
    Use this after convert_document to get the actual markdown content.
    This is useful when you want to process or analyze the converted document.""",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "markdown_path": {
                            "type": "string",
                            "description": "Path to the markdown file (returned by convert_document)",
                        },
                    },
                    "required": ["markdown_path"],
                },
            ),
            Tool(
                name="list_conversions",
                description="""List all cached document conversions.
    
    Shows all documents that have been converted, including their output paths
    and number of extracted images. Useful for finding previously converted files.""",
                inputSchema={
                    "type": "object",
                    "properties": {},
                },
            ),
            Tool(
                name="clear_cache",
                description="""Clear all cached conversions.
    
    Removes all converted markdown files and extracted images from the cache.
    Use this to free up disk space or reset the conversion cache.""",
                inputSchema={
                    "type": "object",
                    "properties": {},
                },
            ),
            Tool(
                name="get_document_metadata",
                description=f"""Get metadata from an Office document without full conversion.
    
    Extracts document properties like title, author, creation date, etc.
    Faster than full conversion when you only need metadata.
    
    Supported formats: {supported_exts}""",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "file_path": {
                            "type": "string",
                            "description": f"Absolute path to the Office document. Supported: {supported_exts}",
                        },
                    },
                    "required": ["file_path"],
                },
            ),
            Tool(
                name="get_supported_formats",
                description="""Get list of all supported file formats.
    
    Returns a dictionary of file types (word, excel, powerpoint) and their extensions.""",
                inputSchema={
                    "type": "object",
                    "properties": {},
                },
            ),
        ]
  • Core helper method OfficeConverter.convert_file() called by the handler. Detects document type and delegates to specialized converters (word, excel, powerpoint) for the actual conversion logic.
        self,
        file_path: str,
        extract_images: bool = True,
        image_format: str = "file",
        output_name: Optional[str] = None,
    ) -> dict:
        """
        Convert any supported Office document to Markdown.
    
        Args:
            file_path: Path to the document
            extract_images: Whether to extract images
            image_format: "file", "base64", or "both"
            output_name: Custom output name
    
        Returns:
            dict with markdown, images, metadata, and paths
        """
        file_path = Path(file_path)
    
        if not file_path.exists():
            raise FileNotFoundError(f"File not found: {file_path}")
    
        file_type = get_file_type(file_path)
        if file_type is None:
            supported = []
            for exts in SUPPORTED_FORMATS.values():
                supported.extend(exts)
            raise ValueError(
                f"Unsupported file format: {file_path.suffix}. "
                f"Supported formats: {', '.join(supported)}"
            )
    
        # Generate output name
        if not output_name:
            file_hash = self._get_file_hash(file_path)
            output_name = f"{file_path.stem}_{file_hash[:8]}"
    
        # Create output directory
        conversion_dir = self.output_dir / output_name
        conversion_dir.mkdir(exist_ok=True)
        images_dir = conversion_dir / "images"
        images_dir.mkdir(exist_ok=True)
    
        # Convert based on file type
        if file_type == "word":
            result = self._docx_converter.convert_file(
                str(file_path),
                extract_images=extract_images,
                image_format=image_format,
                output_name=output_name,
            )
        elif file_type == "excel":
            result = self.excel_converter.convert_file(
                str(file_path),
                extract_images=extract_images,
                image_format=image_format,
                output_name=output_name,
                conversion_dir=conversion_dir,
                images_dir=images_dir,
            )
        elif file_type == "powerpoint":
            result = self.pptx_converter.convert_file(
                str(file_path),
                extract_images=extract_images,
                image_format=image_format,
                output_name=output_name,
                conversion_dir=conversion_dir,
                images_dir=images_dir,
            )
        else:
            raise ValueError(f"Unknown file type: {file_type}")
    
        # Save markdown if not already saved (for Excel/PPT)
        md_path = conversion_dir / f"{output_name}.md"
        if "output_path" not in result:
            with open(md_path, "w", encoding="utf-8") as f:
                f.write(result["markdown"])
            result["output_path"] = str(md_path)
            result["conversion_dir"] = str(conversion_dir)
    
        # Add file type info
        result["file_type"] = file_type
    
        return result
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by detailing behavioral traits: text extraction with formatting, image extraction and optimization (WebP format, max 1920x1080), speaker notes extraction, and multi-sheet support. It covers key aspects like output format (Markdown) and efficiency features, though it doesn't mention error handling or performance limits.

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 sections for supported formats and features, and each sentence adds useful information. It could be slightly more concise by integrating the image optimization detail into the features list, but overall it's front-loaded and efficient with minimal waste.

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

Completeness4/5

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

Given no annotations and no output schema, the description does a good job covering the tool's behavior, supported formats, and features. It provides enough context for an agent to understand what the tool does and how to use it, though it doesn't specify return values or error cases, which would enhance completeness.

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 100%, so the baseline is 3. The description adds some value by listing supported formats and image optimization details, but does not provide additional semantic context for parameters beyond what's in the schema (e.g., it doesn't explain implications of image_format choices or output_name usage).

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 tool's purpose: converting Office documents to Markdown format for Claude to read. It specifies the exact formats supported (Word, Excel, PowerPoint with file extensions) and distinguishes it from siblings like get_document_metadata or read_converted_markdown by focusing on conversion rather than metadata retrieval or reading.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context by stating it's for Claude to read and listing supported formats, but does not explicitly state when to use this tool versus alternatives like get_supported_formats or list_conversions. It provides clear input requirements but lacks explicit guidance on tool selection among siblings.

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/Asunainlove/OfficeReader-MCP'

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