Skip to main content
Glama
GongRzhe

Office Word MCP Server

set_table_column_width

Adjust table column width in Word documents to improve readability and formatting. Specify filename, table index, column index, and desired width for precise control.

Instructions

Set the width of a specific table column.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameYes
table_indexYes
col_indexYes
widthYes
width_typeNopoints

Implementation Reference

  • MCP tool registration for set_table_column_width using @mcp.tool(). Defines input schema via type hints and docstring. Thin handler delegates to format_tools implementation.
    @mcp.tool()
    def set_table_column_width(filename: str, table_index: int, col_index: int, 
                              width: float, width_type: str = "points"):
        """Set the width of a specific table column."""
        return format_tools.set_table_column_width(filename, table_index, col_index, width, width_type)
  • Primary handler logic: validates inputs, handles document loading/saving, converts width units to Word XML format (dxa/pct), delegates low-level XML manipulation to core.tables.set_column_width_by_position.
    async def set_table_column_width(filename: str, table_index: int, col_index: int, 
                                    width: float, width_type: str = "points") -> str:
        """Set the width of a specific table column.
        
        Args:
            filename: Path to the Word document
            table_index: Index of the table (0-based)
            col_index: Column index (0-based)
            width: Column width value
            width_type: Width type ("points", "inches", "cm", "percent", "auto")
        """
        filename = ensure_docx_extension(filename)
        
        # Ensure numeric parameters are the correct type
        try:
            table_index = int(table_index)
            col_index = int(col_index)
            if width_type != "auto":
                width = float(width)
        except (ValueError, TypeError):
            return "Invalid parameter: table_index and col_index must be integers, width must be a number"
        
        # Validate width type
        valid_width_types = ["points", "inches", "cm", "percent", "auto"]
        if width_type.lower() not in valid_width_types:
            return f"Invalid width type. Valid options: {', '.join(valid_width_types)}"
        
        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]
            
            # Validate column index
            if col_index < 0 or col_index >= len(table.columns):
                return f"Invalid column index. Table has {len(table.columns)} columns (0-{len(table.columns)-1})."
            
            # Convert width and type for Word format
            if width_type.lower() == "points":
                # Points to DXA (twentieths of a point)
                word_width = width
                word_type = "dxa"
            elif width_type.lower() == "inches":
                # Inches to points, then to DXA
                word_width = width * 72  # 72 points per inch
                word_type = "dxa"
            elif width_type.lower() == "cm":
                # CM to points, then to DXA
                word_width = width * 28.35  # ~28.35 points per cm
                word_type = "dxa"
            elif width_type.lower() == "percent":
                # Percentage (Word uses 50x the percentage value)
                word_width = width
                word_type = "pct"
            else:  # auto
                word_width = 0
                word_type = "auto"
            
            # Apply column width
            success = set_column_width_by_position(table, col_index, word_width, word_type)
            
            if success:
                doc.save(filename)
                return f"Column width set successfully for table {table_index}, column {col_index} to {width} {width_type}."
            else:
                return f"Failed to set column width. Check that indices are valid."
        except Exception as e:
            return f"Failed to set column width: {str(e)}"
  • Low-level helper that directly modifies the Word document XML (w:tcW elements in tcPr for each cell in the column) to set the column width. Performs unit conversion to DXA/PCT and handles XML manipulation.
    def set_column_width(table, col_index, width, width_type="dxa"):
        """
        Set the width of a specific column in a table.
        
        Args:
            table: The table to modify
            col_index: Column index (0-based)
            width: Column width value
            width_type: Width type ("dxa" for points*20, "pct" for percentage*50, "auto")
            
        Returns:
            True if successful, False otherwise
        """
        try:
            # Validate column index
            if col_index < 0 or col_index >= len(table.columns):
                return False
            
            # Convert width based on type
            if width_type == "dxa":
                # DXA units (twentieths of a point)
                if isinstance(width, (int, float)):
                    width_value = str(int(width * 20))
                else:
                    width_value = str(width)
            elif width_type == "pct":
                # Percentage (multiply by 50 for Word format)
                if isinstance(width, (int, float)):
                    width_value = str(int(width * 50))
                else:
                    width_value = str(width)
            else:
                width_value = str(width)
            
            # Iterate through all rows and set width for cells in the specified column
            for row in table.rows:
                if col_index < len(row.cells):
                    cell = row.cells[col_index]
                    tc_pr = cell._tc.get_or_add_tcPr()
                    
                    # Remove existing width
                    existing_width = tc_pr.find(qn('w:tcW'))
                    if existing_width is not None:
                        tc_pr.remove(existing_width)
                    
                    # Create new width element
                    width_element = OxmlElement('w:tcW')
                    width_element.set(qn('w:w'), width_value)
                    width_element.set(qn('w:type'), width_type)
                    
                    tc_pr.append(width_element)
            
            return True
            
        except Exception as e:
            print(f"Error setting column width: {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 but offers minimal behavioral insight. It states the action ('Set') implying a mutation, but doesn't disclose whether this requires specific permissions, if changes are reversible, what happens to document state, or any rate limits. For a mutation tool with zero annotation coverage, this is inadequate.

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 directly states the tool's purpose without unnecessary words. It's appropriately front-loaded with the core action, though its brevity contributes to gaps in other dimensions rather than being a virtue of conciseness.

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?

For a mutation tool with 5 parameters (4 required), 0% schema coverage, no annotations, and no output schema, the description is severely incomplete. It doesn't address behavioral aspects, parameter meanings, usage context, or expected outcomes. The tool modifies document structure yet provides minimal guidance for safe invocation.

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

Parameters2/5

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

Schema description coverage is 0%, so the description must compensate but adds no parameter information. It doesn't explain what 'filename', 'table_index', 'col_index', 'width', or 'width_type' mean, their expected formats, or relationships. The description fails to provide any semantic context beyond what's inferable from parameter names.

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') and target resource ('width of a specific table column'), making the purpose immediately understandable. It distinguishes itself from sibling tools like 'set_table_column_widths' (plural) by focusing on a single column, though this distinction could be more explicit.

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., document must exist), compare to sibling tools like 'auto_fit_table_columns' or 'set_table_column_widths' (plural), or specify when this operation is appropriate versus other table formatting tools.

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