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

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