· 14 Min read

Complete Gemini CLI Setup Guide: Google's AI Assistant

Complete Gemini CLI Setup Guide: Google's AI Assistant

Google's Gemini CLI has taken the developer community by storm since its launch in June 2025, garnering over 70,000 GitHub stars and 2,800 community contributions within just months. This open-source AI agent brings the full power of Gemini 2.5 Pro directly into your terminal, offering an unprecedented combination of coding assistance, workflow automation, and extensibility through the Model Context Protocol (MCP).

Link to section: What Makes Gemini CLI RevolutionaryWhat Makes Gemini CLI Revolutionary

Gemini CLI stands out in the crowded field of AI coding assistants through several key innovations. Unlike browser-based AI tools, it integrates seamlessly into your existing terminal workflow, supporting massive codebases with its 1 million token context window. The tool's recent GitHub Actions integration transforms it from a personal assistant into a collaborative team member that can automatically handle issue triage, pull request reviews, and code generation tasks.

The free tier offers industry-leading usage limits of 60 requests per minute and 1,000 requests daily, making it accessible for individual developers and small teams. This generous allocation, combined with Google's backing, has driven rapid adoption across the developer community.

Link to section: Prerequisites and System RequirementsPrerequisites and System Requirements

Before installing Gemini CLI, ensure your system meets the following requirements:

  • Node.js 18 LTS or later - Check with node -v
  • npm 9+ or compatible package manager - Verify with npm -v
  • Operating System: Windows 10 (21H2+), macOS 10.15+, or Linux (most distributions)
  • Terminal: PowerShell 5.1+, Windows Terminal, or any POSIX-compatible shell
  • Internet Connection: Required for authentication and API calls

For Windows users, administrator privileges may be needed for global installations. Linux and macOS users should have standard development tools installed.

Link to section: Installation MethodsInstallation Methods

The most straightforward approach installs Gemini CLI globally on your system:

npm install -g @google/gemini-cli

Verify the installation:

gemini --version
# Expected output: @google/gemini-cli v0.1.20 (or latest)

Check installation path:

which gemini
# macOS/Linux: /usr/local/bin/gemini
# Windows: C:\Users\[username]\AppData\Roaming\npm\gemini.cmd

Link to section: Method 2: Run Once with npx (Trial Mode)Method 2: Run Once with npx (Trial Mode)

For testing without permanent installation:

npx https://github.com/google-gemini/gemini-cli

This method downloads and runs Gemini CLI temporarily, ideal for evaluation purposes. No files remain after the session ends.

Link to section: Method 3: Windows Package ManagersMethod 3: Windows Package Managers

Using winget:

# Install Node.js if missing
winget install OpenJS.NodeJS.LTS --silent
 
# Install Gemini CLI
npm install -g @google/gemini-cli

Using Chocolatey:

# Install Node.js
choco install nodejs-lts -y
 
# Install Gemini CLI with elevation
elevate npm install -g @google/gemini-cli

Link to section: First-Time Setup and AuthenticationFirst-Time Setup and Authentication

Launch Gemini CLI for initial configuration:

gemini

The setup wizard will guide you through three key steps:

Link to section: Step 1: Theme SelectionStep 1: Theme Selection

Choose from available themes:

  • Default: Standard terminal colors
  • Dark: High contrast for dark terminals
  • Light: Optimized for light backgrounds
  • Pink: Distinctive pink accent colors
  • Dracula: Popular dark theme

Link to section: Step 2: Authentication MethodStep 2: Authentication Method

Select your preferred authentication approach:

Option A: Personal Google Account (Free Tier)

  • Provides 60 requests/minute, 1,000 requests/day
  • Uses Gemini 2.5 Pro with 1M token context
  • Requires browser authentication

Option B: API Key (Paid Usage)

  • Get your key from Google AI Studio
  • Set environment variable: export GEMINI_API_KEY="your-api-key"
  • Usage-based billing with higher limits

Link to section: Step 3: Browser Authentication (Free Tier)Step 3: Browser Authentication (Free Tier)

