Skip to main content
Glama
ZatesloFL

Google Workspace MCP Server

by ZatesloFL

batch_update_doc

Execute multiple document edits in a single batch operation for Google Docs, including text insertion, formatting, table creation, and page breaks, ensuring atomic updates.

Instructions

Executes multiple document operations in a single atomic batch update.

Args: user_google_email: User's Google email address document_id: ID of the document to update operations: List of operation dictionaries. Each operation should contain: - type: Operation type ('insert_text', 'delete_text', 'replace_text', 'format_text', 'insert_table', 'insert_page_break') - Additional parameters specific to each operation type

Example operations: [ {"type": "insert_text", "index": 1, "text": "Hello World"}, {"type": "format_text", "start_index": 1, "end_index": 12, "bold": true}, {"type": "insert_table", "index": 20, "rows": 2, "columns": 3} ]

Returns: str: Confirmation message with batch operation results

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
document_idYes
operationsYes
user_google_emailYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Primary handler function for 'batch_update_doc' tool. Decorated with @server.tool() for registration, performs input validation, delegates execution to BatchOperationManager, and returns formatted response with document link.
    @server.tool()
    @handle_http_errors("batch_update_doc", service_type="docs")
    @require_google_service("docs", "docs_write")
    async def batch_update_doc(
        service,
        user_google_email: str,
        document_id: str,
        operations: list,
    ) -> str:
        """
        Executes multiple document operations in a single atomic batch update.
    
        Args:
            user_google_email: User's Google email address
            document_id: ID of the document to update
            operations: List of operation dictionaries. Each operation should contain:
                       - type: Operation type ('insert_text', 'delete_text', 'replace_text', 'format_text', 'insert_table', 'insert_page_break')
                       - Additional parameters specific to each operation type
    
        Example operations:
            [
                {"type": "insert_text", "index": 1, "text": "Hello World"},
                {"type": "format_text", "start_index": 1, "end_index": 12, "bold": true},
                {"type": "insert_table", "index": 20, "rows": 2, "columns": 3}
            ]
    
        Returns:
            str: Confirmation message with batch operation results
        """
        logger.debug(f"[batch_update_doc] Doc={document_id}, operations={len(operations)}")
    
        # Input validation
        validator = ValidationManager()
    
        is_valid, error_msg = validator.validate_document_id(document_id)
        if not is_valid:
            return f"Error: {error_msg}"
    
        is_valid, error_msg = validator.validate_batch_operations(operations)
        if not is_valid:
            return f"Error: {error_msg}"
    
        # Use BatchOperationManager to handle the complex logic
        batch_manager = BatchOperationManager(service)
    
        success, message, metadata = await batch_manager.execute_batch_operations(
            document_id, operations
        )
    
        if success:
            link = f"https://docs.google.com/document/d/{document_id}/edit"
            replies_count = metadata.get('replies_count', 0)
            return f"{message} on document {document_id}. API replies: {replies_count}. Link: {link}"
        else:
            return f"Error: {message}"
  • Core helper method in BatchOperationManager that orchestrates validation, request building from operations list, batch API execution via documents.batchUpdate, result processing, and metadata generation. Extracts complex logic from the main handler.
    async def execute_batch_operations(
        self,
        document_id: str,
        operations: list[dict[str, Any]]
    ) -> tuple[bool, str, dict[str, Any]]:
        """
        Execute multiple document operations in a single atomic batch.
        
        This method extracts the complex logic from batch_update_doc tool function.
        
        Args:
            document_id: ID of the document to update
            operations: List of operation dictionaries
            
        Returns:
            Tuple of (success, message, metadata)
        """
        logger.info(f"Executing batch operations on document {document_id}")
        logger.info(f"Operations count: {len(operations)}")
        
        if not operations:
            return False, "No operations provided. Please provide at least one operation.", {}
            
        try:
            # Validate and build requests
            requests, operation_descriptions = await self._validate_and_build_requests(operations)
            
            if not requests:
                return False, "No valid requests could be built from operations", {}
            
            # Execute the batch
            result = await self._execute_batch_requests(document_id, requests)
            
            # Process results
            metadata = {
                'operations_count': len(operations),
                'requests_count': len(requests),
                'replies_count': len(result.get('replies', [])),
                'operation_summary': operation_descriptions[:5]  # First 5 operations
            }
            
            summary = self._build_operation_summary(operation_descriptions)
            
            return True, f"Successfully executed {len(operations)} operations ({summary})", metadata
            
        except Exception as e:
            logger.error(f"Failed to execute batch operations: {str(e)}")
            return False, f"Batch operation failed: {str(e)}", {}
  • Function signature with type hints and comprehensive docstring defining input schema (especially 'operations' list structure with examples) and output format.
    async def batch_update_doc(
        service,
        user_google_email: str,
        document_id: str,
        operations: list,
    ) -> str:
        """
        Executes multiple document operations in a single atomic batch update.
    
        Args:
            user_google_email: User's Google email address
            document_id: ID of the document to update
            operations: List of operation dictionaries. Each operation should contain:
                       - type: Operation type ('insert_text', 'delete_text', 'replace_text', 'format_text', 'insert_table', 'insert_page_break')
                       - Additional parameters specific to each operation type
    
        Example operations:
            [
                {"type": "insert_text", "index": 1, "text": "Hello World"},
                {"type": "format_text", "start_index": 1, "end_index": 12, "bold": true},
                {"type": "insert_table", "index": 20, "rows": 2, "columns": 3}
            ]
    
        Returns:
            str: Confirmation message with batch operation results
        """
        logger.debug(f"[batch_update_doc] Doc={document_id}, operations={len(operations)}")
    
        # Input validation
        validator = ValidationManager()
    
        is_valid, error_msg = validator.validate_document_id(document_id)
        if not is_valid:
            return f"Error: {error_msg}"
    
        is_valid, error_msg = validator.validate_batch_operations(operations)
        if not is_valid:
            return f"Error: {error_msg}"
    
        # Use BatchOperationManager to handle the complex logic
        batch_manager = BatchOperationManager(service)
    
        success, message, metadata = await batch_manager.execute_batch_operations(
            document_id, operations
        )
    
        if success:
            link = f"https://docs.google.com/document/d/{document_id}/edit"
            replies_count = metadata.get('replies_count', 0)
            return f"{message} on document {document_id}. API replies: {replies_count}. Link: {link}"
        else:
            return f"Error: {message}"
  • Method providing detailed schema documentation for all supported operation types, their required/optional parameters, descriptions, and examples - serves as runtime schema reference.
    def get_supported_operations(self) -> dict[str, Any]:
        """
        Get information about supported batch operations.
        
        Returns:
            Dictionary with supported operation types and their required parameters
        """
        return {
            'supported_operations': {
                'insert_text': {
                    'required': ['index', 'text'],
                    'description': 'Insert text at specified index'
                },
                'delete_text': {
                    'required': ['start_index', 'end_index'],
                    'description': 'Delete text in specified range'
                },
                'replace_text': {
                    'required': ['start_index', 'end_index', 'text'],
                    'description': 'Replace text in range with new text'
                },
                'format_text': {
                    'required': ['start_index', 'end_index'],
                    'optional': ['bold', 'italic', 'underline', 'font_size', 'font_family'],
                    'description': 'Apply formatting to text range'
                },
                'insert_table': {
                    'required': ['index', 'rows', 'columns'],
                    'description': 'Insert table at specified index'
                },
                'insert_page_break': {
                    'required': ['index'],
                    'description': 'Insert page break at specified index'
                },
                'find_replace': {
                    'required': ['find_text', 'replace_text'],
                    'optional': ['match_case'],
                    'description': 'Find and replace text throughout document'
                }
            },
            'example_operations': [
                {"type": "insert_text", "index": 1, "text": "Hello World"},
                {"type": "format_text", "start_index": 1, "end_index": 12, "bold": True},
                {"type": "insert_table", "index": 20, "rows": 2, "columns": 3}
            ]
        }
