Skip to main content
Glama

gmail_refresh_token

Refresh Google OAuth2 access tokens for Gmail API authentication using refresh tokens and client credentials to maintain continuous server access.

Instructions

Refresh the access token using the refresh token and client credentials

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
google_access_tokenNoGoogle OAuth2 access token (optional if expired)
google_refresh_tokenYesGoogle OAuth2 refresh token
google_client_idYesGoogle OAuth2 client ID for token refresh
google_client_secretYesGoogle OAuth2 client secret for token refresh

Implementation Reference

  • Core handler function in GmailClient class that performs the OAuth2 token refresh using google.oauth2.credentials.Credentials.refresh() with client credentials.
    def refresh_token(self, client_id: str, client_secret: str) -> str:
        """Refresh the access token using the refresh token
        
        Args:
            client_id: Google OAuth2 client ID
            client_secret: Google OAuth2 client secret
        """
        if not self.credentials.refresh_token:
            return json.dumps({
                "error": "No refresh token provided",
                "status": "error"
            })
            
        try:
            # Set client_id and client_secret for refresh
            self.credentials._client_id = client_id
            self.credentials._client_secret = client_secret
            
            # Force refresh
            request = Request()
            self.credentials.refresh(request)
            
            # Get token expiration time
            expiry = self.credentials.expiry
            
            # Return the new access token and its expiration
            return json.dumps({
                "access_token": self.credentials.token,
                "expires_at": expiry.isoformat() if expiry else None,
                "expires_in": int((expiry - datetime.now(expiry.tzinfo)).total_seconds()) if expiry else None,
                "status": "success"
            })
            
        except google.auth.exceptions.RefreshError as e:
            logger.error(f"Token refresh error: {str(e)}")
            return json.dumps({
                "error": "Token refresh failed. Please provide valid client ID and client secret.",
                "details": str(e),
                "status": "error"
            })
        except Exception as e:
            logger.error(f"Exception: {str(e)}")
            return json.dumps({
                "error": str(e),
                "status": "error"
            })
  • MCP server @server.call_tool() dispatch logic that extracts input arguments, initializes GmailClient, and invokes the refresh_token handler.
    if name == "gmail_refresh_token":
        # For refresh token, we need refresh token, client ID and secret
        refresh_token = arguments.get("google_refresh_token")
        client_id = arguments.get("google_client_id")
        client_secret = arguments.get("google_client_secret")
        access_token = arguments.get("google_access_token")  # Optional for refresh
        
        if not refresh_token:
            raise ValueError("google_refresh_token is required for token refresh")
        
        if not client_id or not client_secret:
            raise ValueError("Both google_client_id and google_client_secret are required for token refresh")
        
        # Initialize Gmail client for token refresh
        gmail = GmailClient(
            access_token=access_token, 
            refresh_token=refresh_token
        )
        
        # Call the refresh_token method
        results = gmail.refresh_token(client_id=client_id, client_secret=client_secret)
        return [types.TextContent(type="text", text=results)]
  • Tool registration in @server.list_tools() including name, description, and input schema definition.
        name="gmail_refresh_token",
        description="Refresh the access token using the refresh token and client credentials",
        inputSchema={
            "type": "object",
            "properties": {
                "google_access_token": {"type": "string", "description": "Google OAuth2 access token (optional if expired)"},
                "google_refresh_token": {"type": "string", "description": "Google OAuth2 refresh token"},
                "google_client_id": {"type": "string", "description": "Google OAuth2 client ID for token refresh"},
                "google_client_secret": {"type": "string", "description": "Google OAuth2 client secret for token refresh"}
            },
            "required": ["google_refresh_token", "google_client_id", "google_client_secret"]
        },
    ),
  • Pydantic-style input schema defining parameters for the gmail_refresh_token tool.
        inputSchema={
            "type": "object",
            "properties": {
                "google_access_token": {"type": "string", "description": "Google OAuth2 access token (optional if expired)"},
                "google_refresh_token": {"type": "string", "description": "Google OAuth2 refresh token"},
                "google_client_id": {"type": "string", "description": "Google OAuth2 client ID for token refresh"},
                "google_client_secret": {"type": "string", "description": "Google OAuth2 client secret for token refresh"}
            },
            "required": ["google_refresh_token", "google_client_id", "google_client_secret"]
        },
    ),
Behavior2/5

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

With no annotations provided, the description carries full burden but only states what the tool does at a high level. It doesn't disclose behavioral traits like whether this invalidates previous tokens, rate limits, error conditions, or what the refreshed token enables. For a security-sensitive operation with zero annotation coverage, this is inadequate.

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 a single, efficient sentence that directly states the tool's purpose with zero waste. It's appropriately sized and front-loaded, with every word contributing to understanding the core functionality.

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?

For a security-critical token refresh operation with no annotations and no output schema, the description is insufficient. It doesn't explain what happens after refresh (e.g., token lifetime, scope preservation), error handling, or integration with sibling tools. Given the complexity and lack of structured data, more context is needed.

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 schema already documents all 4 parameters thoroughly. The description adds no parameter-specific semantics beyond what's in the schema (e.g., it doesn't explain relationships between parameters or provide usage examples). Baseline 3 is appropriate when schema does the heavy lifting.

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 verb ('Refresh') and resource ('access token'), specifying it uses refresh token and client credentials. It distinguishes from sibling tools (email-related operations) by focusing on authentication token management, though it doesn't explicitly name alternatives for token refresh.

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 when access tokens expire (via 'optional if expired' in schema), but doesn't explicitly state when to use this tool versus alternatives like initial authentication or other token management methods. No guidance on prerequisites or exclusions is provided.

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/baryhuang/mcp-headless-gmail'

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