When using personal Google account:

  1. Gemini CLI opens your default browser
  2. Sign in to your Google account
  3. Grant permissions to Gemini CLI
  4. Return to terminal for confirmation

If the callback fails, try these solutions:

# Disable VPN split-tunneling temporarily
# Or use global VPN mode
 
# Alternative: Use API key authentication
export GEMINI_API_KEY="your-api-key"
gemini --auth-type api-key

Link to section: Basic Usage and CommandsBasic Usage and Commands

Link to section: Interactive ModeInteractive Mode

Start an interactive session:

gemini

Within the interactive shell, you can:

# Ask coding questions
> How do I implement a binary search tree in Python?
 
# Analyze files
> @package.json explain the dependencies in this file
 
# Debug errors  
> I'm getting a TypeError on line 25. Here's my code: [paste code]
 
# Generate code
> Create a REST API endpoint for user authentication using Express.js

Link to section: Single Prompt ModeSingle Prompt Mode

Execute one-off commands:

# Quick code generation
gemini "Write a function to validate email addresses in JavaScript"
 
# File analysis
gemini "Analyze this codebase structure" @src/
 
# Debug assistance
gemini "Fix this SQL query: SELECT * FROM users WHERE age > AND name = 'John'"

Link to section: Command Line OptionsCommand Line Options

Essential flags for customizing behavior:

# Enable debug mode for troubleshooting
gemini -d
 
# Use specific model
gemini --model gemini-2.5-pro
 
# Set theme
gemini --style dark
 
# Enable multiline input
gemini --multiline
 
# Specify config file
gemini --config ~/.gemini/custom-settings.json
Gemini CLI running in terminal with syntax highlighting

Link to section: Advanced Configuration with MCP IntegrationAdvanced Configuration with MCP Integration

The Model Context Protocol (MCP) extends Gemini CLI's capabilities by connecting it to external tools and services. This powerful feature allows integration with databases, APIs, and custom workflows.

Link to section: Understanding MCP ServersUnderstanding MCP Servers

MCP servers act as bridges between Gemini CLI and external systems. Popular MCP servers include:

  • GitHub MCP: Repository management and operations
  • Database MCP: SQL query execution and schema analysis
  • Web MCP: HTTP requests and API interactions
  • File System MCP: Advanced file operations

Link to section: Configuring GitHub MCP ServerConfiguring GitHub MCP Server

Create or edit the global settings file:

# Create settings directory
mkdir -p ~/.gemini
 
# Edit settings file
nano ~/.gemini/settings.json

Add GitHub MCP configuration:

{
  "theme": "Default",
  "selectedAuthType": "oauth-personal",
  "mcpServers": {
    "github": {
      "httpUrl": "https://api.githubcopilot.com/mcp/",
      "headers": {
        "Authorization": "Bearer YOUR_GITHUB_PAT"
      },
      "timeout": 5000
    }
  }
}

Generate a GitHub Personal Access Token:

  1. Visit GitHub Settings > Developer settings > Personal access tokens
  2. Create new token with these scopes:
    • repo (Full repository access)
    • read:org (Organization membership)
    • workflow (GitHub Actions)
  3. Copy the token and replace YOUR_GITHUB_PAT in settings.json

Link to section: Local MCP Server SetupLocal MCP Server Setup

For custom tools, create a local MCP server:

# Create MCP server directory
mkdir ~/mcp-servers
cd ~/mcp-servers
 
# Initialize Node.js project
npm init -y
npm install @modelcontextprotocol/sdk

Create a basic MCP server (server.js):

import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
 
class CustomMCPServer {
  constructor() {
    this.server = new Server(
      {
        name: "custom-tools",
        version: "0.1.0",
      },
      {
        capabilities: {
          tools: {},
        },
      }
    );
 
    this.setupToolHandlers();
  }
 
  setupToolHandlers() {
    this.server.setRequestHandler('tools/call', async (request) => {
      const { name, arguments: args } = request.params;
      
      switch (name) {
        case 'system_info':
          return {
            content: [{
              type: 'text',
              text: `System: ${process.platform}, Node: ${process.version}`
            }]
          };
        default:
          throw new Error(`Unknown tool: ${name}`);
      }
    });
  }
 
