DEV Community

James Miller
James Miller

Posted on

Advanced Gemini CLI: Building Secure MCP Connections and Authentication

As the Model Context Protocol (MCP) gains popularity, more and more developers are using the Gemini CLI to debug and connect to various MCP servers. Whether you are connecting to a simple toolset or interfacing with enterprise-grade services on Google Cloud that have strict permission controls, choosing the right authentication method is indispensable for ensuring both security and availability.

Gemini CLI Installation

If you haven't installed the Gemini CLI yet, you can get it set up quickly using the following method.

Node Version Management

The Gemini CLI relies on a Node.js environment. We recommend using ServBay to manage your Node.js versions.

ServBay offers one-click installation for the latest Node.js environment and supports full version coverage from Node 12 to Node 24. Furthermore, ServBay allows different versions of Node.js to coexist simultaneously without the need for repeated switching or configuring environment variables, providing a solid foundation for running and debugging the Gemini CLI.

Ensure ServBay is running and the Node module is enabled, then install the Gemini CLI:

npm install -g @google/gemini-cli
Enter fullscreen mode Exit fullscreen mode

Next, let's look at how to define security within the CLI environment.

Defining Security in the CLI Environment

When running the CLI locally, security is not just about transport encryption (HTTPS); it is fundamentally about credential management and token lifecycles.

  • Low Security: Storing long-lived, static API Keys in plain text within configuration files. Once the file is leaked or accidentally committed to a code repository, the credentials are permanently exposed.
  • High Security: Using Application Default Credentials (ADC) or Service Account impersonation. These credentials are usually stored locally but have a short lifecycle and are automatically refreshed by the Google Cloud CLI (gcloud). Even if the machine is compromised, the attacker's window of opportunity is very limited.

Below are four main authentication configuration strategies.

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

This is the most direct method, suitable for third-party services that rely on long-lived API Keys or Personal Access Tokens (PATs).

While you can add these by editing the configuration file, it is fastest to specify them directly via command-line arguments when adding a server. The Gemini CLI provides the gemini mcp add command, which can be used with the --header parameter.

Command Line Example:

Suppose you want to add a weather service protected by a Bearer Token:

gemini mcp add weather-service https://api.weather-data.com/mcp \
    --transport http \
    --header "Authorization: Bearer secret-token-123"
Enter fullscreen mode Exit fullscreen mode

This command automatically updates the settings.json file. Note that you must explicitly define the transport type, as the default standard input/output (stdio) mode ignores HTTP headers.

Configuration File Example (settings.json):

To avoid writing tokens in plain text into the file, Gemini CLI supports referencing environment variables in the configuration file. During CLI initialization, ${ENV_VAR} will be replaced with the actual value.

{
  "mcpServers": {
    "data-tool": {
      "httpUrl": "https://api.myservice.com/mcp",
      "headers": {
        "Authorization": "Bearer ${APP_API_TOKEN}",
        "X-Org-Id": "org-888"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Pros: Simple configuration, easy to generate manually.
  • Cons: Risk of long-lived Token leakage.

2. Google Credentials (google_credentials)

For developers within the Google Cloud ecosystem, this is the preferred solution. It automatically utilizes credentials from the local environment—typically Application Default Credentials (ADC) or the currently active gcloud session.

The Gemini CLI intercepts requests and injects a Google ID Token belonging to the current user. This is perfect for calling private MCP services deployed on Cloud Run or Cloud Functions.

Configuration Example (settings.json):

Simply specify the authProviderType field:

{
  "mcpServers": {
    "cloud-logger": {
      "httpUrl": "https://logger-service-abc.a.run.app/sse",
      "authProviderType": "google_credentials"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Pros: Uses short-lived, rotatable Tokens; high security.
  • Cons: Relies on the gcloud login state.

3. Service Account Impersonation (service_account_impersonation)

While google_credentials uses personal identity, service account impersonation allows the Gemini CLI to use an independent, machine-only identity.

In local development, this method is primarily used for production simulation (testing how a Bot behaves under restricted permissions) or identity isolation (where the target MCP server rejects human users and only accepts specific service accounts).

Workflow:

  1. The user requests to impersonate a service account.
  2. Google IAM verifies if the user has the "Token Creator" role.
  3. Gemini CLI retrieves a Token representing that service account and uses it to access the target service.

Configuration Example (settings.json):

{
  "mcpServers": {
    "finance-bot": {
      "httpUrl": "https://secure-finance.a.run.app/sse",
      "authProviderType": "service_account_impersonation",
      "targetServiceAccount": "bot-sa@my-gcp-project.iam.gserviceaccount.com",
      "targetAudience": "https://secure-finance.a.run.app"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Note: If it is a Cloud Run service, targetAudience is usually the URL of the service.

Prerequisite Permission Setup:

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

# Define variables
export PROJ_ID="my-gcp-project"
export SA_EMAIL="bot-sa@${PROJ_ID}.iam.gserviceaccount.com"
export MY_EMAIL="developer@company.com"

# Grant the Token Creator role
gcloud iam service-accounts add-iam-policy-binding "${SA_EMAIL}" \
    --member="user:${MY_EMAIL}" \
    --role="roles/iam.serviceAccountTokenCreator" \
    --project="${PROJ_ID}"
Enter fullscreen mode Exit fullscreen mode

IAM permission changes are eventually consistent and may take a minute or two to take effect.

  • Pros: Follows the principle of least privilege; strict permission control.
  • Cons: IAM configuration is relatively verbose.

4. Built-in OAuth 2.0 Support

For complex third-party services like GitHub, Linear, or Slack that require standard user login flows, the Gemini CLI has built-in OAuth handlers.

Shell Command Method:

You can complete authentication via shell commands before starting work.

# View list of services requiring authentication
gemini mcp auth

# Start the login flow for GitLab service (opens browser)
gemini mcp auth gitlab-server
Enter fullscreen mode Exit fullscreen mode

Interactive Command Method:

If you encounter a permission error during an interactive session in Gemini CLI, you don't need to exit the tool. You can input the instruction directly in the dialog:

>>> User: Please list my todo items.
>>> Gemini: I need access permissions for Linear.
>>> /mcp auth linear-server
Enter fullscreen mode Exit fullscreen mode
  • Pros: Standard OAuth flow, automatic Token refresh, good user experience.
  • Cons: Requires periodic browser interaction for login.

Summary

Which authentication method you choose depends on where your credentials are stored and the usage scenario:

  • Static Headers: Suitable for third-party services providing generic API Keys. Use with environment variables to avoid plain text storage.
  • Google Credentials: Suitable for internal Google Cloud tool development; fast and secure.
  • Service Account Impersonation: Suitable for permission testing or scenarios requiring strict identity isolation.
  • Built-in OAuth: Suitable for scenarios requiring operations within third-party ecosystems (like GitHub PRs) on behalf of the user.

Regardless of the method chosen, ensuring the stability of the underlying Node.js environment is the first step. Using ServBay to manage Node versions can effectively avoid runtime errors caused by environmental differences.

Top comments (0)