Skip to main content
Glama

update_spreadsheet_title_tool

Change the title of a Google Spreadsheet to organize or rename documents for better management and clarity.

Instructions

Update a Google Spreadsheet title.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
spreadsheet_nameYesThe name of the spreadsheet to rename
new_titleYesThe new title for the spreadsheet

Implementation Reference

  • Main handler function that orchestrates spreadsheet lookup, title update, error handling, and JSON response formatting.
    def update_spreadsheet_title_handler(
        drive_service,
        sheets_service,
        spreadsheet_name: str,
        new_title: str
    ) -> str:
        """Handler to update a spreadsheet title by name."""
        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."
            })
        
        try:
            update_spreadsheet_title(sheets_service, spreadsheet_id, new_title)
            return compact_json_response({
                "success": True,
                "spreadsheet_name": spreadsheet_name,
                "new_title": new_title,
                "message": f"Successfully updated spreadsheet '{spreadsheet_name}' title to '{new_title}'"
            })
        except Exception as e:
            return compact_json_response({
                "success": False,
                "message": f"Error updating spreadsheet title: {str(e)}"
            })
  • Core helper that executes the Google Sheets API batchUpdate request to modify the spreadsheet's title property.
    def update_spreadsheet_title(sheets_service, spreadsheet_id: str, new_title: str) -> str:
        """Update a spreadsheet title by its ID."""
        try:
            sheets_service.spreadsheets().batchUpdate(
                spreadsheetId=spreadsheet_id,
                body={
                    "requests": [
                        {
                            "updateSpreadsheetProperties": {
                                "properties": {"title": new_title},
                                "fields": "title"
                            }
                        }
                    ]
                }
            ).execute()
            return f"Spreadsheet {spreadsheet_id} title updated to '{new_title}'"
        except HttpError as error:
            raise RuntimeError(f"Error updating spreadsheet title: {error}")
  • Registers the tool with MCP framework, defines input schema via Field annotations, initializes services, and delegates execution to handler.
    @mcp.tool()
    def update_spreadsheet_title_tool(
        spreadsheet_name: str = Field(..., description="The name of the spreadsheet to rename"),
        new_title: str = Field(..., description="The new title for the spreadsheet")
    ) -> str:
        """
        Update a Google Spreadsheet title.
        """
        sheets_service, drive_service = _get_google_services()
        return update_spreadsheet_title_handler(drive_service, sheets_service, spreadsheet_name, new_title)
  • Critical helper utility that queries Google Drive API to find the unique spreadsheet ID matching the given name.
    def get_spreadsheet_id_by_name(
        drive_service,
        spreadsheet_name: str
    ) -> Optional[str]:
        """
        Convert a spreadsheet name to its ID by making direct API call to Google Drive.
        
        Args:
            drive_service: Google Drive API service instance
            spreadsheet_name: Name of the spreadsheet to find
        
        Returns:
            Spreadsheet ID if exactly one match found, None otherwise
        
        Raises:
            RuntimeError: If Google Drive service not initialized or if multiple files with same name found
        """
        if not drive_service:
            raise RuntimeError("Google Drive service not initialized. Set Google credentials environment variables.")
        
        try:
            # Make direct API call to Google Drive
            results = (
                drive_service.files()
                .list(
                    q="mimeType='application/vnd.google-apps.spreadsheet'",
                    pageSize=100,
                    fields="files(id,name)",
                )
                .execute()
            )
            files = results.get("files", [])
            
            # Collect all files with exact name match
            matching_files = []
            for file in files:
                current_name = file["name"]
                if current_name == spreadsheet_name:
                    matching_files.append({
                        "id": file["id"],
                        "name": file["name"]
                    })
            
            # Check for errors based on number of matches
            if len(matching_files) == 0:
                raise RuntimeError(f"No spreadsheet found with name '{spreadsheet_name}'")
            elif len(matching_files) > 1:
                file_ids = [file["id"] for file in matching_files]
                raise RuntimeError(f"Multiple spreadsheets found with name '{spreadsheet_name}'. IDs: {file_ids}")
            
            # Return the single matching file's ID
            return matching_files[0]["id"]
            
        except HttpError as error:
            print(f"Error searching for spreadsheet '{spreadsheet_name}': {error}")
            return None
        except Exception as error:
            print(f"Unexpected error while searching for spreadsheet '{spreadsheet_name}': {error}")
            return None
  • Utility for serializing response dictionaries to compact JSON strings to minimize token usage.
    def compact_json_response(data: Dict[str, Any]) -> str:
        """
        Convert a Python dictionary to a compact JSON string with no newlines or extra spaces.
        
        Args:
            data: Python dictionary to serialize
        
        Returns:
            Compact JSON string with minimal formatting
        """
        return json.dumps(data, separators=(',', ':'))

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