  async run() {
    const transport = new StdioServerTransport();
    await this.server.connect(transport);
    console.error('Custom MCP Server running on stdio');
  }
}
 
const server = new CustomMCPServer();
server.run().catch(console.error);

Register the local server in ~/.gemini/settings.json:

{
  "mcpServers": {
    "custom-tools": {
      "command": "node",
      "args": ["/path/to/your/mcp-servers/server.js"]
    }
  }
}

Link to section: Verifying MCP ConfigurationVerifying MCP Configuration

Restart Gemini CLI and verify MCP servers:

gemini
> /mcp

This command displays configured MCP servers and their available tools. Test GitHub integration:

> List repositories in my GitHub account
> Clone the repository 'username/repo-name' to my local machine
> Create a new issue in repository 'username/repo-name' with title "Bug report"

Link to section: VS Code Integration SetupVS Code Integration Setup

Gemini CLI's VS Code integration provides enhanced functionality for developers who prefer IDE environments alongside terminal workflows.

Link to section: Installation and ConfigurationInstallation and Configuration

Install the Gemini CLI VS Code extension:

  1. Open VS Code
  2. Navigate to Extensions (Ctrl+Shift+X)
  3. Search for "Gemini CLI"
  4. Install the official Google extension

Configure the integration:

# Ensure Gemini CLI version 0.1.20+
gemini --version
 
# Run one-time setup command
gemini --setup-vscode

This creates necessary configuration files and establishes communication between VS Code and Gemini CLI.

Link to section: Using VS Code IntegrationUsing VS Code Integration

The integration enables several powerful features:

File Selection: Gemini CLI becomes aware of currently open files and can reference them directly:

> @currentFile explain this component's lifecycle methods
> Refactor @selectedText to use modern async/await syntax

Native Diffing: View suggested changes side-by-side with your original code. The diff interface allows you to:

  • Accept entire suggestions
  • Accept partial changes
  • Edit suggestions before applying
  • Reject changes and request alternatives

Command Palette Integration: Access Gemini CLI through VS Code's command palette (Ctrl+Shift+P):

  • "Gemini: Ask Question About Current File"
  • "Gemini: Generate Code for Selected Text"
  • "Gemini: Debug Selected Code"

Link to section: GitHub Actions IntegrationGitHub Actions Integration

The recent GitHub Actions integration transforms Gemini CLI into a collaborative team member. This beta feature automates repository workflows and enables AI-powered code reviews.

Link to section: Setting Up Gemini CLI GitHub ActionsSetting Up Gemini CLI GitHub Actions

Add the action to your repository's workflow file (.github/workflows/gemini-cli.yml):

name: Gemini CLI Assistant
on:
  issues:
    types: [opened, edited]
  pull_request:
    types: [opened, synchronize, reopened]
  issue_comment:
    types: [created]
 
jobs:
  gemini-assistant:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      issues: write
      pull-requests: write
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        
      - name: Run Gemini CLI
        uses: google-github-actions/run-gemini-cli@v1
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          gemini-api-key: ${{ secrets.GEMINI_API_KEY }}

Link to section: Configuring Workflow BehaviorsConfiguring Workflow Behaviors

Create .github/gemini-config.yml to customize AI behaviors:

issue_triage:
  enabled: true
  auto_label: true
  priority_keywords:
    - "urgent"
    - "critical"
    - "security"
  label_mapping:
    bug: ["error", "crash", "broken"]
    feature: ["enhancement", "new"]
    documentation: ["docs", "readme"]
 
pull_request_review:
  enabled: true
  auto_review: true
  focus_areas:
    - "security vulnerabilities"
    - "performance issues"
    - "code style consistency"
    - "test coverage"
  
collaboration:
  trigger_phrase: "@gemini-cli"
  max_response_length: 2000
  include_code_suggestions: true

Link to section: Using GitHub Actions FeaturesUsing GitHub Actions Features

Automatic Issue Triage: When new issues are created, Gemini CLI automatically:

  • Analyzes issue content and assigns appropriate labels
  • Identifies priority levels based on keywords
  • Suggests related existing issues
  • Provides initial troubleshooting guidance

