Skip to main content
Glama

format_table

Apply custom borders, shading, and structured formatting to tables in Word documents. Specify table index, header row, and design preferences to enhance document clarity and presentation.

Instructions

Format a table with borders, shading, and structure.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
border_styleNo
filenameYes
has_header_rowNo
shadingNo
table_indexYes

Implementation Reference

  • Main handler function that loads the document, validates the table index, applies table styling using the helper function, saves the document, and returns a status message.
    async def format_table(filename: str, table_index: int, 
                          has_header_row: Optional[bool] = None,
                          border_style: Optional[str] = None,
                          shading: Optional[List[List[str]]] = None) -> str:
        """Format a table with borders, shading, and structure.
        
        Args:
            filename: Path to the Word document
            table_index: Index of the table (0-based)
            has_header_row: If True, formats the first row as a header
            border_style: Style for borders ('none', 'single', 'double', 'thick')
            shading: 2D list of cell background colors (by row and column)
        """
        filename = ensure_docx_extension(filename)
        
        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 formatting
            success = apply_table_style(table, has_header_row, border_style, shading)
            
            if success:
                doc.save(filename)
                return f"Table at index {table_index} formatted successfully."
            else:
                return f"Failed to format table at index {table_index}."
        except Exception as e:
            return f"Failed to format table: {str(e)}"
  • MCP tool registration using @mcp.tool() decorator. Defines the tool schema via parameters and docstring, and delegates execution to the implementation in format_tools.py.
    @mcp.tool()
    async def format_table(filename: str, table_index: int, has_header_row: Optional[bool] = None,
                    border_style: Optional[str] = None, shading: Optional[List[str]] = None):
        """Format a table with borders, shading, and structure."""
        return await format_tools.format_table(filename, table_index, has_header_row, border_style, shading)
  • Core helper function that performs the actual table formatting: makes header bold, applies borders to cells, and sets cell shading using low-level docx XML manipulation.
    def apply_table_style(table, has_header_row=False, border_style=None, shading=None):
        """
        Apply formatting to a table.
        
        Args:
            table: The table to format
            has_header_row: If True, formats the first row as a header
            border_style: Style for borders ('none', 'single', 'double', 'thick')
            shading: 2D list of cell background colors (by row and column)
            
        Returns:
            True if successful, False otherwise
        """
        try:
            # Format header row if requested
            if has_header_row and table.rows:
                header_row = table.rows[0]
                for cell in header_row.cells:
                    for paragraph in cell.paragraphs:
                        if paragraph.runs:
                            for run in paragraph.runs:
                                run.bold = True
            
            # Apply border style if specified
            if border_style:
                val_map = {
                    'none': 'nil',
                    'single': 'single',
                    'double': 'double',
                    'thick': 'thick'
                }
                val = val_map.get(border_style.lower(), 'single')
                
                # Apply to all cells
                for row in table.rows:
                    for cell in row.cells:
                        set_cell_border(
                            cell,
                            top=True,
                            bottom=True,
                            left=True,
                            right=True,
                            val=val,
                            color="000000"
                        )
            
            # Apply cell shading if specified
            if shading:
                for i, row_colors in enumerate(shading):
                    if i >= len(table.rows):
                        break
                    for j, color in enumerate(row_colors):
                        if j >= len(table.rows[i].cells):
                            break
                        try:
                            # Apply shading to cell
                            cell = table.rows[i].cells[j]
                            shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{color}"/>')
                            cell._tc.get_or_add_tcPr().append(shading_elm)
                        except:
                            # Skip if color format is invalid
                            pass
            
            return True
        except Exception:
            return False
  • Exposes the format_table function from format_tools.py for import in the main server file.
    from word_document_server.tools.format_tools import (
        format_text, create_custom_style, format_table
    )
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. 'Format' implies a mutation operation, but the description doesn't specify whether this requires specific permissions, if changes are reversible, what happens to existing formatting, or the response format. It mentions 'borders, shading, and structure' but lacks details on how these are applied or any constraints (e.g., rate limits, side effects).

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 purpose ('Format a table') and lists key features ('borders, shading, and structure') without unnecessary words. Every part earns its place, making it highly concise and well-structured.

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 (5 parameters, mutation operation), lack of annotations, and no output schema, the description is incomplete. It doesn't cover parameter meanings, behavioral traits, or return values, leaving significant gaps for an AI agent to understand how to invoke the tool correctly. It's inadequate for a tool with multiple parameters and potential side effects.

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 for undocumented parameters. It mentions 'borders, shading, and structure', which loosely maps to 'border_style' and 'shading', but doesn't explain the other parameters ('filename', 'table_index', 'has_header_row') or provide any syntax, format, or usage details. The description adds minimal value beyond the schema's property 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 ('Format') and the resource ('a table') with specific formatting aspects ('borders, shading, and structure'). It distinguishes from siblings like 'add_table' or 'modify_table_cell' by focusing on visual formatting rather than creation or content modification. However, it doesn't explicitly differentiate from potential formatting in 'format_text', which might handle text-level formatting.

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., an existing table), exclusions (e.g., not for text formatting), or direct comparisons to siblings like 'modify_table_cell' or 'format_text'. Usage is implied only by the tool name and description, with no explicit context.

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

Related 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/franlealp1/mcp-word'

If you have feedback or need assistance with the MCP directory API, please join our Discord server