Skip to main content
Glama
ZatesloFL

Google Workspace MCP Server

by ZatesloFL

find_and_replace_doc

Locate and substitute specific text within a Google Doc. Specify user email, document ID, and text to find and replace. Optionally match case for precise adjustments. Returns replacement count for confirmation.

Instructions

Finds and replaces text throughout a Google Doc.

Args: user_google_email: User's Google email address document_id: ID of the document to update find_text: Text to search for replace_text: Text to replace with match_case: Whether to match case exactly

Returns: str: Confirmation message with replacement count

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
document_idYes
find_textYes
match_caseNo
replace_textYes
user_google_emailYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main handler function for the 'find_and_replace_doc' tool. It is registered via @server.tool(), requires Docs write access, handles the find-and-replace logic using the Google Docs batchUpdate API, and returns the number of replacements made.
    @server.tool()
    @handle_http_errors("find_and_replace_doc", service_type="docs")
    @require_google_service("docs", "docs_write")
    async def find_and_replace_doc(
        service,
        user_google_email: str,
        document_id: str,
        find_text: str,
        replace_text: str,
        match_case: bool = False,
    ) -> str:
        """
        Finds and replaces text throughout a Google Doc.
    
        Args:
            user_google_email: User's Google email address
            document_id: ID of the document to update
            find_text: Text to search for
            replace_text: Text to replace with
            match_case: Whether to match case exactly
    
        Returns:
            str: Confirmation message with replacement count
        """
        logger.info(f"[find_and_replace_doc] Doc={document_id}, find='{find_text}', replace='{replace_text}'")
    
        requests = [create_find_replace_request(find_text, replace_text, match_case)]
    
        result = await asyncio.to_thread(
            service.documents().batchUpdate(
                documentId=document_id,
                body={'requests': requests}
            ).execute
        )
    
        # Extract number of replacements from response
        replacements = 0
        if 'replies' in result and result['replies']:
            reply = result['replies'][0]
            if 'replaceAllText' in reply:
                replacements = reply['replaceAllText'].get('occurrencesChanged', 0)
    
        link = f"https://docs.google.com/document/d/{document_id}/edit"
        return f"Replaced {replacements} occurrence(s) of '{find_text}' with '{replace_text}' in document {document_id}. Link: {link}"
  • Supporting helper function that constructs the exact Google Docs API request object for the replaceAllText operation used by the find_and_replace_doc handler.
    def create_find_replace_request(
        find_text: str, 
        replace_text: str, 
        match_case: bool = False
    ) -> Dict[str, Any]:
        """
        Create a replaceAllText request for Google Docs API.
        
        Args:
            find_text: Text to find
            replace_text: Text to replace with
            match_case: Whether to match case exactly
        
        Returns:
            Dictionary representing the replaceAllText request
        """
        return {
            'replaceAllText': {
                'containsText': {
                    'text': find_text,
                    'matchCase': match_case
                },
                'replaceText': replace_text
            }
        }
Behavior2/5

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

With no annotations provided, the description carries full burden of behavioral disclosure. While it mentions the action and return format, it doesn't address important behavioral aspects: whether this requires specific permissions, if changes are reversible, whether it affects document history/versioning, or if there are rate limits. For a mutation tool with zero annotation coverage, this is a significant gap.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections (purpose, Args, Returns) and uses minimal words to convey essential information. The front-loaded purpose statement is effective, though the Args section could be slightly more concise by integrating some details into the main description.

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

Completeness3/5

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

For a mutation tool with 5 parameters, 0% schema description coverage, and no annotations, the description does an adequate job covering the basics. The presence of an output schema reduces the need to explain return values in the description. However, given the tool's complexity (text replacement in documents), more behavioral context about permissions, side effects, and limitations would be beneficial.

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

Parameters4/5

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

With 0% schema description coverage, the description provides valuable parameter context through the Args section. It clearly explains what each parameter represents (user's Google email, document ID, text to search for, etc.) and adds the 'match_case' default behavior. This compensates well for the schema's lack of descriptions, though it doesn't provide format examples or validation rules.

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 action ('Finds and replaces text') and resource ('throughout a Google Doc'), making the purpose immediately understandable. However, it doesn't explicitly differentiate from sibling tools like 'modify_doc_text' or 'batch_update_doc', which could have overlapping functionality.

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 multiple document modification tools in the sibling list (modify_doc_text, batch_update_doc, insert_doc_elements), there's no indication of when this specific find-and-replace operation is appropriate versus other document editing approaches.

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

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/ZatesloFL/google_workspace_mcp'

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