Pull Request Reviews: For new pull requests, the AI:

  • Reviews code changes for common issues
  • Suggests improvements and optimizations
  • Checks for security vulnerabilities
  • Validates test coverage and documentation

On-Demand Collaboration: Team members can directly interact with Gemini CLI by mentioning it in comments:

@gemini-cli write unit tests for the new authentication module
 
@gemini-cli analyze the performance impact of this database query
 
@gemini-cli suggest improvements for error handling in this function

Link to section: Practical Workflow ExamplesPractical Workflow Examples

Link to section: Example 1: Full-Stack Bug InvestigationExample 1: Full-Stack Bug Investigation

Investigate a production bug using Gemini CLI's comprehensive analysis capabilities:

# Start investigation
gemini
 
# Analyze error logs
> @logs/error.log identify patterns in these error messages
 
# Examine related code
> @src/auth/login.js @src/database/users.js find potential causes for authentication failures
 
# Review recent changes
> What git commits in the last week might have introduced this bug?
 
# Generate fix
> Create a patch for the authentication timeout issue, including error handling and logging

Link to section: Example 2: Code Review and OptimizationExample 2: Code Review and Optimization

Use Gemini CLI for comprehensive code review:

# Analyze entire module
> @src/api/ review this API module for security vulnerabilities and performance issues
 
# Check specific patterns
> @src/utils/helpers.js identify functions that could benefit from memoization
 
# Generate improvements
> Refactor the user validation functions to use modern async patterns and improve error messages

Link to section: Example 3: Documentation GenerationExample 3: Documentation Generation

Automatically generate project documentation:

# Create comprehensive README
> @package.json @src/ generate a detailed README.md with installation instructions, API documentation, and usage examples
 
# Generate API docs
> @src/routes/ create OpenAPI/Swagger documentation for these Express.js routes
 
# Update changelog
> @git-log generate changelog entries for version 2.1.0 based on recent commits

Link to section: Troubleshooting Common IssuesTroubleshooting Common Issues

Link to section: Authentication ProblemsAuthentication Problems

Error: "Failed to login" or "Request contains an invalid argument"

Solutions:

  1. Clear authentication cache: rm -rf ~/.gemini/auth
  2. Use API key instead: export GEMINI_API_KEY="your-key"
  3. Check Google Workspace restrictions: Set GOOGLE_CLOUD_PROJECT environment variable

Browser callback failures:

# Disable VPN split-tunneling
# Or switch to global VPN mode
 
# Alternative: Manual token entry
gemini --auth-type manual

Link to section: Model and Quota IssuesModel and Quota Issues

Automatic model switching from Pro to Flash:

This indicates quota limitations. Solutions:

  1. Upgrade to paid API key for higher limits
  2. Reduce request frequency
  3. Use --model gemini-2.5-flash explicitly for faster, cheaper queries

Rate limit errors:

# Check current usage
gemini --usage-stats
 
# Wait for quota reset (daily limits reset at midnight UTC)
# Or upgrade to paid tier

Link to section: MCP Server ConnectivityMCP Server Connectivity

EADDRINUSE errors:

# Kill existing MCP processes
pkill -f "mcp-server"
 
# Restart Gemini CLI
gemini --restart

MCP server not discovered:

  1. Verify settings.json syntax: cat ~/.gemini/settings.json | jq .
  2. Check server executable permissions: chmod +x /path/to/server
  3. Test server manually: node /path/to/server.js

Link to section: Debug Mode for Complex IssuesDebug Mode for Complex Issues

Enable comprehensive debugging:

# Maximum verbosity
gemini -d --verbose
 
# Log to file for analysis
gemini -d 2>&1 | tee gemini-debug.log
 
# Check system diagnostics
gemini --doctor

The --doctor command runs comprehensive system checks:

  • API connectivity tests
  • Authentication status
  • MCP server health
  • Configuration validation
  • Network connectivity

Link to section: Advanced Automation and WorkflowsAdvanced Automation and Workflows

Link to section: Custom Slash CommandsCustom Slash Commands

