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)}"

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