Skip to main content
Glama
GongRzhe

Office Word MCP Server

format_text

Apply formatting to specific text ranges in Word documents, including bold, italic, underline, font changes, and color adjustments for precise document styling.

Instructions

Format a specific range of text within a paragraph.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameYes
paragraph_indexYes
start_posYes
end_posYes
boldNo
italicNo
underlineNo
colorNo
font_sizeNo
font_nameNo

Implementation Reference

  • The core handler function that implements the text formatting logic: loads the document, validates indices, clears and rebuilds runs with specified formatting (bold, italic, underline, color, font), and saves the document.
    async def format_text(filename: str, paragraph_index: int, start_pos: int, end_pos: int, 
                         bold: Optional[bool] = None, italic: Optional[bool] = None, 
                         underline: Optional[bool] = None, color: Optional[str] = None,
                         font_size: Optional[int] = None, font_name: Optional[str] = None) -> str:
        """Format a specific range of text within a paragraph.
        
        Args:
            filename: Path to the Word document
            paragraph_index: Index of the paragraph (0-based)
            start_pos: Start position within the paragraph text
            end_pos: End position within the paragraph text
            bold: Set text bold (True/False)
            italic: Set text italic (True/False)
            underline: Set text underlined (True/False)
            color: Text color (e.g., 'red', 'blue', etc.)
            font_size: Font size in points
            font_name: Font name/family
        """
        filename = ensure_docx_extension(filename)
        
        # Ensure numeric parameters are the correct type
        try:
            paragraph_index = int(paragraph_index)
            start_pos = int(start_pos)
            end_pos = int(end_pos)
            if font_size is not None:
                font_size = int(font_size)
        except (ValueError, TypeError):
            return "Invalid parameter: paragraph_index, start_pos, end_pos, and font_size must be integers"
        
        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 paragraph index
            if paragraph_index < 0 or paragraph_index >= len(doc.paragraphs):
                return f"Invalid paragraph index. Document has {len(doc.paragraphs)} paragraphs (0-{len(doc.paragraphs)-1})."
            
            paragraph = doc.paragraphs[paragraph_index]
            text = paragraph.text
            
            # Validate text positions
            if start_pos < 0 or end_pos > len(text) or start_pos >= end_pos:
                return f"Invalid text positions. Paragraph has {len(text)} characters."
            
            # Get the text to format
            target_text = text[start_pos:end_pos]
            
            # Clear existing runs and create three runs: before, target, after
            for run in paragraph.runs:
                run.clear()
            
            # Add text before target
            if start_pos > 0:
                run_before = paragraph.add_run(text[:start_pos])
            
            # Add target text with formatting
            run_target = paragraph.add_run(target_text)
            if bold is not None:
                run_target.bold = bold
            if italic is not None:
                run_target.italic = italic
            if underline is not None:
                run_target.underline = underline
            if color:
                # Define common RGB colors
                color_map = {
                    'red': RGBColor(255, 0, 0),
                    'blue': RGBColor(0, 0, 255),
                    'green': RGBColor(0, 128, 0),
                    'yellow': RGBColor(255, 255, 0),
                    'black': RGBColor(0, 0, 0),
                    'gray': RGBColor(128, 128, 128),
                    'white': RGBColor(255, 255, 255),
                    'purple': RGBColor(128, 0, 128),
                    'orange': RGBColor(255, 165, 0)
                }
                
                try:
                    if color.lower() in color_map:
                        # Use predefined RGB color
                        run_target.font.color.rgb = color_map[color.lower()]
                    else:
                        # Try to set color by name
                        run_target.font.color.rgb = RGBColor.from_string(color)
                except Exception as e:
                    # If all else fails, default to black
                    run_target.font.color.rgb = RGBColor(0, 0, 0)
            if font_size:
                run_target.font.size = Pt(font_size)
            if font_name:
                run_target.font.name = font_name
            
            # Add text after target
            if end_pos < len(text):
                run_after = paragraph.add_run(text[end_pos:])
            
            doc.save(filename)
            return f"Text '{target_text}' formatted successfully in paragraph {paragraph_index}."
        except Exception as e:
            return f"Failed to format text: {str(e)}"
  • MCP tool registration decorator (@mcp.tool()) with a thin wrapper that delegates execution to the async format_tools.format_text function.
    @mcp.tool()
    def format_text(filename: str, paragraph_index: int, start_pos: int, end_pos: int,
                   bold: bool = None, italic: bool = None, underline: bool = None,
                   color: str = None, font_size: int = None, font_name: str = None):
        """Format a specific range of text within a paragraph."""
        return format_tools.format_text(
            filename, paragraph_index, start_pos, end_pos, bold, italic, 
            underline, color, font_size, font_name
        )
  • Exports the format_text function from format_tools.py for import in main.py.
    from word_document_server.tools.format_tools import (
        format_text, create_custom_style, format_table
    )
  • Detailed docstring defining input parameters and their types/descriptions, serving as the tool schema.
                     font_size: Optional[int] = None, font_name: Optional[str] = None) -> str:
    """Format a specific range of text within a paragraph.
    
    Args:
        filename: Path to the Word document
        paragraph_index: Index of the paragraph (0-based)
        start_pos: Start position within the paragraph text
        end_pos: End position within the paragraph text
        bold: Set text bold (True/False)
        italic: Set text italic (True/False)
        underline: Set text underlined (True/False)
        color: Text color (e.g., 'red', 'blue', etc.)
        font_size: Font size in points
        font_name: Font name/family
    """

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