Gemini CLI supports custom slash commands for frequently used workflows. Create project-specific commands in GEMINI.md:

# Project Instructions for Gemini CLI
 
## Custom Commands
 
### /deploy
Deploy the application to staging environment:
1. Run test suite
2. Build production assets  
3. Update staging server
4. Verify deployment health
 
### /review-pr
Code review checklist:
- Security vulnerabilities
- Performance implications
- Test coverage
- Documentation updates
- Breaking changes
 
## Code Style
- Use TypeScript for all new files
- Follow Airbnb ESLint configuration  
- Write comprehensive JSDoc comments
- Maintain 80%+ test coverage

Use custom commands in interactive mode:

> /deploy
> /review-pr --pr-number 123

Link to section: Integration with Existing ToolsIntegration with Existing Tools

Workflow automation becomes powerful when Gemini CLI integrates with your existing toolchain:

Git Integration:

# Automated commit messages
> @git-diff generate a conventional commit message for these changes
 
# Branch management
> Create a new feature branch for implementing user notifications

Docker Integration:

# Container debugging
> @docker-logs analyze these container logs for performance bottlenecks
 
# Dockerfile optimization
> @Dockerfile suggest improvements for build time and image size

Database Operations:

# Query optimization
> @slow-queries.sql optimize these database queries for better performance
 
# Schema analysis
> @database-schema suggest indexes for this user activity table

Link to section: Performance Optimization and Best PracticesPerformance Optimization and Best Practices

Link to section: Efficient Context ManagementEfficient Context Management

Gemini CLI's 1 million token context window is powerful but requires thoughtful management:

Include relevant files only:

# Instead of entire directories
> @src/ analyze this codebase
 
# Target specific components
> @src/auth/ @tests/auth/ review authentication implementation

Use incremental analysis:

# Build context progressively
> @package.json what is this project about?
> @README.md @package.json explain the architecture
> @src/main.js @README.md @package.json how does the application bootstrap?

Link to section: Cost Management StrategiesCost Management Strategies

Monitor usage to optimize costs:

# Check current usage
gemini --usage-stats
 
# Use Flash model for simple queries
gemini --model gemini-2.5-flash "fix this syntax error: const x = ;"
 
# Batch similar requests
> Analyze these three files for security issues: @auth.js @validation.js @middleware.js

Link to section: Team Collaboration GuidelinesTeam Collaboration Guidelines

For teams using Gemini CLI GitHub Actions:

  1. Standardize trigger phrases: Use consistent @gemini-cli mentions
  2. Define review criteria: Establish clear expectations in .github/gemini-config.yml
  3. Monitor AI suggestions: Review automated suggestions before merging
  4. Document AI decisions: Track which AI recommendations were accepted or rejected

Link to section: Future Roadmap and Community ContributionsFuture Roadmap and Community Contributions

Gemini CLI's rapid evolution continues with upcoming features:

  • Enhanced MCP ecosystem: More pre-built servers for popular tools
  • Multi-modal capabilities: Image and video analysis integration
  • Improved VS Code integration: Deeper IDE embedding
  • Enterprise features: Team management and usage analytics

The thriving open-source community has contributed over 2,800 pull requests since launch, with active development in areas like:

  • Performance optimizations
  • Additional MCP servers
  • Security enhancements
  • Documentation improvements

Contributing to Gemini CLI is straightforward:

# Clone the repository
git clone https://github.com/google-gemini/gemini-cli.git
cd gemini-cli
 
# Install dependencies
npm install
 
# Run tests
npm test
 
# Start development
npm run dev

The project welcomes contributions through GitHub issues, feature requests, and pull requests. The maintainers actively review community submissions and provide guidance for new contributors.

Gemini CLI represents a significant advancement in AI-powered development tools, combining Google's cutting-edge AI models with the familiar terminal environment that developers prefer. Its open-source nature, generous free tier, and extensible architecture through MCP make it an compelling choice for individual developers and teams seeking to integrate AI assistance into their workflows. As the tool continues to evolve through community contributions and Google's ongoing development, it's positioned to become an essential part of the modern developer toolkit.