Skip to main content
Glama

add_heading

Add structured headings to Microsoft Word documents, specifying text and level for improved organization and readability. Helps manage content hierarchy efficiently.

Instructions

Add a heading to a Word document.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameYes
levelNo
textYes

Implementation Reference

  • Primary MCP tool handler for 'add_heading' registered with @mcp.tool() decorator. Implements the core logic using document resolver, heading styles, and fallback formatting.
    @mcp.tool()
    async def add_heading(filename: str, text: str, level: int = 1):
        """Add a heading to a Word document."""
        try:
            # Validate level
            if level < 1 or level > 9:
                return f"Invalid heading level: {level}. Level must be between 1 and 9."
            
            # Use resolver to find the document
            doc, resolved_path = load_document_with_resolver(filename)
            
            # Add the heading
            from word_document_server.core.styles import ensure_heading_style
            ensure_heading_style(doc)
            
            try:
                heading = doc.add_heading(text, level=level)
            except Exception:
                # Fallback to direct formatting if style fails
                from docx.shared import Pt
                paragraph = doc.add_paragraph(text)
                paragraph.style = doc.styles['Normal']
                run = paragraph.runs[0]
                run.bold = True
                if level == 1:
                    run.font.size = Pt(16)
                elif level == 2:
                    run.font.size = Pt(14)
                else:
                    run.font.size = Pt(12)
            
            # Save the document
            save_document_with_resolver(doc, filename, resolved_path)
            return f"Heading '{text}' (level {level}) added to {filename}"
            
        except FileNotFoundError as e:
            return str(e)
        except Exception as e:
            return f"Failed to add heading: {str(e)}"
  • Supporting helper function for adding headings, with file validation and write checks. Similar logic to MCP handler but without resolver integration.
    async def add_heading(filename: str, text: str, level: int = 1) -> str:
        """Add a heading to a Word document.
        
        Args:
            filename: Path to the Word document
            text: Heading text
            level: Heading level (1-9, where 1 is the highest level)
        """
        filename = ensure_docx_extension(filename)
        
        # Ensure level is converted to integer
        try:
            level = int(level)
        except (ValueError, TypeError):
            return "Invalid parameter: level must be an integer between 1 and 9"
        
        # Validate level range
        if level < 1 or level > 9:
            return f"Invalid heading level: {level}. Level must be between 1 and 9."
        
        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:
            # Suggest creating a copy
            return f"Cannot modify document: {error_message}. Consider creating a copy first or creating a new document."
        
        try:
            doc = Document(filename)
            
            # Ensure heading styles exist
            ensure_heading_style(doc)
            
            # Try to add heading with style
            try:
                heading = doc.add_heading(text, level=level)
                doc.save(filename)
                return f"Heading '{text}' (level {level}) added to {filename}"
            except Exception as style_error:
                # If style-based approach fails, use direct formatting
                paragraph = doc.add_paragraph(text)
                paragraph.style = doc.styles['Normal']
                run = paragraph.runs[0]
                run.bold = True
                # Adjust size based on heading level
                if level == 1:
                    run.font.size = Pt(16)
                elif level == 2:
                    run.font.size = Pt(14)
                else:
                    run.font.size = Pt(12)
                
                doc.save(filename)
                return f"Heading '{text}' added to {filename} with direct formatting (style not available)"
        except Exception as e:
            return f"Failed to add heading: {str(e)}"
  • Exports the add_heading function from content_tools for use across the tools package.
    from word_document_server.tools.content_tools import (
        add_heading, add_paragraph, add_table, add_picture,
        add_page_break, add_table_of_contents, delete_paragraph,
        search_and_replace
    )
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries full burden for behavioral disclosure. 'Add a heading' implies a write/mutation operation, but the description doesn't specify where the heading is added (e.g., at end, at cursor position), whether it modifies an existing document or creates a new one, what permissions are required, or what happens on failure. This leaves significant behavioral gaps for a mutation tool.

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, clear sentence that states the core purpose without unnecessary words. It's appropriately sized for a simple tool and front-loads the essential information efficiently.

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?

For a mutation tool with 3 parameters, 0% schema coverage, no annotations, and no output schema, the description is inadequate. It doesn't explain parameter usage, behavioral constraints, error conditions, or what constitutes success. Given the complexity of document editing and multiple sibling tools, more context is needed for reliable agent operation.

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?

With 0% schema description coverage, the schema provides only parameter names and types without explanations. The description doesn't mention any parameters, so it adds no semantic value beyond what's inferred from parameter names (e.g., 'filename' for document, 'text' for heading content, 'level' possibly for heading hierarchy). This meets the baseline for minimal parameter information when schema coverage is low.

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 ('Add a heading') and target resource ('to a Word document'), which is specific and unambiguous. However, it doesn't differentiate from sibling tools like 'add_paragraph' or 'insert_header_near_text' that also add content to documents, leaving some ambiguity about when to choose this specific tool.

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. With many sibling tools for document modification (e.g., add_paragraph, add_table, insert_header_near_text), there's no indication of when a heading is appropriate versus other content types or positioning methods, leaving the agent to guess based on tool names alone.

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