Skip to main content
Glama
GongRzhe

Office Word MCP Server

create_custom_style

Define custom text formatting styles in Microsoft Word documents to maintain consistent formatting across your document.

Instructions

Create a custom style in the document.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameYes
style_nameYes
boldNo
italicNo
font_sizeNo
font_nameNo
colorNo
base_styleNo

Implementation Reference

  • The primary handler function implementing the create_custom_style tool. Loads the document, validates access, constructs font properties, calls the create_style helper from core.styles, saves the document, and returns status.
    async def create_custom_style(filename: str, style_name: str, 
                                 bold: Optional[bool] = None, italic: Optional[bool] = None,
                                 font_size: Optional[int] = None, font_name: Optional[str] = None,
                                 color: Optional[str] = None, base_style: Optional[str] = None) -> str:
        """Create a custom style in the document.
        
        Args:
            filename: Path to the Word document
            style_name: Name for the new style
            bold: Set text bold (True/False)
            italic: Set text italic (True/False)
            font_size: Font size in points
            font_name: Font name/family
            color: Text color (e.g., 'red', 'blue')
            base_style: Optional existing style to base this on
        """
        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)
            
            # Build font properties dictionary
            font_properties = {}
            if bold is not None:
                font_properties['bold'] = bold
            if italic is not None:
                font_properties['italic'] = italic
            if font_size is not None:
                font_properties['size'] = font_size
            if font_name is not None:
                font_properties['name'] = font_name
            if color is not None:
                font_properties['color'] = color
            
            # Create the style
            new_style = create_style(
                doc, 
                style_name, 
                WD_STYLE_TYPE.PARAGRAPH, 
                base_style=base_style,
                font_properties=font_properties
            )
            
            doc.save(filename)
            return f"Style '{style_name}' created successfully."
        except Exception as e:
            return f"Failed to create style: {str(e)}"
  • MCP tool registration using @mcp.tool() decorator. This thin wrapper delegates execution to the handler in format_tools.create_custom_style.
    @mcp.tool()
    def create_custom_style(filename: str, style_name: str, bold: bool = None, 
                          italic: bool = None, font_size: int = None, 
                          font_name: str = None, color: str = None, 
                          base_style: str = None):
        """Create a custom style in the document."""
        return format_tools.create_custom_style(
            filename, style_name, bold, italic, font_size, font_name, color, base_style
        )
  • Supporting utility function that actually creates and configures the new style object in the docx document, handling font and paragraph properties.
    def create_style(doc, style_name, style_type, base_style=None, font_properties=None, paragraph_properties=None):
        """
        Create a new style in the document.
        
        Args:
            doc: Document object
            style_name: Name for the new style
            style_type: Type of style (WD_STYLE_TYPE)
            base_style: Optional base style to inherit from
            font_properties: Dictionary of font properties (bold, italic, size, name, color)
            paragraph_properties: Dictionary of paragraph properties (alignment, spacing)
            
        Returns:
            The created style
        """
        from docx.shared import Pt
        
        try:
            # Check if style already exists
            style = doc.styles.get_by_id(style_name, WD_STYLE_TYPE.PARAGRAPH)
            return style
        except:
            # Create new style
            new_style = doc.styles.add_style(style_name, style_type)
            
            # Set base style if specified
            if base_style:
                new_style.base_style = doc.styles[base_style]
            
            # Set font properties
            if font_properties:
                font = new_style.font
                if 'bold' in font_properties:
                    font.bold = font_properties['bold']
                if 'italic' in font_properties:
                    font.italic = font_properties['italic']
                if 'size' in font_properties:
                    font.size = Pt(font_properties['size'])
                if 'name' in font_properties:
                    font.name = font_properties['name']
                if 'color' in font_properties:
                    from docx.shared import RGBColor
                    
                    # 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)
                    }
                    
                    color_value = font_properties['color']
                    try:
                        # Handle string color names
                        if isinstance(color_value, str) and color_value.lower() in color_map:
                            font.color.rgb = color_map[color_value.lower()]
                        # Handle RGBColor objects
                        elif hasattr(color_value, 'rgb'):
                            font.color.rgb = color_value
                        # Try to parse as RGB string
                        elif isinstance(color_value, str):
                            font.color.rgb = RGBColor.from_string(color_value)
                        # Use directly if it's already an RGB value
                        else:
                            font.color.rgb = color_value
                    except Exception as e:
                        # Fallback to black if all else fails
                        font.color.rgb = RGBColor(0, 0, 0)
            
            # Set paragraph properties
            if paragraph_properties:
                if 'alignment' in paragraph_properties:
                    new_style.paragraph_format.alignment = paragraph_properties['alignment']
                if 'spacing' in paragraph_properties:
                    new_style.paragraph_format.line_spacing = paragraph_properties['spacing']
            
            return new_style

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