Skip to main content
Glama

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
NameRequiredDescriptionDefault
filenameYes
find_textYes
replace_textYes

Implementation Reference

  • 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
  • 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
    )
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It states the tool replaces 'all occurrences,' implying a mutation operation, but doesn't disclose critical behavioral traits: whether it modifies files in-place, requires write permissions, handles errors (e.g., if file doesn't exist), or has side effects like backups. For a mutation tool with zero annotation coverage, this is a significant gap in transparency.

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 extremely concise: 'Search for text and replace all occurrences.' It's a single sentence with zero waste, front-loading the core action. Every word earns its place, making it easy to parse quickly.

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

Completeness2/5

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

Given the complexity (a mutation tool with 3 parameters) and lack of annotations or output schema, the description is incomplete. It doesn't cover behavioral aspects like safety, error handling, or return values, nor does it clarify parameter usage. For a tool that modifies documents, this minimal description leaves too many unknowns for effective agent use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, meaning none of the parameters (filename, find_text, replace_text) have descriptions in the schema. The tool description doesn't add any meaning beyond the parameter names—it doesn't explain what 'filename' refers to (e.g., path, document name), how text matching works (case-sensitive?), or the scope of replacement. With low coverage, the description fails to compensate, leaving parameters poorly documented.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Search for text and replace all occurrences.' This specifies the verb (search and replace) and resource (text), but it doesn't differentiate from sibling tools like 'find_text_in_document' or 'replace_block_between_manual_anchors', which appear to have overlapping functionality. The description is clear but lacks sibling differentiation.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. With siblings like 'find_text_in_document' (which likely only searches) and 'replace_block_between_manual_anchors' (which may replace specific blocks), there's no indication of when this global replace tool is preferred. No context, exclusions, or alternatives are mentioned.

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

Related 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/franlealp1/mcp-word'

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