Skip to main content
Glama

create_duplicate_sheet_tool

Duplicate an existing sheet in your Google Spreadsheet. Specify the source sheet name, and optionally set a new name and insert position.

Instructions

Create a duplicate of an existing sheet.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
spreadsheet_nameYesThe name of the Google Spreadsheet
source_sheet_nameYesName of the sheet to duplicate
new_sheet_nameNoName for the duplicated sheet (optional, will auto-generate if not provided)
insert_positionNoPosition to insert the duplicated sheet (1-based index, optional - will insert at end if not specified)

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Main handler function that validates inputs, gets spreadsheet/sheet IDs, checks for duplicate names, and calls create_duplicate_sheet to perform the Google Sheets API duplicate operation.
    def create_duplicate_sheet_handler(
        drive_service,
        sheets_service,
        spreadsheet_name: str,
        source_sheet_name: str,
        new_sheet_name: str = None,
        insert_position: int = None
    ) -> str:
        """
        Handler to create a duplicate of an existing sheet.
        
        Args:
            drive_service: Google Drive service
            sheets_service: Google Sheets service
            spreadsheet_name: Name of the spreadsheet
            source_sheet_name: Name of the sheet to duplicate
            new_sheet_name: Name for the duplicated sheet (optional)
            insert_position: Position to insert the duplicated sheet (optional)
        
        Returns:
            JSON string with success status and duplicate sheet info
        """
        try:
            # Validate inputs
            if not source_sheet_name or not isinstance(source_sheet_name, str):
                return compact_json_response({
                    "success": False,
                    "message": "Source sheet name is required and must be a string."
                })
            
            # Validate new sheet name if provided
            if new_sheet_name:
                validation = validate_sheet_name(new_sheet_name)
                if not validation["valid"]:
                    return compact_json_response({
                        "success": False,
                        "message": f"Invalid new sheet name: {validation['error']}"
                    })
                new_sheet_name = validation["cleaned_name"]
            
            # Validate insert position if provided
            if insert_position is not None:
                if not isinstance(insert_position, int) or insert_position < 0:
                    return compact_json_response({
                        "success": False,
                        "message": "Insert position must be a non-negative integer."
                    })
            
            # Get spreadsheet ID
            spreadsheet_id = get_spreadsheet_id_by_name(drive_service, spreadsheet_name)
            if not spreadsheet_id:
                return compact_json_response({
                    "success": False,
                    "message": f"Spreadsheet '{spreadsheet_name}' not found."
                })
            
            # Get source sheet ID
            sheet_ids = get_sheet_ids_by_names(sheets_service, spreadsheet_id, [source_sheet_name])
            source_sheet_id = sheet_ids.get(source_sheet_name)
            if source_sheet_id is None:
                return compact_json_response({
                    "success": False,
                    "message": f"Source sheet '{source_sheet_name}' not found in spreadsheet '{spreadsheet_name}'."
                })
            
            # Check for duplicate name if new name is provided
            if new_sheet_name:
                duplicate_check = check_duplicate_sheet_name_for_duplicate(sheets_service, spreadsheet_id, new_sheet_name)
                if duplicate_check["has_duplicates"]:
                    return compact_json_response({
                        "success": False,
                        "message": duplicate_check["error"]
                    })
            
            # Create duplicate sheet
            try:
                result = create_duplicate_sheet(sheets_service, spreadsheet_id, source_sheet_id, new_sheet_name, insert_position)
                
                if result["success"]:
                    # Prepare response
                    response_data = {
                        "success": True,
                        "spreadsheet_name": spreadsheet_name,
                        "source_sheet_name": source_sheet_name,
                        "new_sheet_name": result["title"],
                        "new_sheet_index": result["index"],
                        "insert_position": insert_position,
                        "message": f"Successfully created duplicate of sheet '{source_sheet_name}' as '{result['title']}' in '{spreadsheet_name}'",
                        "sheet_details": {
                            "sheet_id": result["sheet_id"],
                            "title": result["title"],
                            "index": result["index"]
                        }
                    }
                    
                    return compact_json_response(response_data)
                else:
                    return compact_json_response({
                        "success": False,
                        "message": result["error"]
                    })
                    
            except HttpError as e:
                error_details = e.error_details if hasattr(e, 'error_details') else str(e)
                return compact_json_response({
                    "success": False,
                    "message": f"Failed to create duplicate sheet: {error_details}",
                    "error_code": e.resp.status if hasattr(e, 'resp') else None
                })
            
        except Exception as e:
            return compact_json_response({
                "success": False,
                "message": f"Unexpected error: {str(e)}",
                "error_type": type(e).__name__
            })
  • Tool registration with MCP decorator defining the input schema: spreadsheet_name (required), source_sheet_name (required), new_sheet_name (optional), insert_position (optional).
    @mcp.tool()
    def create_duplicate_sheet_tool(
        spreadsheet_name: str = Field(..., description="The name of the Google Spreadsheet"),
        source_sheet_name: str = Field(..., description="Name of the sheet to duplicate"),
        new_sheet_name: str = Field(default="", description="Name for the duplicated sheet (optional, will auto-generate if not provided)"),
        insert_position: int = Field(default=None, description="Position to insert the duplicated sheet (1-based index, optional - will insert at end if not specified)")
    ) -> str:
  • Registered as an MCP tool via the @mcp.tool() decorator. The function is named create_duplicate_sheet_tool and delegates to create_duplicate_sheet_handler.
    @mcp.tool()
    def create_duplicate_sheet_tool(
        spreadsheet_name: str = Field(..., description="The name of the Google Spreadsheet"),
        source_sheet_name: str = Field(..., description="Name of the sheet to duplicate"),
        new_sheet_name: str = Field(default="", description="Name for the duplicated sheet (optional, will auto-generate if not provided)"),
        insert_position: int = Field(default=None, description="Position to insert the duplicated sheet (1-based index, optional - will insert at end if not specified)")
    ) -> str:
        """
        Create a duplicate of an existing sheet.
        """
        sheets_service, drive_service = _get_google_services()
        return create_duplicate_sheet_handler(drive_service, sheets_service, spreadsheet_name, source_sheet_name, new_sheet_name, insert_position)
  • Core helper that executes the Google Sheets API batchUpdate call with a duplicateSheet request to create the sheet duplicate.
    def create_duplicate_sheet(sheets_service, spreadsheet_id: str, source_sheet_id: int, new_sheet_name: str = None, insert_position: int = None) -> Dict[str, Any]:
        """Create a duplicate sheet within the same spreadsheet."""
        try:
            # Prepare the duplicate sheet request
            request = {
                "duplicateSheet": {
                    "sourceSheetId": source_sheet_id,
                    "insertSheetIndex": insert_position,  # Will be inserted at specified position or at the end if None
                    "newSheetId": None,  # Let Google assign a new ID
                    "newSheetName": new_sheet_name
                }
            }
            
            response = sheets_service.spreadsheets().batchUpdate(
                spreadsheetId=spreadsheet_id,
                body={"requests": [request]}
            ).execute()
            
            # Extract the created sheet information
            reply = response.get("replies", [{}])[0]
            if "duplicateSheet" in reply:
                sheet_props = reply["duplicateSheet"]["properties"]
                return {
                    "success": True,
                    "sheet_id": sheet_props["sheetId"],
                    "title": sheet_props["title"],
                    "index": sheet_props["index"]
                }
            else:
                return {
                    "success": False,
                    "error": "Failed to create duplicate sheet"
                }
                
        except HttpError as e:
            return {
                "success": False,
                "error": f"Failed to create duplicate sheet: {str(e)}"
            }
Behavior2/5

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

No annotations provided, yet the description does not disclose behavioral details such as whether formatting is preserved, collision handling for existing sheet names, or authentication requirements.

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?

One sentence, front-loaded, no extraneous information; perfectly concise.

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 simple duplication tool with an output schema, the description suffices minimally but lacks usage context and behavioral details that would help an agent use it correctly.

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

Parameters3/5

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

Schema description coverage is 100%, so the description adds no additional parameter meaning beyond what is already in the schema; baseline 3 is appropriate.

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 'Create a duplicate of an existing sheet' uses a specific verb and resource, clearly distinguishing it from siblings like 'create_sheets_tool' which creates new blank sheets.

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?

No guidance on when to use this tool versus alternatives; no mention of prerequisites or when not to use it.

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/henilcalagiya/google-sheets-mcp'

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