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
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | Absolute path to file to edit. It should be under your current working directory. | |
| inserts | Yes | Sequence of paragraphs to insert. |
Implementation Reference
- mcp_server_office/office.py:151-227 (handler)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 ""
- mcp_server_office/tools.py:24-62 (schema)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"] } )
- mcp_server_office/office.py:358-361 (registration)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]
- mcp_server_office/office.py:376-378 (registration)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)]