Skip to main content
Glama
GongRzhe

Office Word MCP Server

auto_fit_table_columns

Automatically adjusts table column widths in Word documents to fit content, eliminating manual resizing for better readability.

Instructions

Set table columns to auto-fit based on content.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameYes
table_indexYes

Implementation Reference

  • MCP tool registration using @mcp.tool() decorator. This sync function delegates to the async handler in format_tools.
    @mcp.tool()
    def auto_fit_table_columns(filename: str, table_index: int):
        """Set table columns to auto-fit based on content."""
        return format_tools.auto_fit_table_columns(filename, table_index)
  • Main asynchronous handler implementing the tool logic: input validation, document loading, table access, helper call, and saving.
    async def auto_fit_table_columns(filename: str, table_index: int) -> str:
        """Set table columns to auto-fit based on content.
        
        Args:
            filename: Path to the Word document
            table_index: Index of the table (0-based)
        """
        filename = ensure_docx_extension(filename)
        
        # Ensure numeric parameters are the correct type
        try:
            table_index = int(table_index)
        except (ValueError, TypeError):
            return "Invalid parameter: table_index must be an integer"
        
        if not os.path.exists(filename):
            return f"Document {filename} does not exist"
        
        # Check if file is writeable
        is_writeable, error_message = check_file_writeable(filename)
        if not is_writeable:
            return f"Cannot modify document: {error_message}. Consider creating a copy first."
        
        try:
            doc = Document(filename)
            
            # Validate table index
            if table_index < 0 or table_index >= len(doc.tables):
                return f"Invalid table index. Document has {len(doc.tables)} tables (0-{len(doc.tables)-1})."
            
            table = doc.tables[table_index]
            
            # Apply auto-fit
            success = auto_fit_table(table)
            
            if success:
                doc.save(filename)
                return f"Table {table_index} set to auto-fit columns based on content."
            else:
                return f"Failed to set table auto-fit."
        except Exception as e:
            return f"Failed to set table auto-fit: {str(e)}"
  • Supporting helper that configures the table XML for autofit layout and sets columns to auto width.
    def auto_fit_table(table):
        """
        Set table to auto-fit columns based on content.
        
        Args:
            table: The table to modify
            
        Returns:
            True if successful, False otherwise
        """
        try:
            # Get table element and properties
            tbl = table._tbl
            
            # Get or create table properties
            tbl_pr = tbl.find(qn('w:tblPr'))
            if tbl_pr is None:
                tbl_pr = OxmlElement('w:tblPr')
                tbl.insert(0, tbl_pr)
            
            # Remove existing layout
            existing_layout = tbl_pr.find(qn('w:tblLayout'))
            if existing_layout is not None:
                tbl_pr.remove(existing_layout)
            
            # Create auto layout element
            layout_element = OxmlElement('w:tblLayout')
            layout_element.set(qn('w:type'), 'autofit')
            
            tbl_pr.append(layout_element)
            
            # Set all column widths to auto
            for col_index in range(len(table.columns)):
                set_column_width(table, col_index, 0, "auto")
            
            return True
            
        except Exception as e:
            print(f"Error setting auto-fit table: {e}")
            return False

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