Skip to main content
Glama
GongRzhe

Office Word MCP Server

insert_line_or_paragraph_near_text

Add text before or after specific paragraphs in Word documents by targeting text or paragraph index, with optional style matching.

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
target_textNo
line_textNo
positionNoafter
line_styleNo
target_paragraph_indexNo

Implementation Reference

  • MCP tool registration using @mcp.tool() decorator. Includes input schema via docstring describing arguments and their types.
    @mcp.tool()
    def insert_line_or_paragraph_near_text(filename: str, target_text: str = None, line_text: str = None, position: str = 'after', line_style: str = None, target_paragraph_index: 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 content_tools.insert_line_or_paragraph_near_text_tool(filename, target_text, line_text, position, line_style, target_paragraph_index)
  • Async handler function for the tool, which delegates to the core implementation in document_utils.
    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 function that performs the actual document manipulation: finds target paragraph, inserts new paragraph with matching style before/after, handles TOC skipping, 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?

No annotations are provided, so the description carries the full burden. It mentions the action ('insert') and optional style matching, but it doesn't disclose behavioral traits such as whether the insertion modifies the document permanently, what happens if the target text isn't found, error handling, or permissions required. 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.

Conciseness4/5

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

The description is appropriately sized with two sentences: the first states the purpose and key parameters, and the second lists args. It's front-loaded with the core action, but the arg list is somewhat redundant with the schema and could be more integrated for efficiency.

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?

Given the complexity (6 parameters, mutation operation), lack of annotations, and no output schema, the description is incomplete. It covers the basic action and parameters but misses critical context like error conditions, return values, side effects, and how it differs from sibling tools, making it inadequate for safe and effective use.

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 hints (e.g., 'optional', 'before or after'), adding some meaning beyond the bare schema. However, it doesn't explain parameter interactions (e.g., using target_text vs. target_paragraph_index), valid values for line_style, or format details, leaving gaps in understanding.

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 with specific verbs ('insert a new line or paragraph') and resources ('before or after the target paragraph'), and it distinguishes the action from siblings like 'add_paragraph' by specifying positional insertion near text. However, it doesn't explicitly differentiate from tools like 'insert_header_near_text' or 'insert_numbered_list_near_text' beyond the line/paragraph focus.

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' and listing optional parameters, which suggests when to use certain arguments. However, it lacks explicit guidance on when to choose this tool over alternatives like 'add_paragraph' or 'insert_header_near_text', and it doesn't mention prerequisites or exclusions.

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

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