Skip to main content
Glama

insert_line_or_paragraph_near_text

Add a line or paragraph with specific formatting before or after a target paragraph in Microsoft Word documents. Specify by text or paragraph index for precise content placement.

Instructions

Insert a new line or paragraph (with specified or matched style) before or after the target paragraph. Specify by text or paragraph index. Args: filename (str), target_text (str, optional), line_text (str), position ('before' or 'after'), line_style (str, optional), target_paragraph_index (int, optional).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameYes
line_styleNo
line_textNo
positionNoafter
target_paragraph_indexNo
target_textNo

Implementation Reference

  • MCP tool registration using @mcp.tool() decorator. Defines input schema via function parameters and docstring. Delegates execution to content_tools.insert_line_or_paragraph_near_text_tool.
    async def insert_line_or_paragraph_near_text(filename: str, target_text: Optional[str] = None, line_text: Optional[str] = None, position: str = 'after', line_style: Optional[str] = None, target_paragraph_index: Optional[int] = None):
        """
        Insert a new line or paragraph (with specified or matched style) before or after the target paragraph. Specify by text or paragraph index. Args: filename (str), target_text (str, optional), line_text (str), position ('before' or 'after'), line_style (str, optional), target_paragraph_index (int, optional).
        """
        return await content_tools.insert_line_or_paragraph_near_text_tool(filename, target_text, line_text, position, line_style, target_paragraph_index)
  • Handler function in content_tools.py that receives tool call and delegates to the core utility function insert_line_or_paragraph_near_text in document_utils.py.
    async def insert_line_or_paragraph_near_text_tool(filename: str, target_text: str = None, line_text: str = "", position: str = 'after', line_style: str = None, target_paragraph_index: int = None) -> str:
        """Insert a new line or paragraph (with specified or matched style) before or after the target paragraph. Specify by text or paragraph index."""
        return insert_line_or_paragraph_near_text(filename, target_text, line_text, position, line_style, target_paragraph_index)
  • Core implementation: loads document, locates target paragraph by text or index (skipping TOC), creates new paragraph with matching/specified style, inserts before/after using low-level XML element manipulation (addprevious/addnext), saves the document.
    def insert_line_or_paragraph_near_text(doc_path: str, target_text: str = None, line_text: str = "", position: str = 'after', line_style: str = None, target_paragraph_index: int = None) -> str:
        """
        Insert a new line or paragraph (with specified or matched style) before or after the target paragraph.
        You can specify the target by text (first match) or by paragraph index.
        Skips paragraphs whose style name starts with 'TOC' if using text search.
        """
        import os
        from docx import Document
        if not os.path.exists(doc_path):
            return f"Document {doc_path} does not exist"
        try:
            doc = Document(doc_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
            # Determine style: use provided or match target
            style = line_style if line_style else para.style
            new_para = doc.add_paragraph(line_text, style=style)
            if position == 'before':
                para._element.addprevious(new_para._element)
            else:
                para._element.addnext(new_para._element)
            doc.save(doc_path)
            if anchor_index is not None:
                return f"Line/paragraph inserted {position} paragraph (index {anchor_index}) with style '{style}'."
            else:
                return f"Line/paragraph inserted {position} the target paragraph with style '{style}'."
        except Exception as e:
            return f"Failed to insert line/paragraph: {str(e)}"
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions style matching and positional insertion, but doesn't cover critical aspects: whether this modifies the original document permanently, what permissions are required, error handling for invalid targets, or what happens if multiple paragraphs match the target text. For a mutation tool with zero annotation coverage, this is insufficient.

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 efficiently structured in two sentences: first states the core functionality, second lists parameters. No wasted words, though it could be more front-loaded by emphasizing the primary action before parameter details. Every sentence adds value.

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 document mutation tool with 6 parameters, 0% schema coverage, no annotations, and no output schema, the description is incomplete. It doesn't explain return values, error conditions, style matching mechanics, or how conflicts between target_text and target_paragraph_index are resolved. The agent lacks sufficient context to use this tool reliably.

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 lists all 6 parameters with brief explanations, providing essential semantics like 'before or after' for position and 'optional' flags. However, it doesn't explain parameter interactions (e.g., target_text vs target_paragraph_index), format requirements, or constraints beyond what's obvious from parameter names.

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: 'Insert a new line or paragraph (with specified or matched style) before or after the target paragraph.' It specifies the verb (insert), resource (line/paragraph), and scope (near target text). However, it doesn't explicitly differentiate from siblings like 'add_paragraph' or 'insert_header_near_text' beyond mentioning style matching.

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 when this tool is preferred over 'add_paragraph' or 'insert_header_near_text', nor does it specify prerequisites or exclusions. The agent must infer usage from the tool name and parameter list 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