Skip to main content
Glama

edit_docx_insert

Insert new paragraphs into Microsoft Word documents at specified positions or the end, generating a diff of changes made.

Instructions

Insert new paragraphs into a docx file. Accepts a list of inserts with text and optional paragraph index. Each insert creates a new paragraph at the specified position. If paragraph_index is not specified, the paragraph is added at the end. When multiple inserts target the same paragraph_index, they are inserted in order. Returns a git-style diff showing the changes made.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesAbsolute path to file to edit. It should be under your current working directory.
insertsYesSequence of paragraphs to insert.

Implementation Reference

  • The main asynchronous handler function that loads the DOCX document, sorts and inserts new paragraphs at specified positions (before tables or paragraphs), updates the element list, saves the file, generates and returns a unified diff of changes.
    async def edit_docx_insert(path: str, inserts: list[Dict[str, str | int]]) -> str:
        """Insert new paragraphs into a docx file.
        
        Args:
            path: path to target docx file
            inserts: list of dictionaries containing text and optional paragraph_index
                [{'text': 'text to insert', 'paragraph_index': 0}, ...]
                text: text to insert as a new paragraph (required)
                paragraph_index: 0-based index of the paragraph before which to insert (optional)
        Returns:
            str: A git-style diff showing the changes made
        """
        if not await validate_path(path):
            raise ValueError(f"Not a docx file: {path}")
        
        doc = Document(path)
        original = await read_docx(path)
    
        # パラグラフとテーブルを順番に収集
        elements = []
        paragraph_count = 0
        table_count = 0
        for element in doc._body._body:
            if element.tag == W_P:
                elements.append(('p', doc.paragraphs[paragraph_count]))
                paragraph_count += 1
            elif element.tag == W_TBL:
                elements.append(('tbl', doc.tables[table_count]))
                table_count += 1
    
        # 挿入位置でソート(同じ位置への挿入は指定順を保持)
        sorted_inserts = sorted(
            enumerate(inserts),
            key=lambda x: (x[1].get('paragraph_index', float('inf')), x[0])
        )
    
        # 各挿入を処理
        for _, insert in sorted_inserts:
            text = insert['text']
            paragraph_index = insert.get('paragraph_index')
    
            # 新しい段落を作成
            new_paragraph = doc.add_paragraph(text)
    
            if paragraph_index is None:
                # 文書の最後に追加
                doc.element.body.append(new_paragraph._element)
                elements.append(('p', new_paragraph))
            elif paragraph_index >= len(elements):
                raise ValueError(f"Paragraph index out of range: {paragraph_index}")
            else:
                # 指定位置に挿入
                element_type, element = elements[paragraph_index]
                if element_type == 'p':
                    element._element.addprevious(new_paragraph._element)
                elif element_type == 'tbl':
                    element._element.addprevious(new_paragraph._element)
                
                # elementsリストを更新(後続の挿入のために必要)
                elements.insert(paragraph_index, ('p', new_paragraph))
    
        doc.save(path)
        
        # 差分の生成
        modified = await read_docx(path)
        diff_lines = []
        original_lines = [line for line in original.split("\n") if line.strip()]
        modified_lines = [line for line in modified.split("\n") if line.strip()]
        
        for line in difflib.unified_diff(original_lines, modified_lines, n=0):
            if line.startswith('---') or line.startswith('+++'):
                continue
            if line.startswith('-') or line.startswith('+'):
                diff_lines.append(line)
        
        return "\n".join(diff_lines) if diff_lines else ""
  • Defines the Tool object with name, description, and inputSchema for parameter validation: path (string) and inserts (array of objects with text (required) and optional paragraph_index (integer)).
    EDIT_DOCX_INSERT = types.Tool(
        name="edit_docx_insert",
        description=(
            "Insert new paragraphs into a docx file. "
            "Accepts a list of inserts with text and optional paragraph index. "
            "Each insert creates a new paragraph at the specified position. "
            "If paragraph_index is not specified, the paragraph is added at the end. "
            "When multiple inserts target the same paragraph_index, they are inserted in order. "
            "Returns a git-style diff showing the changes made."
        ),
        inputSchema={
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Absolute path to file to edit. It should be under your current working directory."
                },
                "inserts": {
                    "type": "array",
                    "description": "Sequence of paragraphs to insert.",
                    "items": {
                        "type": "object",
                        "properties": {
                            "text": {
                                "type": "string",
                                "description": "Text to insert as a new paragraph."
                            },
                            "paragraph_index": {
                                "type": "integer",
                                "description": "0-based index of the paragraph before which to insert. If not specified, insert at the end."
                            }
                        },
                        "required": ["text"]
                    }
                }
            },
            "required": ["path", "inserts"]
        }
    )
  • Registers the edit_docx_insert tool (imported as EDIT_DOCX_INSERT) in the server's tool list via the list_tools handler.
    @server.list_tools()
    async def list_tools() -> list[types.Tool]:
        return [READ_DOCX, EDIT_DOCX_PARAGRAPH, WRITE_DOCX, EDIT_DOCX_INSERT]
  • Dispatches calls to the edit_docx_insert handler function within the server's call_tool method.
    elif name == "edit_docx_insert":
        result = await edit_docx_insert(arguments["path"], arguments["inserts"])
        return [types.TextContent(type="text", text=result)]
Behavior4/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 effectively describes key behaviors: the mutation nature ('Insert new paragraphs'), insertion logic (default to end, ordering for same index), and output format ('Returns a git-style diff showing the changes made'). It doesn't cover error conditions or file system implications, but provides substantial operational context.

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 perfectly front-loaded with the core purpose in the first sentence, followed by operational details and output information. Every sentence adds essential value: insertion logic, default behavior, ordering rules, and return format. There's zero wasted text or redundancy.

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

Completeness4/5

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

For a mutation tool with no annotations and no output schema, the description does an excellent job covering purpose, behavior, and output format. The main gap is lack of error handling or permission requirements information, but given the tool's moderate complexity and the description's coverage of core functionality, it's substantially complete.

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 100%, so the schema already fully documents both parameters and their nested properties. The description adds some semantic context about paragraph_index behavior ('0-based index', 'inserted in order' for same index), but doesn't provide significant additional meaning beyond what's in the schema descriptions. This meets the baseline for high schema coverage.

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 specific action ('Insert new paragraphs'), target resource ('into a docx file'), and distinguishes from siblings by focusing on insertion rather than editing existing paragraphs (edit_docx_paragraph), reading (read_docx), or full file writing (write_docx). The verb+resource combination is precise and unambiguous.

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

Usage Guidelines4/5

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

The description provides clear context about when to use this tool (for inserting paragraphs with optional positioning) and implicitly distinguishes it from siblings by its specific function. However, it doesn't explicitly state when NOT to use it or name alternative tools for different scenarios, which prevents a perfect score.

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/famano/mcp-server-office'

If you have feedback or need assistance with the MCP directory API, please join our Discord server