Skip to main content
Glama

format_text

Format text within a specific paragraph range in Word documents. Customize font style, color, size, and formatting (bold, italic, underline) using precise inputs like paragraph index and position.

Instructions

Format a specific range of text within a paragraph.

IMPORTANT: When specifying the color parameter, use a hex code WITHOUT the leading # (e.g., '0070C0', not '#0070C0').

Input Schema

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

Implementation Reference

  • Core handler function that executes the format_text tool logic: loads the DOCX, finds the paragraph, recreates runs for the specified range, applies bold/italic/underline/color/font formatting, 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() defining the tool interface and delegating to the core handler in format_tools.
    @mcp.tool()
    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):
        """Format a specific range of text within a paragraph.
        
        IMPORTANT: When specifying the color parameter, use a hex code WITHOUT the leading # (e.g., '0070C0', not '#0070C0').
        """
        return await format_tools.format_text(
            filename, paragraph_index, start_pos, end_pos, bold, italic, 
            underline, color, font_size, font_name
        )
  • Tool description and parameter notes in the docstring, which serves as the schema documentation for MCP.
    """Format a specific range of text within a paragraph.
    
    IMPORTANT: When specifying the color parameter, use a hex code WITHOUT the leading # (e.g., '0070C0', not '#0070C0').
    """
  • Export of format_text function for use in main.py registration.
    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. It states the tool performs formatting (a mutation operation) but doesn't clarify permissions needed, whether changes are reversible, potential side effects on document structure, or error handling. The color format note is helpful but insufficient for a mutation tool with no annotation coverage.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately concise with two sentences: one stating the purpose and one providing a key parameter constraint. It's front-loaded with the core function, and the IMPORTANT note is justified as it prevents a common formatting error. No extraneous information is included.

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 (10 parameters, mutation operation, no annotations, no output schema), the description is incomplete. It lacks details on behavioral traits, most parameter meanings, return values, and usage context. While the color format note is valuable, it doesn't compensate for the overall gaps in a tool that modifies document content.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/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. It adds critical semantic guidance for the 'color' parameter (hex code format without '#'), which clarifies beyond the schema's generic string type. However, it doesn't explain the other 9 parameters (e.g., what 'paragraph_index' refers to, how positions are measured), leaving significant gaps in parameter understanding.

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 tool's purpose: 'Format a specific range of text within a paragraph.' This specifies the verb ('Format'), resource ('range of text'), and scope ('within a paragraph'). However, it doesn't explicitly differentiate from sibling tools like 'format_table' or 'create_custom_style', which also handle formatting in different contexts.

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 sibling tools like 'format_table' for table formatting or 'create_custom_style' for reusable styles, nor does it specify prerequisites such as needing an existing document or paragraph. The only usage note is about color format, which is parameter-specific rather than contextual.

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