search_and_replace
Locate specific text in a Word document and substitute it with desired content. Simplify document editing by automating repetitive 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
- The core handler function implementing the search and replace logic using python-docx library, including file checks, replacement, and saving.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)}"
- word_document_server/main.py:202-205 (registration)MCP tool registration using @mcp.tool() decorator. This thin wrapper delegates to the implementation in content_tools.@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)
- Import statement exposing search_and_replace from content_tools module for use in main.py.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 )