Skip to main content
Glama
GongRzhe

Office Word MCP Server

set_table_width

Adjust table width in Microsoft Word documents to control layout and formatting for better document presentation.

Instructions

Set the overall width of a table.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameYes
table_indexYes
widthYes
width_typeNopoints

Implementation Reference

  • Tool registration using FastMCP @mcp.tool() decorator. Thin wrapper that delegates to the format_tools.set_table_width implementation.
    @mcp.tool()
    def set_table_width(filename: str, table_index: int, width: float, 
                       width_type: str = "points"):
        """Set the overall width of a table."""
        return format_tools.set_table_width(filename, table_index, width, width_type)
  • Primary handler function that orchestrates the tool execution: validates inputs, loads document, converts user-friendly width units to Word XML format, calls core helper, saves document.
    async def set_table_width(filename: str, table_index: int, width: float, 
                             width_type: str = "points") -> str:
        """Set the overall width of a table.
        
        Args:
            filename: Path to the Word document
            table_index: Index of the table (0-based)
            width: Table 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)
            if width_type != "auto":
                width = float(width)
        except (ValueError, TypeError):
            return "Invalid parameter: table_index must be an integer, 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]
            
            # Convert width and type for Word format
            if width_type.lower() == "points":
                word_width = width
                word_type = "dxa"
            elif width_type.lower() == "inches":
                word_width = width * 72  # 72 points per inch
                word_type = "dxa"
            elif width_type.lower() == "cm":
                word_width = width * 28.35  # ~28.35 points per cm
                word_type = "dxa"
            elif width_type.lower() == "percent":
                word_width = width
                word_type = "pct"
            else:  # auto
                word_width = 0
                word_type = "auto"
            
            # Apply table width
            success = set_table_width_func(table, word_width, word_type)
            
            if success:
                doc.save(filename)
                return f"Table width set successfully for table {table_index} to {width} {width_type}."
            else:
                return f"Failed to set table width."
        except Exception as e:
            return f"Failed to set table width: {str(e)}"
  • Core low-level helper that directly manipulates the Word document XML to set the <w:tblW> element in table properties, converting units to DXA or PCT as needed.
    def set_table_width(table, width, width_type="dxa"):
        """
        Set the overall width of a table.
        
        Args:
            table: The table to modify
            width: Table width value
            width_type: Width type ("dxa" for points*20, "pct" for percentage*50, "auto")
            
        Returns:
            True if successful, False otherwise
        """
        try:
            # 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)
            
            # 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 table width
            existing_width = tbl_pr.find(qn('w:tblW'))
            if existing_width is not None:
                tbl_pr.remove(existing_width)
            
            # Create new table width element
            width_element = OxmlElement('w:tblW')
            width_element.set(qn('w:w'), width_value)
            width_element.set(qn('w:type'), width_type)
            
            tbl_pr.append(width_element)
            
            return True
            
        except Exception as e:
            print(f"Error setting table width: {e}")
            return False
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 action 'Set', implying a mutation, but does not disclose critical traits like whether this operation is destructive, requires specific permissions, has side effects (e.g., affecting table layout), or any rate limits. The description is too minimal to inform the agent adequately about behavioral risks or constraints.

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, direct sentence that is front-loaded and wastes no words. It efficiently conveys the core action without unnecessary elaboration, making it easy to parse and understand 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 complexity of a mutation tool with 4 parameters, 0% schema coverage, no annotations, and no output schema, the description is incomplete. It fails to provide necessary context such as parameter meanings, behavioral traits, or usage guidelines, leaving the agent under-informed for safe and effective tool 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 by explaining parameters. It mentions 'overall width of a table', which hints at the 'width' parameter but does not clarify the meaning of 'filename', 'table_index', or 'width_type'. Without this, the agent lacks understanding of what each parameter represents, leaving significant gaps in parameter semantics.

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 resource ('overall width of a table'), making the purpose immediately understandable. However, it does not differentiate from sibling tools like 'set_table_column_width' or 'set_table_column_widths', which suggests it might be for table-level vs. column-level adjustments, but this distinction is not explicitly stated.

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, such as 'set_table_column_width' or 'format_table'. It lacks context about prerequisites, like requiring an existing table, or exclusions, such as not applying to specific table types. This omission leaves the agent without clear usage direction.

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