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

NameRequiredDescriptionDefault
boldNo
colorNo
end_posYes
filenameYes
font_nameNo
font_sizeNo
italicNo
paragraph_indexYes
start_posYes
underlineNo

Input Schema (JSON Schema)

{ "properties": { "bold": { "default": null, "title": "Bold", "type": "boolean" }, "color": { "default": null, "title": "Color", "type": "string" }, "end_pos": { "title": "End Pos", "type": "integer" }, "filename": { "title": "Filename", "type": "string" }, "font_name": { "default": null, "title": "Font Name", "type": "string" }, "font_size": { "default": null, "title": "Font Size", "type": "integer" }, "italic": { "default": null, "title": "Italic", "type": "boolean" }, "paragraph_index": { "title": "Paragraph Index", "type": "integer" }, "start_pos": { "title": "Start Pos", "type": "integer" }, "underline": { "default": null, "title": "Underline", "type": "boolean" } }, "required": [ "filename", "paragraph_index", "start_pos", "end_pos" ], "type": "object" }

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 )

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