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
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It states the tool performs a mutation ('Set'), implying it modifies document structure, but doesn't specify whether this requires write permissions, whether changes are reversible, what happens if the table doesn't exist, or what visual/formatting side effects occur. For a mutation tool 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 states the core functionality without unnecessary words. It's appropriately sized for a straightforward tool and front-loads the key action. Every word earns its place, making it easy to parse quickly.

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 tool performs a mutation (auto-fitting table columns) with no annotations, no output schema, and 2 undocumented parameters, the description is incomplete. It doesn't address behavioral aspects like error conditions, side effects, or return values, nor does it clarify parameter semantics. For a document-editing tool in a rich sibling context, more guidance is needed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, meaning neither parameter ('filename', 'table_index') has any documentation in the schema. The description provides no information about these parameters—what they represent, expected formats, constraints, or examples. For a tool with 2 required parameters, this leaves the agent guessing about their meaning and proper usage.

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 action ('Set table columns to auto-fit') and the target resource ('based on content'), providing a specific verb+resource combination. It distinguishes from sibling tools like 'set_table_column_width' or 'set_table_column_widths' by focusing on automatic fitting rather than manual width specification. However, it doesn't explicitly contrast with these siblings in the description text itself.

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 like 'set_table_column_width' or 'format_table'. It doesn't mention prerequisites (e.g., document must be open, table must exist), performance considerations, or typical use cases. The agent must infer usage from the tool name and sibling context alone.

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

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