Skip to main content
Glama
GongRzhe

Office Word MCP Server

set_table_cell_padding

Adjust margins within specific table cells in Microsoft Word documents to control spacing and layout precisely.

Instructions

Set padding/margins for a specific table cell.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameYes
table_indexYes
row_indexYes
col_indexYes
topNo
bottomNo
leftNo
rightNo
unitNopoints

Implementation Reference

  • Tool registration using @mcp.tool() decorator. Defines the tool schema via function signature and docstring. Thin synchronous wrapper that delegates to the async implementation in format_tools.
    @mcp.tool()
    def set_table_cell_padding(filename: str, table_index: int, row_index: int, col_index: int,
                               top: float = None, bottom: float = None, left: float = None, 
                               right: float = None, unit: str = "points"):
        """Set padding/margins for a specific table cell."""
        return format_tools.set_table_cell_padding(filename, table_index, row_index, col_index,
                                                   top, bottom, left, right, unit)
  • Primary asynchronous handler function. Performs input validation, loads and modifies the Word document using python-docx, calls low-level helper for padding, saves changes, and returns success message.
    async def set_table_cell_padding(filename: str, table_index: int, row_index: int, col_index: int,
                                     top: Optional[float] = None, bottom: Optional[float] = None, left: Optional[float] = None, 
                                     right: Optional[float] = None, unit: str = "points") -> str:
        """Set padding/margins for a specific table cell.
        
        Args:
            filename: Path to the Word document
            table_index: Index of the table (0-based)
            row_index: Row index (0-based)
            col_index: Column index (0-based)
            top: Top padding in specified units
            bottom: Bottom padding in specified units
            left: Left padding in specified units
            right: Right padding in specified units
            unit: Unit type ("points" or "percent")
        """
        filename = ensure_docx_extension(filename)
        
        # Ensure numeric parameters are the correct type
        try:
            table_index = int(table_index)
            row_index = int(row_index)
            col_index = int(col_index)
            if top is not None:
                top = float(top)
            if bottom is not None:
                bottom = float(bottom)
            if left is not None:
                left = float(left)
            if right is not None:
                right = float(right)
        except (ValueError, TypeError):
            return "Invalid parameter: indices must be integers, padding values must be numbers"
        
        # Validate unit
        valid_units = ["points", "percent"]
        if unit.lower() not in valid_units:
            return f"Invalid unit. Valid options: {', '.join(valid_units)}"
        
        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 row and column indices
            if row_index < 0 or row_index >= len(table.rows):
                return f"Invalid row index. Table has {len(table.rows)} rows (0-{len(table.rows)-1})."
            
            if col_index < 0 or col_index >= len(table.rows[row_index].cells):
                return f"Invalid column index. Row has {len(table.rows[row_index].cells)} cells (0-{len(table.rows[row_index].cells)-1})."
            
            # Convert unit for Word format
            word_unit = "dxa" if unit.lower() == "points" else "pct"
            
            # Apply cell padding
            success = set_cell_padding_by_position(table, row_index, col_index, top, bottom, 
                                                  left, right, word_unit)
            
            if success:
                doc.save(filename)
                padding_desc = []
                if top is not None:
                    padding_desc.append(f"top={top}")
                if bottom is not None:
                    padding_desc.append(f"bottom={bottom}")
                if left is not None:
                    padding_desc.append(f"left={left}")
                if right is not None:
                    padding_desc.append(f"right={right}")
                
                padding_str = ", ".join(padding_desc) if padding_desc else "no padding"
                return f"Cell padding set successfully for table {table_index}, cell ({row_index},{col_index}): {padding_str} {unit}."
            else:
                return f"Failed to set cell padding. Check that indices are valid."
        except Exception as e:
            return f"Failed to set cell padding: {str(e)}"
  • Helper function to locate a table cell by row and column indices and delegate padding setting to set_cell_padding.
    def set_cell_padding_by_position(table, row_index, col_index, top=None, bottom=None, 
                                    left=None, right=None, unit="dxa"):
        """
        Set padding for a specific table cell by position.
        
        Args:
            table: The table containing the cell
            row_index: Row index (0-based)
            col_index: Column index (0-based)
            top: Top padding value
            bottom: Bottom padding value
            left: Left padding value
            right: Right padding value
            unit: Unit type ("dxa" for twentieths of a point, "pct" for percentage)
            
        Returns:
            True if successful, False otherwise
        """
        try:
            if (0 <= row_index < len(table.rows) and 
                0 <= col_index < len(table.rows[row_index].cells)):
                cell = table.rows[row_index].cells[col_index]
                return set_cell_padding(cell, top, bottom, left, right, unit)
            else:
                return False
        except Exception as e:
            print(f"Error setting cell padding by position: {e}")
            return False
  • Low-level helper that directly manipulates the underlying XML of the table cell (using python-docx OxmlElement) to set top, bottom, left, right padding/margins in specified units.
    def set_cell_padding(cell, top=None, bottom=None, left=None, right=None, unit="dxa"):
        """
        Set padding/margins for a table cell.
        
        Args:
            cell: The table cell to format
            top: Top padding value
            bottom: Bottom padding value
            left: Left padding value
            right: Right padding value
            unit: Unit type ("dxa" for twentieths of a point, "pct" for percentage)
            
        Returns:
            True if successful, False otherwise
        """
        try:
            # Get or create table cell properties
            tc_pr = cell._tc.get_or_add_tcPr()
            
            # Remove existing margins
            existing_margins = tc_pr.find(qn('w:tcMar'))
            if existing_margins is not None:
                tc_pr.remove(existing_margins)
            
            # Create margins element if any padding is specified
            if any(p is not None for p in [top, bottom, left, right]):
                margins_element = OxmlElement('w:tcMar')
                
                # Add individual margin elements
                margin_sides = {
                    'w:top': top,
                    'w:bottom': bottom,
                    'w:left': left,
                    'w:right': right
                }
                
                for side, value in margin_sides.items():
                    if value is not None:
                        margin_el = OxmlElement(side)
                        if unit == "dxa":
                            # DXA units (twentieths of a point)
                            margin_el.set(qn('w:w'), str(int(value * 20)))
                            margin_el.set(qn('w:type'), 'dxa')
                        elif unit == "pct":
                            # Percentage
                            margin_el.set(qn('w:w'), str(int(value * 50)))
                            margin_el.set(qn('w:type'), 'pct')
                        else:
                            # Default to DXA
                            margin_el.set(qn('w:w'), str(int(value * 20)))
                            margin_el.set(qn('w:type'), 'dxa')
                        
                        margins_element.append(margin_el)
                
                tc_pr.append(margins_element)
            
            return True
            
        except Exception as e:
            print(f"Error setting cell padding: {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 only states the action without behavioral details. It doesn't disclose whether this is a destructive operation, what permissions are needed, how errors are handled, or what happens if the cell doesn't exist. 'Set' implies mutation, but no safety or side-effect information is given.

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's front-loaded with the core purpose. There's no wasted language or redundancy, making it appropriately concise for a tool with this name.

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 9 parameters, 0% schema coverage, no annotations, and no output schema, the description is insufficient. It lacks critical context about behavior, parameters, error handling, and output, leaving significant gaps for an agent to use it correctly.

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', or padding values represent, their formats, or that 'unit' defaults to 'points'. With 9 parameters (4 required) completely undocumented, this is inadequate.

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 padding/margins') and target ('for a specific table cell'), providing a specific verb+resource combination. However, it doesn't distinguish from sibling tools like 'set_table_cell_alignment' or 'set_table_cell_shading' that also modify table cells, missing explicit differentiation.

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. There's no mention of prerequisites (e.g., document must exist), exclusions, or comparisons to similar sibling tools like 'format_table' or 'set_table_cell_alignment', leaving usage context unclear.

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