search_and_replace
Find specific text in Word documents and replace all instances with new text to update content efficiently.
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:202-205 (registration)Registers the 'search_and_replace' tool with the FastMCP server using the @mcp.tool() decorator. This synchronous wrapper function delegates execution to the asynchronous implementation in content_tools.search_and_replace.@mcp.tool() def search_and_replace(filename: str, find_text: str, replace_text: str): """Search for text and replace all occurrences.""" return content_tools.search_and_replace(filename, find_text, replace_text)
- Core handler function for the search_and_replace tool. Validates the document file, loads it using python-docx, invokes the find_and_replace_text helper to perform replacements (skipping TOC), saves the document, and returns a status 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 performs the actual text replacement in paragraphs and table cells, skipping TOC-styled content. Iterates through runs for precise replacement and returns the total count of replacements made.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