search_and_replace
Find and replace specific text in Microsoft Word documents to update content accurately and efficiently. Streamline document editing with precise text modifications.
Instructions
Search for text and replace all occurrences.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| filename | Yes | ||
| find_text | Yes | ||
| replace_text | Yes |
Implementation Reference
- word_document_server/main.py:737-740 (registration)MCP tool registration using @mcp.tool() decorator. Defines the tool schema via function signature and docstring, and delegates to the implementation in content_tools.@mcp.tool() async def search_and_replace(filename: str, find_text: str, replace_text: str): """Search for text and replace all occurrences.""" return await content_tools.search_and_replace(filename, find_text, replace_text)
- Core handler implementation. Loads document, performs validation, calls helper find_and_replace_text, saves changes, and returns success/error message with replacement count.async def search_and_replace(filename: str, find_text: str, replace_text: str) -> str: """Search for text and replace all occurrences. Args: filename: Path to the Word document find_text: Text to search for replace_text: Text to replace with """ filename = ensure_docx_extension(filename) if not os.path.exists(filename): return f"Document {filename} does not exist" # Check if file is writeable is_writeable, error_message = check_file_writeable(filename) if not is_writeable: return f"Cannot modify document: {error_message}. Consider creating a copy first." try: doc = Document(filename) # Perform find and replace count = find_and_replace_text(doc, find_text, replace_text) if count > 0: doc.save(filename) return f"Replaced {count} occurrence(s) of '{find_text}' with '{replace_text}'." else: return f"No occurrences of '{find_text}' found." except Exception as e: return f"Failed to search and replace: {str(e)}"
- Supporting utility function that implements the actual text replacement logic across paragraphs and tables, skipping TOC content, preserving runs, and counting replacements.def find_and_replace_text(doc, old_text, new_text): """ Find and replace text throughout the document, skipping Table of Contents (TOC) paragraphs. Args: doc: Document object old_text: Text to find new_text: Text to replace with Returns: Number of replacements made """ count = 0 # Search in paragraphs for para in doc.paragraphs: # Skip TOC paragraphs if para.style and para.style.name.startswith("TOC"): continue if old_text in para.text: for run in para.runs: if old_text in run.text: run.text = run.text.replace(old_text, new_text) count += 1 # Search in tables for table in doc.tables: for row in table.rows: for cell in row.cells: for para in cell.paragraphs: # Skip TOC paragraphs in tables if para.style and para.style.name.startswith("TOC"): continue if old_text in para.text: for run in para.runs: if old_text in run.text: run.text = run.text.replace(old_text, new_text) count += 1 return count
- word_document_server/tools/__init__.py:16-20 (registration)Central import exposing the search_and_replace handler from content_tools for use in main.py registration.from word_document_server.tools.content_tools import ( add_heading, add_paragraph, add_table, add_picture, add_page_break, add_table_of_contents, delete_paragraph, search_and_replace )