Gemini CLI Beyond the Basics: Choosing the Right MCP Authentication

The Gemini CLI offers flexible authentication strategies to secure your Model Context Protocol (MCP) connections. Whether you are connecting to a simple MCP server exposing a couple of tools or a strictly governed enterprise service on Google Cloud, selecting the right authentication method is critical for both security and usability.

Defining “Security” in a CLI Context

Before diving into configuration, it is important to define what “secure” means when running a local CLI. We aren’t just talking about encryption in transit (HTTPS); we are talking about Local Credential Management and Token Lifespan.

  • Low Safety: Storing long-lived, static API keys or tokens in a plain-text settings.json file. If this file is compromised or accidentally committed to version control, the key is exposed indefinitely.
  • High Safety: Using mechanisms like Application Default Credentials (ADC) or Service Account Impersonation. While these credentials are typically stored locally, they are short-lived and automatically refreshed by the Google Cloud CLI (gcloud). This significantly reduces the window of exposure if the machine is compromised.

Below are the details on how to add servers quickly using the CLI, followed by a deep dive into the four primary authentication configuration strategies.

Quick Setup with gemini mcp add

Before manually editing configuration files, you should know that the Gemini CLI provides a helper command to register servers quickly: gemini mcp add.

What authentication does this implement?

By default, running the gemini mcp add command creates a configuration with no authentication. However, if you use the optional --header flag, this command specifically implements the Static HTTP Header authentication method (Method #1 below).

Example:

To add a server and immediately secure it with a Bearer token, you would run:

gemini mcp add my-server https://api.example.com/mcp \
    --transport http \
    --header "Authorization: Bearer my-secret-token"

This command automatically updates your settings.json file, inserting the URL and the headers block for you. Note that it defines transport as “Streamable HTTP”. You need to explicitly define it. By default, the transport is set to stdio which ignores the headers block. For more complex authentication methods (like Google Credentials or OAuth), you will typically need to edit the settings.json file manually after adding the server.

1. Static HTTP Headers (API Keys & Bearer Tokens)

This is the most straightforward method, ideal for connecting to third-party services that rely on long-lived API keys or Personal Access Tokens (PATs).

Configuration example (settings.json)

If you need to add headers manually (or add multiple headers), you can edit the configuration file directly.

Tip

  • The Gemini CLI supports using environment variables directly within settings.json. In the example below, ${MY_ENV_VAR_TOKEN} will be substituted with the actual value of the MY_ENV_VAR_TOKEN environment variable when the CLI initializes.
  • Ensure you do not leave a trailing comma after the last item in your list or object (e.g., after "secret-value" in the example below), or the configuration file will fail to load.

{
  "mcpServers": {
    "my-custom-tool": {
      "httpUrl": "https://api.example.com/mcp",
      "headers": {
        "Authorization": "Bearer ${MY_ENV_VAR_TOKEN}",
        "X-Custom-Auth": "secret-value"
      }
    }
  }
}

Pros & Cons

Perspective Analysis
Security 🟠 Low to medium: Long-lived tokens are risky if leaked.
Management 🟢 Easy: Simple to generate and revoke manually.
Config Complexity 🟢 Low: Can be done in one line via gemini mcp add.
User Complexity 🟢 Low: “Set and forget” for the user.

2. Google Credentials (google_credentials)

This method is designed for users working within the Google Cloud ecosystem. It automatically uses your local environment’s credentials—typically Application Default Credentials (ADC) or your active gcloud session.

How it works:

The Gemini CLI intercepts requests and injects a Google ID token belonging to you (the user running the CLI). This is perfect for calling Google MCP servers or custom MCP solutions that invoke services such as Cloud Run or Cloud Functions directly.

Configuration example (settings.json)

{
  "mcpServers": {
    "internal-tool": {
      "httpUrl": "https://internal-tool-xyz.a.run.app/sse",
      "authProviderType": "google_credentials"
    }
  }
}

Pros & Cons

Perspective Analysis
Security 🟢 High: Uses short-lived, rotatable tokens.
Management 🟢 Automated: Relies on gcloud auth login state.
Config Complexity 🟢 Low: Only requires one JSON field.
User Complexity 🟢 Low: Transparent if the user is already logged into gcloud.

3. Service Account Impersonation (service_account_impersonation)

While google_credentials uses your personal identity, Service Account Impersonation allows the Gemini CLI to adopt a distinct, machine-only identity.

Why use this locally?

  1. Production Simulation: You want to test exactly how the bot will behave when deployed to Cloud Run, ensuring it only has the permissions it needs (and not your broad admin privileges).
  2. Identity Separation: The target MCP server may be configured to reject human users entirely, accepting only specific trusted Service Account emails.

The Flow:

  1. You (User) request to act as the Service Account.
  2. Google IAM verifies you have the “Token Creator” role.
  3. Gemini CLI receives a token representing the Service Account.
  4. Gemini CLI uses that token to access the Cloud Run service.

Configuration example (settings.json)

{
  "mcpServers": {
    "enterprise-bot": {
      "httpUrl": "https://secure-bot.a.run.app/sse",
      "authProviderType": "service_account_impersonation",
      "targetServiceAccount": "agent-sa@my-project.iam.gserviceaccount.com",
      "targetAudience": "YOUR_OAUTH_CLIENT_ID"
    }
  }
}

Note

Note regarding targetAudience: If your MCP server is configured as an OAuth client, use the OAuth Client ID as the audience. If your service is a Cloud Run service, use the service URL (e.g., https://secure-bot.a.run.app) instead.

Required Setup

You must grant your user account permission to impersonate the service account.

# 1. Variables
export PROJECT_ID="your-project-id"
export SERVICE_ACCOUNT_EMAIL="service-account-name@${PROJECT_ID}.iam.gserviceaccount.com"
export USER_EMAIL="jane.doe@example.com"

# 2. Grant 'Token Creator' role to your user
gcloud iam service-accounts add-iam-policy-binding "${SERVICE_ACCOUNT_EMAIL}" \
    --member="user:${USER_EMAIL}" \
    --role="roles/iam.serviceAccountTokenCreator" \
    --project="${PROJECT_ID}"

Important

IAM permission changes in Google Cloud are eventually consistent and can take up to 1-2 minutes to propagate. If the gcloud command succeeds but the Gemini CLI returns a 403 Forbidden error when you try to connect immediately after, wait a minute and try again.

Pros & Cons

Perspective Analysis
Security 🟣 Very high: Strictly scoped permissions (Principle of Least Privilege).
Management 🔴 Complex: Requires IAM setup (Service Account Token Creator role).
Config Complexity 🔴 High.: Requires specific Client IDs and SA emails.
User Complexity 🟠 Medium: User needs permission to impersonate the account.

4. Built-in OAuth 2.0 Support

For sophisticated third-party services (like GitHub, Linear, or Slack) that require standard user login flows, the Gemini CLI has a native OAuth handler.

You can manage OAuth tokens either from your system shell or directly inside the interactive Gemini session.

A. The Shell Command (gemini mcp auth)

Use this when you are setting up your environment before starting your work.

# List servers that require authentication
gemini mcp auth

# Initiate the login flow (opens browser)
gemini mcp auth github-server

B. The Interactive Command (/mcp auth)

Use this when you are already inside the Gemini CLI (interactive mode) and encounter a permission error. This prevents you from having to exit the tool just to log in.

>>> User: Can you check my latest PRs?
>>> Gemini: I need access to GitHub to do that. Please authenticate.

# You can run this directly in the chat input:
>>> /mcp auth github-server

Pros & Cons

Perspective Analysis
Security 🟢 High: Standard OAuth flow; tokens are refreshed automatically.
Management 🟢 Delegated: Auth is managed by the third-party provider.
Config Complexity 🟢 Low: Often zero-config on the user’s side.
User Complexity 🟠 Medium: Requires interactive steps (browser login) periodically.

Summary: Which Method Should I Choose?

Don’t overcomplicate it. Choose your method based on where your credentials live:

  • Use Static Headers if… You are connecting to a 3rd party API (like a weather service) that simply provides a generic API Key. Risk: The key is stored in plain text on your machine.
  • Use Google Credentials (ADC) if… You are building internal tools on Google Cloud and you are the primary user. This is the fastest, safest way to prototype without managing keys.
  • Use Service Account Impersonation if… You are strictly testing permissions or connecting to an endpoint that explicitly denies human users. This keeps your personal admin privileges separate from the bot’s logic.
  • Use Built-in OAuth if… The tool needs to act on your behalf in a third-party ecosystem (like commenting on a GitHub PR or creating a Linear ticket).