Skip to main content
Glama
GongRzhe

Office Word MCP Server

set_table_cell_alignment

Adjust text alignment within specific table cells in Microsoft Word documents to control horizontal and vertical positioning for improved document formatting.

Instructions

Set text alignment for a specific table cell.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameYes
table_indexYes
row_indexYes
col_indexYes
horizontalNoleft
verticalNotop

Implementation Reference

  • Primary asynchronous handler implementing the tool logic: validates parameters, loads and saves the document, verifies table and cell indices, calls core helper, and returns formatted success/error message.
    async def set_table_cell_alignment(filename: str, table_index: int, row_index: int, col_index: int,
                                     horizontal: str = "left", vertical: str = "top") -> str:
        """Set text alignment 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)
            horizontal: Horizontal alignment ("left", "center", "right", "justify")
            vertical: Vertical alignment ("top", "center", "bottom")
        """
        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)
        except (ValueError, TypeError):
            return "Invalid parameter: table_index, row_index, and col_index must be integers"
        
        # Validate alignment parameters
        valid_horizontal = ["left", "center", "right", "justify"]
        valid_vertical = ["top", "center", "bottom"]
        
        if horizontal.lower() not in valid_horizontal:
            return f"Invalid horizontal alignment. Valid options: {', '.join(valid_horizontal)}"
        
        if vertical.lower() not in valid_vertical:
            return f"Invalid vertical alignment. Valid options: {', '.join(valid_vertical)}"
        
        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 cell alignment
            success = set_cell_alignment_by_position(table, row_index, col_index, horizontal, vertical)
            
            if success:
                doc.save(filename)
                return f"Cell alignment set successfully for table {table_index}, cell ({row_index},{col_index}) to {horizontal}/{vertical}."
            else:
                return f"Failed to set cell alignment. Check that indices are valid."
        except Exception as e:
            return f"Failed to set cell alignment: {str(e)}"
  • MCP tool registration using FastMCP @mcp.tool() decorator. Provides synchronous wrapper with argument types and docstring schema, delegating to the async handler in format_tools.
    @mcp.tool()
    def set_table_cell_alignment(filename: str, table_index: int, row_index: int, col_index: int,
                               horizontal: str = "left", vertical: str = "top"):
        """Set text alignment for a specific table cell."""
        return format_tools.set_table_cell_alignment(filename, table_index, row_index, col_index, horizontal, vertical)
  • Core helper function that validates row/col indices, retrieves the target table cell, and applies alignment via low-level set_cell_alignment function.
    def set_cell_alignment_by_position(table, row_index, col_index, horizontal="left", vertical="top"):
        """
        Set text alignment for a specific cell by position.
        
        Args:
            table: The table containing the cell
            row_index: Row index (0-based)
            col_index: Column index (0-based)
            horizontal: Horizontal alignment ("left", "center", "right", "justify")
            vertical: Vertical alignment ("top", "center", "bottom")
            
        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_alignment(cell, horizontal, vertical)
            else:
                return False
        except Exception as e:
            print(f"Error setting cell alignment by position: {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 disclosing behavioral traits. It doesn't mention whether this is a mutation (likely), what permissions are needed, if changes are reversible, error conditions, or side effects on document structure.

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 front-loads the core action. There's no wasted wording, making it easy to parse, though it may be overly terse for the tool's complexity.

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 6 parameters with 0% schema coverage, no annotations, and no output schema, the description is incomplete. It lacks details on parameter meanings, behavioral context, return values, and error handling, which are essential for a mutation tool with multiple inputs.

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 semantics. It doesn't explain what 'filename', 'table_index', or alignment values mean, their formats, or constraints beyond the schema's basic types and defaults.

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 verb ('Set') and resource ('text alignment for a specific table cell'), making the purpose unambiguous. It distinguishes from siblings like 'set_table_alignment_all' by specifying 'cell' rather than whole-table operations, though it doesn't explicitly contrast with them.

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?

No guidance is provided on when to use this tool versus alternatives like 'format_table_cell_text' or 'set_table_alignment_all'. The description implies usage for cell-level alignment but offers no context about prerequisites, dependencies, or typical workflows.

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