Skip to main content
Glama

insert_header_near_text

Add a styled header before or after a specific paragraph in a Word document. Use text content or paragraph index to locate the target, and customize header title, style, and position.

Instructions

Insert a header (with specified style) before or after the target paragraph. Specify by text or paragraph index. Args: filename (str), target_text (str, optional), header_title (str), position ('before' or 'after'), header_style (str, default 'Heading 1'), target_paragraph_index (int, optional).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameYes
header_styleNoHeading 1
header_titleNo
positionNoafter
target_paragraph_indexNo
target_textNo

Implementation Reference

  • Registration of the MCP tool 'insert_header_near_text' using FastMCP @mcp.tool() decorator. Includes input schema in docstring and delegates to content_tools handler.
    async def insert_header_near_text(filename: str, target_text: Optional[str] = None, header_title: Optional[str] = None, position: str = 'after', header_style: str = 'Heading 1', target_paragraph_index: Optional[int] = None):
        """Insert a header (with specified style) before or after the target paragraph. Specify by text or paragraph index. Args: filename (str), target_text (str, optional), header_title (str), position ('before' or 'after'), header_style (str, default 'Heading 1'), target_paragraph_index (int, optional)."""
        return await content_tools.insert_header_near_text_tool(filename, target_text, header_title, position, header_style, target_paragraph_index)
  • Tool handler function in content_tools that wraps and calls the core implementation.
    async def insert_header_near_text_tool(filename: str, target_text: str = None, header_title: str = "", position: str = 'after', header_style: str = 'Heading 1', target_paragraph_index: int = None) -> str:
        """Insert a header (with specified style) before or after the target paragraph. Specify by text or paragraph index."""
        return insert_header_near_text(filename, target_text, header_title, position, header_style, target_paragraph_index)
  • Core implementation of the tool logic: finds target paragraph by text or index, inserts new header paragraph with specified style before/after it, handles TOC skipping, file resolution from path/URL/temp, saves document.
    def insert_header_near_text(doc_path: str, target_text: str = None, header_title: str = "", position: str = 'after', header_style: str = 'Heading 1', target_paragraph_index: int = None) -> str:
        """Insert a header (with specified style) before or after the target paragraph. Specify by text or paragraph index. Skips TOC paragraphs in text search. Supports URLs."""
        success, message, resolved_path, is_temp = resolve_file_path(doc_path)
    
        if not success:
            return message
    
        try:
            doc = Document(resolved_path)
            found = False
            para = None
            if target_paragraph_index is not None:
                if target_paragraph_index < 0 or target_paragraph_index >= len(doc.paragraphs):
                    return f"Invalid target_paragraph_index: {target_paragraph_index}. Document has {len(doc.paragraphs)} paragraphs."
                para = doc.paragraphs[target_paragraph_index]
                found = True
            else:
                for i, p in enumerate(doc.paragraphs):
                    # Skip TOC paragraphs
                    if p.style and p.style.name.lower().startswith("toc"):
                        continue
                    if target_text and target_text in p.text:
                        para = p
                        found = True
                        break
            if not found or para is None:
                return f"Target paragraph not found (by index or text). (TOC paragraphs are skipped in text search)"
            # Save anchor index before insertion
            if target_paragraph_index is not None:
                anchor_index = target_paragraph_index
            else:
                anchor_index = None
                for i, p in enumerate(doc.paragraphs):
                    if p is para:
                        anchor_index = i
                        break
            new_para = doc.add_paragraph(header_title, style=header_style)
            if position == 'before':
                para._element.addprevious(new_para._element)
            else:
                para._element.addnext(new_para._element)
            doc.save(resolved_path)
    
            # Build response message
            if anchor_index is not None:
                result = f"Header '{header_title}' (style: {header_style}) inserted {position} paragraph (index {anchor_index})."
            else:
                result = f"Header '{header_title}' (style: {header_style}) inserted {position} the target paragraph."
    
            # Add temp file info if applicable
            if is_temp:
                result += f" Modified file saved to temporary location: {resolved_path}"
    
            return result
        except Exception as e:
            return f"Failed to insert header: {str(e)}"
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It describes the action ('insert') but lacks details on permissions, error handling, or what happens if the target text is not found. This is a significant gap for a mutation tool with zero 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.

Conciseness5/5

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

The description is appropriately sized and front-loaded, with the first sentence stating the core purpose and subsequent text efficiently detailing parameters without redundancy. Every sentence adds value, making it concise and well-structured.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (6 parameters, mutation operation) and lack of annotations and output schema, the description is partially complete. It covers parameters well but misses behavioral aspects like error handling or return values, leaving gaps for an AI agent to understand full usage.

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

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description adds substantial meaning beyond the input schema, which has 0% description coverage. It explains all six parameters, their purposes (e.g., 'target_text' for specifying by text, 'position' as 'before' or 'after'), and default values like 'header_style' as 'Heading 1', fully compensating for the schema's lack of descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/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 with specific verbs ('insert a header') and resources ('before or after the target paragraph'), distinguishing it from siblings like 'add_heading' by specifying positional insertion near text rather than general addition.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage by mentioning 'specify by text or paragraph index' but does not explicitly state when to use this tool versus alternatives like 'add_heading' or 'insert_line_or_paragraph_near_text', nor does it provide exclusions or prerequisites.

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