Skip to main content
Glama

convert_to_pdf

Transform Word documents into PDF format using standardized processing. Ideal for managing file compatibility and sharing needs directly within the Office Word MCP Server.

Instructions

Convert a Word document to PDF format.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameYes
output_filenameNo

Implementation Reference

  • The core handler function that implements the convert_to_pdf tool logic. It handles DOCX to PDF conversion using docx2pdf on Windows or LibreOffice subprocess on Linux/macOS, with comprehensive error handling and file management.
    async def convert_to_pdf(filename: str, output_filename: Optional[str] = None) -> str:
        """Convert a Word document to PDF format.
        
        Args:
            filename: Path to the Word document
            output_filename: Optional path for the output PDF. If not provided, 
                             will use the same name with .pdf extension
        """
        filename = ensure_docx_extension(filename)
        
        if not os.path.exists(filename):
            return f"Document {filename} does not exist"
        
        # Generate output filename if not provided
        if not output_filename:
            base_name, _ = os.path.splitext(filename)
            output_filename = f"{base_name}.pdf"
        elif not output_filename.lower().endswith('.pdf'):
            output_filename = f"{output_filename}.pdf"
        
        # Convert to absolute path if not already
        if not os.path.isabs(output_filename):
            output_filename = os.path.abspath(output_filename)
        
        # Ensure the output directory exists
        output_dir = os.path.dirname(output_filename)
        if not output_dir:
            output_dir = os.path.abspath('.')
        
        # Create the directory if it doesn't exist
        os.makedirs(output_dir, exist_ok=True)
        
        # Check if output file can be written
        is_writeable, error_message = check_file_writeable(output_filename)
        if not is_writeable:
            return f"Cannot create PDF: {error_message} (Path: {output_filename}, Dir: {output_dir})"
        
        try:
            # Determine platform for appropriate conversion method
            system = platform.system()
            
            if system == "Windows":
                # On Windows, try docx2pdf which uses Microsoft Word
                try:
                    from docx2pdf import convert
                    convert(filename, output_filename)
                    return f"Document successfully converted to PDF: {output_filename}"
                except (ImportError, Exception) as e:
                    return f"Failed to convert document to PDF: {str(e)}\nNote: docx2pdf requires Microsoft Word to be installed."
                    
            elif system in ["Linux", "Darwin"]:  # Linux or macOS
                # Try using LibreOffice if available (common on Linux/macOS)
                try:
                    # Choose the appropriate command based on OS
                    if system == "Darwin":  # macOS
                        lo_commands = ["soffice", "/Applications/LibreOffice.app/Contents/MacOS/soffice"]
                    else:  # Linux
                        lo_commands = ["libreoffice", "soffice"]
                    
                    # Try each possible command
                    conversion_successful = False
                    errors = []
                    
                    for cmd_name in lo_commands:
                        try:
                            # Construct LibreOffice conversion command
                            output_dir = os.path.dirname(output_filename)
                            # If output_dir is empty, use current directory
                            if not output_dir:
                                output_dir = '.'
                            # Ensure the directory exists
                            os.makedirs(output_dir, exist_ok=True)
                            
                            cmd = [
                                cmd_name, 
                                '--headless', 
                                '--convert-to', 
                                'pdf', 
                                '--outdir', 
                                output_dir, 
                                filename
                            ]
                            
                            result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
                            
                            if result.returncode == 0:
                                # LibreOffice creates the PDF with the same basename
                                base_name = os.path.basename(filename)
                                pdf_base_name = os.path.splitext(base_name)[0] + ".pdf"
                                created_pdf = os.path.join(os.path.dirname(output_filename) or '.', pdf_base_name)
                                
                                # If the created PDF is not at the desired location, move it
                                if created_pdf != output_filename and os.path.exists(created_pdf):
                                    shutil.move(created_pdf, output_filename)
                                
                                conversion_successful = True
                                break  # Exit the loop if successful
                            else:
                                errors.append(f"{cmd_name} error: {result.stderr}")
                        except (subprocess.SubprocessError, FileNotFoundError) as e:
                            errors.append(f"{cmd_name} error: {str(e)}")
                    
                    if conversion_successful:
                        return f"Document successfully converted to PDF: {output_filename}"
                    else:
                        # If all LibreOffice attempts failed, try docx2pdf as fallback
                        try:
                            from docx2pdf import convert
                            convert(filename, output_filename)
                            return f"Document successfully converted to PDF: {output_filename}"
                        except (ImportError, Exception) as e:
                            error_msg = "Failed to convert document to PDF using LibreOffice or docx2pdf.\n"
                            error_msg += "LibreOffice errors: " + "; ".join(errors) + "\n"
                            error_msg += f"docx2pdf error: {str(e)}\n"
                            error_msg += "To convert documents to PDF, please install either:\n"
                            error_msg += "1. LibreOffice (recommended for Linux/macOS)\n"
                            error_msg += "2. Microsoft Word (required for docx2pdf on Windows/macOS)"
                            return error_msg
                            
                except Exception as e:
                    return f"Failed to convert document to PDF: {str(e)}"
            else:
                return f"PDF conversion not supported on {system} platform"
                
        except Exception as e:
            return f"Failed to convert document to PDF: {str(e)}"
  • MCP tool registration using @mcp.tool() decorator. This wrapper function delegates execution to the implementation in extended_document_tools.py.
    async def convert_to_pdf(filename: str, output_filename: Optional[str] = None):
        """Convert a Word document to PDF format."""
        return await extended_document_tools.convert_to_pdf(filename, output_filename)
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the conversion action but doesn't describe traits like whether it overwrites files, requires specific permissions, handles errors, or has rate limits. For a mutation tool (conversion implies change) with zero annotation coverage, this is a significant gap in transparency.

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 that front-loads the core action ('Convert a Word document to PDF format'). There is no wasted text, and it directly communicates the tool's function without unnecessary elaboration, making it highly concise and well-structured.

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

Completeness2/5

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

Given the complexity (a mutation tool with 2 parameters), lack of annotations, and no output schema, the description is incomplete. It doesn't cover behavioral aspects like side effects, error handling, or output details, leaving gaps that could hinder an AI agent's correct invocation. More context is needed for adequate 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 0%, so the schema provides no parameter details. The description mentions 'Word document' and 'PDF format', which hints at the 'filename' parameter for input and 'output_filename' for output, but doesn't explain parameter meanings, formats, or constraints. It adds minimal value beyond the schema, compensating slightly for the coverage gap but not fully.

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 tool's purpose: converting a Word document to PDF format. It uses specific verbs ('Convert') and identifies the resource ('Word document'), making the function unambiguous. However, it doesn't explicitly differentiate from sibling tools like 'copy_document' or 'create_document', which might also involve document format changes, though those are not direct PDF conversions.

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. It doesn't mention prerequisites (e.g., needing an existing Word document), exclusions (e.g., not for other file types), or comparisons to siblings like 'copy_document' for format preservation. Usage is implied from the purpose but lacks explicit context or decision criteria.

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

Related 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/franlealp1/mcp-word'

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