Behavior4/5

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

With no annotations provided, the description carries full burden. It discloses key behavioral traits: the atomic nature (all-or-nothing execution), batch capability, and operation types with examples. It mentions a return confirmation but doesn't detail error handling, permissions, or rate limits, leaving some gaps for a mutation tool.

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, example, returns) and front-loaded key information. It's appropriately sized but includes some redundancy (e.g., repeating 'operations' in the example). Every sentence adds value, though minor trimming is possible.

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

Completeness4/5

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

Given the tool's complexity (batch mutations with nested operations), no annotations, and an output schema (returns str), the description is largely complete. It covers purpose, parameters, and behavioral context but could enhance completeness by addressing prerequisites (e.g., authentication) or error scenarios, though the output schema mitigates return value explanation needs.

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

Parameters5/5

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

Schema description coverage is 0%, so the description must compensate fully. It adds substantial meaning: it explains user_google_email as 'User's Google email address,' document_id as 'ID of the document to update,' and operations with detailed structure, types, and examples, effectively documenting all three parameters beyond the bare schema.

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

Purpose5/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: 'Executes multiple document operations in a single atomic batch update.' It specifies the verb ('executes'), resource ('document operations'), and key characteristic ('atomic batch'), distinguishing it from single-operation siblings like modify_doc_text or insert_doc_elements.

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

Usage Guidelines3/5

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

The description implies usage context by mentioning 'multiple document operations in a single atomic batch,' suggesting efficiency for bulk edits. However, it lacks explicit guidance on when to use this tool versus alternatives like modify_doc_text or when not to use it (e.g., for single operations). No sibling tools are directly compared.

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