metir
metir
Download on App StoreGet it on Google PlayF1 FantasyLoginSign Up
Back to Blog
Gemini CLI
Google Gemini
AI Development Tools
CLI Tools
AI Automation

The Ultimate Guide to Gemini CLI: Master Google's AI Terminal Agent in 2026

Learn everything about Gemini CLI, from installation to advanced automation. Discover tips, tricks, MCP integrations, custom commands, and workflows that transform your development experience with Google's free AI agent.

Metir AI TeamDecember 27, 202512 min read

In 2026, the terminal remains the command center for developers worldwide. But what if your terminal could understand natural language, write code, debug issues, and automate complex workflows—all powered by Google's most advanced AI model? Enter Gemini CLI, an open-source AI agent that's transforming how developers interact with their development environment.

Unlike traditional CLI tools that require memorizing commands and flags, Gemini CLI brings the full power of Gemini 3 Pro with its 1 million token context window directly into your terminal. The best part? It's completely free with your Google account, offering 60 requests per minute and 1,000 requests per day—no credit card required.

Whether you're debugging a stubborn bug, refactoring a massive codebase, or automating repetitive workflows, this comprehensive guide will teach you everything you need to know about Gemini CLI, from basic installation to advanced power-user techniques.

What Makes Gemini CLI Special?

Gemini CLI isn't just another AI chatbot wrapped in a terminal interface. It's a sophisticated AI agent built specifically for developers, featuring:

Massive Context Window: With Gemini 3 Pro's 1M token context, you can process entire codebases, documentation sets, and complex projects without hitting context limits. This makes it ideal for large-scale refactoring and comprehensive code analysis.

Built-in Developer Tools: Out of the box, Gemini CLI includes Google Search grounding, file operations, shell commands, and web fetching, allowing it to interact with your development environment directly.

Model Context Protocol (MCP) Support: Extend Gemini CLI with custom integrations to GitHub, Firebase, Google Workspace, and countless other services through standardized MCP servers.

Terminal-First Design: Unlike web-based AI assistants, Gemini CLI is designed for developers who live in the command line, providing a seamless workflow without context switching.

Free and Generous: The free tier provides 60 requests/minute and 1,000 requests/day—more than enough for serious development work.

Installation and Setup: Getting Started

Prerequisites

Before installing Gemini CLI, ensure you have Node.js 20 or later installed on your machine. The tool works seamlessly on macOS, Windows, and Linux.

Quick Start Installation

The fastest way to try Gemini CLI is running it directly without installation:

npx @google/gemini-cli

This command downloads and executes Gemini CLI immediately, perfect for testing before committing to a full installation.

Standard Installation via NPM

For regular use, install Gemini CLI globally:

npm install -g @google/gemini-cli

Once installed, launch Gemini CLI by simply typing:

gemini

Windows Installation

For Windows users, the recommended approach uses Chocolatey:

choco install nodejs-lts -y
npm install -g @google/gemini-cli

Authentication Options

When you first run Gemini CLI, you'll be prompted to authenticate. You have two options:

Option 1: Personal Google Account (Recommended for Most Users)

Simply authenticate with your personal Google account when prompted. This grants you the generous free tier: 60 requests per minute and 1,000 requests per day.

Option 2: API Key (For Higher Limits)

For users needing higher request limits or specific model access:

  1. Generate an API key from Google AI Studio
  2. Set it as an environment variable:
export GEMINI_API_KEY="YOUR_API_KEY"
  1. Add to your shell profile (~/.bashrc, ~/.zshrc) for persistence:
echo 'export GEMINI_API_KEY="YOUR_API_KEY"' >> ~/.zshrc

Sandbox Mode for Enhanced Security

For increased security and isolation, run Gemini CLI in sandbox mode:

gemini --sandbox

This is particularly useful when working with untrusted code or experimenting with potentially risky operations.

Basic Usage: Core Commands and Workflows

Interactive Mode

The default interactive mode is where most users spend their time. Launch it by typing gemini and you'll enter a conversational interface where you can:

  • Ask questions about your code
  • Request code generation
  • Debug issues
  • Analyze files and directories
  • Execute shell commands

Essential Slash Commands

Gemini CLI includes several built-in commands for managing your session:

/help - Display all available commands and their descriptions

/tools - List all available tools, including built-in tools and MCP servers

/clear - Clear the current conversation and start fresh

/quit - Exit Gemini CLI

/about - Check the current version and system information

/stats - Display detailed session statistics including token usage and cached tokens

Direct Prompt Execution

For one-off tasks or scripting, execute prompts directly from the command line:

gemini -p "Analyze the performance issues in this codebase"

Auto-Confirm Mode (YOLO Mode)

When you trust the AI's decisions, enable auto-confirm mode to skip approval prompts:

gemini -y

Warning: Use this carefully, as it automatically applies all suggested changes without confirmation.

File and Directory References

One of Gemini CLI's most powerful features is direct file and directory referencing using the @ symbol:

Reference specific files:

@README.md
@src/myFile.ts

Include entire directories:

@src/
@components/

The CLI respects .gitignore and .geminiignore files, automatically excluding irrelevant files from analysis.

Multi-format support: Reference images, PDFs, audio, and video files alongside code for comprehensive analysis.

Shell Integration

Gemini CLI provides seamless shell command execution:

Execute single commands:

! ls -la

Toggle persistent shell mode: Type ! by itself to enter shell mode where every command executes in your actual shell. Type ! again to exit.

Detection: When commands run via !, the GEMINI_CLI=1 environment variable is set, allowing scripts to detect they're running within Gemini CLI.

Advanced Features: Power User Techniques

Chat Session Management

For long-running projects, Gemini CLI's session management lets you pause and resume conversations:

Save sessions:

/chat save quarterly-report

Resume sessions:

/chat resume quarterly-report

Export conversations:

/chat share conversation.md
/chat share conversation.json

This feature is invaluable for maintaining context across multiple work sessions, especially for complex projects that span days or weeks.

Custom Commands: Automate Repetitive Workflows

One of Gemini CLI's most underutilized features is custom command creation using TOML files. These transform complex, multi-step prompts into simple shortcuts.

Location: Store commands in:

  • ~/.gemini/commands/ for personal, global commands
  • <project>/.gemini/commands/ for project-specific commands

Example: Create ~/.gemini/commands/review.toml:

name = "review"
description = "Perform comprehensive code review"

[prompt]
text = """
Review this code for:
- Security vulnerabilities
- Performance bottlenecks
- Code style consistency
- Best practice violations
- Potential bugs

Provide specific, actionable recommendations.
"""

Usage: Simply type /review instead of writing the entire prompt each time.

Team sharing: Commit TOML files in your project's .gemini/commands/ directory so team members automatically inherit shared workflows.

GEMINI.md: Project-Specific Context

The GEMINI.md file is perhaps the most powerful but underutilized feature. Place this file in your project root to provide persistent context that shapes every interaction:

Example GEMINI.md:

# Project: E-commerce Platform

## Tech Stack
- Next.js 14 with App Router
- TypeScript
- Tailwind CSS
- Supabase for backend

## Coding Conventions
- Use functional components with hooks
- Prefer server components unless client interactivity is needed
- All API routes in app/api/
- Use Zod for validation
- Follow Airbnb style guide

## Architecture Patterns
- Feature-based folder structure
- Shared components in components/ui/
- Database queries in lib/queries/
- Type definitions in types/

## Testing Requirements
- Jest for unit tests
- Playwright for E2E tests
- Minimum 80% code coverage

Advanced: Set GEMINI_SYSTEM_MD=true to use system.md in .gemini/ directory, completely replacing the CLI's built-in instructions for specialized workflows.

Model Context Protocol (MCP) Integration

MCP servers extend Gemini CLI with connections to external systems and data sources, making it a truly powerful development agent.

Managing MCP servers:

gemini mcp add <server-name>
gemini mcp list
gemini mcp remove <server-name>

Interactive commands:

  • /mcp list - Show available MCP servers
  • /mcp desc - Display detailed descriptions
  • /mcp schema - View full JSON schema

Configuration: Edit ~/.gemini/settings.json to configure MCP servers with environment variables and options.

Popular MCP integrations:

  • GitHub MCP - Repository management and PR reviews
  • Firebase MCP - Database and hosting operations
  • Google Workspace MCP - Docs, Sheets, and Drive integration
  • Database MCP - SQL query execution
  • JIRA MCP - Issue tracking and project management

Example: A database MCP server provides a /query_db tool for running SQL queries directly through natural language.

FastMCP: Building Custom MCP Servers

As of late 2025, Gemini CLI seamlessly integrates with FastMCP, Python's leading library for building MCP servers.

Setup:

# Install Gemini CLI
npm install -g @google/gemini-cli@latest

# Install FastMCP
pip install fastmcp>=2.12.3

Create server.py:

from fastmcp import FastMCP

mcp = FastMCP("Custom Development Server")

@mcp.tool()
def analyze_dependencies(package_json: str) -> str:
    """Analyze package.json for outdated dependencies"""
    # Your implementation
    return "Analysis results"

if __name__ == "__main__":
    mcp.run()

Rich content support: MCP tools can return text, images, audio, and other binary data in a single response, enabling sophisticated integrations.

IDE Integration: VS Code Connection

For developers who split time between terminal and IDE, Gemini CLI's VS Code integration provides workspace context and native diffing.

Setup:

/ide install
/ide enable

Benefits:

  • Automatic workspace context (recent files, cursor position, selected text)
  • View and approve code changes in VS Code's diff viewer
  • Seamless integration between terminal and editor

Extensions: Modular Functionality

Create extensions to add bundled functionality to Gemini CLI.

Location:

  • <workspace>/.gemini/extensions/
  • ~/.gemini/extensions/

Structure: Each extension is a directory with gemini-extension.json configuring:

  • MCP servers
  • Tools
  • Context files
  • Custom commands

This modular approach allows you to build specialized development environments for different project types.

Memory Management

Gemini CLI's memory system allows the AI to remember important information across sessions:

Add to memory:

/memory add Our API uses JWT tokens with 24-hour expiration

View memory:

/memory

Memory persists across sessions, creating a knowledge base specific to your workflow and preferences.

Checkpointing and Restore

When enabled, checkpointing saves project snapshots before Gemini CLI modifies files:

Enable checkpointing:

gemini --checkpointing

List checkpoints:

/restore

Restore specific checkpoint:

/restore checkpoint_20260127_143022

This safety net is invaluable when experimenting with large refactors or risky changes.

Structured Output for Automation

For scripting and automation workflows, Gemini CLI provides structured output formats:

JSON output:

gemini -p "Analyze this code" --output-format json

Real-time streaming:

gemini --output-format stream-json

This enables integration with other tools, CI/CD pipelines, and custom automation scripts.

Real-World Use Cases and Workflows

Automated Code Reviews

Create a comprehensive code review workflow:

gemini -p "Review @src/ for security vulnerabilities, performance issues, and code quality. Generate a detailed report."

Large-Scale Refactoring

Leverage the 1M token context for codebase-wide changes:

gemini -i "Refactor this codebase to use TypeScript strict mode and update all type definitions"

The -i flag keeps the session open for iterative improvements.

Documentation Generation

Generate comprehensive documentation from code:

gemini -p "Generate API documentation for @src/api/ in Markdown format with code examples"

Bug Investigation and Fixing

Debug complex issues with full codebase context:

gemini -i "There's a memory leak when processing large files. Investigate @src/ and @tests/ and propose fixes."

CI/CD Integration

Integrate Gemini CLI into GitHub Actions for automated workflows:

Automatic PR reviews:

- name: Review PR
  uses: google-github-actions/run-gemini-cli@v1
  with:
    prompt: "Review this PR for code quality and security"

Issue triage:

- name: Triage Issue
  uses: google-github-actions/run-gemini-cli@v1
  with:
    prompt: "Analyze this issue and suggest appropriate labels"

Scheduled Status Reports

Automate project reporting with scheduled jobs:

# Weekly status report
gemini -p "Analyze git commits from the last week and generate a status report highlighting key achievements and blockers" --output-format json > weekly-report.json

Best Practices for Effective Prompting

1. Provide Context Upfront

The quality of results is directly tied to the clarity and context you provide. Before starting complex tasks, give Gemini CLI a clear understanding:

gemini -i "Review the current codebase; show me the good, the bad, and the ugly"

2. Be Specific and Direct

Vague prompts yield vague results. Use specific language:

Vague: "Make this better" Specific: "Refactor this function to use async/await instead of promises and add error handling"

3. Iterative Refinement

Start broad, then narrow down:

# First pass
"Analyze the authentication system"

# Follow-up
"Focus on the JWT validation logic and identify security concerns"

# Refinement
"Propose fixes for the identified security issues with code examples"

4. Validate AI Recommendations

Always validate AI suggestions against current documentation and best practices. AI should inform decisions, not replace technical judgment.

5. Use Custom Commands for Consistency

Package frequently used prompts into custom commands to ensure consistent results and save time.

6. Commit Regularly

After each successful change, commit to git:

git commit -m "Refactor authentication logic per Gemini CLI suggestions"

This creates safety points you can return to if needed.

7. Leverage GEMINI.md Files

Good project structure and clear GEMINI.md files significantly improve efficiency. Invest time upfront to document your project's conventions and architecture.

8. Test Each Step

Ensure each completed step passes tests before moving forward. This maintains code quality and prevents cascading issues.

Gemini CLI vs. Competing Tools

Gemini CLI vs. Claude Code

According to recent benchmarks, both tools excel at different tasks:

Gemini CLI Strengths:

  • Free tier with generous limits (vs. Claude Code's $17-200/month)
  • Excels at large-context refactors with 1M+ token window
  • Superior for static reasoning tasks (feature comparisons, version conflicts)
  • Cross-platform from day one (Windows, macOS, Linux)

Claude Code Strengths:

  • Best for rapid prototyping
  • Excellent terminal UX with clear output design
  • Handles massive files (18,000+ lines) that other tools fail on
  • Superior git workflow automation

Recommendation: Gemini CLI is ideal for cost-conscious developers or those preferring terminal-based workflows, while Claude Code suits enterprise developers needing advanced git automation.

Gemini CLI vs. Cursor

Cursor leads in different areas:

Cursor Strengths:

  • Fastest setup with minimal configuration
  • Excellent Docker/deployment workflows
  • Real-time code generation and in-context edits
  • Model flexibility (GPT-5.4, Claude, Gemini)
  • Smooth IDE experience with minimal friction

Gemini CLI Strengths:

  • Terminal-native workflow (no IDE required)
  • Completely free vs. Cursor's $20/month
  • Superior for automation and scripting
  • Better for large codebase analysis
  • MCP extensibility

Recommendation: Cursor is best for most developers who want comprehensive IDE integration and real-time suggestions, while Gemini CLI suits terminal enthusiasts and those automating workflows.

Gemini CLI vs. GitHub Copilot

GitHub Copilot Strengths:

  • Inline code completion
  • Seamless IDE integration
  • Mature ecosystem
  • Enterprise-friendly licensing

Gemini CLI Strengths:

  • Conversational interface for complex tasks
  • Massive context window for codebase analysis
  • Free tier vs. Copilot's $10-19/month
  • Shell command execution and automation
  • MCP extensibility for custom integrations

Recommendation: Use both together—Copilot for inline completions, Gemini CLI for comprehensive analysis and refactoring.

Common Workflows: Practical Examples

Daily Development Workflow

# Morning: Review overnight changes
gemini -p "Summarize commits from the last 24 hours and highlight potential issues"

# During coding: Get implementation suggestions
gemini -i "I need to implement OAuth2 authentication. Guide me through the implementation."

# Before PR: Comprehensive review
gemini -p "Review @src/ for code quality, security, and test coverage. Generate a PR description."

# End of day: Status update
gemini -p "Generate a status update based on today's commits and modified files"

Debugging Workflow

# Step 1: Describe the issue
gemini -i "Users are reporting timeout errors when uploading large files. Let's investigate."

# Step 2: Analyze relevant code
@src/upload/
"Analyze the file upload logic for performance bottlenecks"

# Step 3: Examine logs
@logs/error.log
"Correlate these errors with the upload code"

# Step 4: Generate fix
"Propose a solution with streaming uploads and progress tracking"

# Step 5: Create tests
"Generate integration tests for the new upload implementation"

Migration Workflow

# Step 1: Assess current state
gemini -i "We're migrating from JavaScript to TypeScript. Analyze @src/ and create a migration plan."

# Step 2: Incremental conversion
"Convert @src/utils/ to TypeScript with strict mode enabled"

# Step 3: Update types
"Generate TypeScript interfaces for @src/models/"

# Step 4: Fix type errors
"Review and fix all type errors in the converted files"

# Step 5: Update tests
"Convert test files to TypeScript and add type-safe mocks"

Tips and Tricks for Power Users

1. Combine with Other CLI Tools

Pipe output to other tools for powerful workflows:

gemini -p "Extract all TODO comments from @src/" --output-format json | jq '.todos' > todos.json

2. Create Command Aliases

Add shell aliases for frequent workflows:

alias gai="gemini -i"
alias gar="gemini -p 'Review current changes and suggest improvements'"
alias gad="gemini -p 'Generate documentation for @'"

3. Use Environment Variables for Configuration

Customize behavior through environment variables:

export GEMINI_MODEL="gemini-3-pro"
export GEMINI_MAX_TOKENS="100000"

4. Version Control Your Configuration

Commit .gemini/ directories to version control so team members inherit:

  • Custom commands
  • Project-specific context (GEMINI.md)
  • Extension configurations

5. Monitor Token Usage

Regularly check /stats to optimize prompts and avoid unnecessary token consumption.

6. Leverage Cached Tokens

With API key authentication, Gemini CLI caches tokens for repeated content, significantly reducing costs and improving performance.

7. Create Prompt Libraries

Maintain a personal library of effective prompts in markdown files:

# My Prompt Library

## Code Review
"Review this code for security, performance, and maintainability. Provide specific, actionable recommendations."

## Documentation
"Generate comprehensive documentation including overview, API reference, and examples."

## Testing
"Create unit tests with edge cases and integration tests for critical paths."

8. Use Multiple Sessions

Run different Gemini CLI sessions for different contexts:

# Terminal 1: Frontend work
cd frontend && gemini -i "Working on React components"

# Terminal 2: Backend work
cd backend && gemini -i "Working on API endpoints"

9. Integrate with tmux/screen

Combine with tmux for persistent sessions:

tmux new -s gemini-dev
gemini -i "Starting development session"
# Detach with Ctrl+B, D
# Reattach with: tmux attach -t gemini-dev

10. Build Custom MCP Servers for Your Stack

Create organization-specific MCP servers that connect to:

  • Internal APIs and services
  • Custom databases
  • Proprietary tools
  • Company-specific workflows

This transforms Gemini CLI into a personalized development assistant that understands your entire infrastructure.

Troubleshooting Common Issues

High Token Usage

If you're hitting token limits:

  1. Use more specific file references instead of entire directories
  2. Create focused custom commands
  3. Clear conversations with /clear when changing topics
  4. Leverage .geminiignore to exclude irrelevant files

Unexpected Behavior

If Gemini CLI isn't performing as expected:

  1. Check GEMINI.md files for conflicting instructions
  2. Verify MCP servers are configured correctly (/mcp list)
  3. Review recent conversation for context issues
  4. Try a fresh session with /clear

MCP Connection Issues

If MCP servers aren't responding:

  1. Verify server configuration in ~/.gemini/settings.json
  2. Check environment variables are set correctly
  3. Ensure the MCP server is running (/mcp list shows status)
  4. Review trust settings—some servers require explicit trust

Performance Issues

If Gemini CLI is slow:

  1. Check your internet connection
  2. Reduce context size by referencing specific files
  3. Use --checkpointing only when needed
  4. Monitor /stats for token usage patterns

The Future of Gemini CLI

Based on recent developments and community feedback, Gemini CLI is rapidly evolving:

Gemini 3 Flash Availability: The newest Gemini 3 Flash model represents an advancement in capabilities, offering improved reasoning and performance.

Expanded MCP Ecosystem: The growing library of MCP servers is making Gemini CLI increasingly powerful, with integrations for virtually every development tool and service.

Enhanced Automation: Future versions will likely include more sophisticated automation capabilities, including self-improving agents and workflow optimization.

Enterprise Features: Expect enhanced team collaboration features, centralized management, and organization-wide skill sharing.

Getting Started: Your First Steps

Ready to transform your terminal into an AI-powered development environment? Here's your action plan:

  1. Install Gemini CLI: Run npm install -g @google/gemini-cli
  2. Authenticate: Launch gemini and sign in with your Google account
  3. Create GEMINI.md: Document your project's conventions and architecture
  4. Build a custom command: Create your first workflow automation
  5. Explore MCP servers: Install a GitHub or Firebase MCP to extend functionality
  6. Join the community: Check out the official GitHub repository for updates and community contributions

Access Gemini Across All Your Tools with Metir AI

While Gemini CLI excels in terminal workflows, you might need Gemini's power in other contexts—chat interfaces, mobile apps, or alongside other AI models. Metir AI provides unified access to Gemini, ChatGPT, Claude, Grok, and Perplexity in one platform.

With Metir AI, you're not locked into a single provider. Use Gemini CLI for terminal workflows, and seamlessly switch to ChatGPT for creative writing, Claude for code review, or Perplexity for research—all within the same ecosystem.

Conclusion

Gemini CLI represents a fundamental shift in how developers interact with AI—from isolated chat conversations to integrated terminal workflows that understand your entire codebase. With its generous free tier, massive context window, and extensible architecture through MCP servers, it's positioned as one of the most powerful AI development tools available in 2026.

Whether you're debugging a complex issue, refactoring legacy code, automating documentation, or building custom development workflows, Gemini CLI provides the intelligence and flexibility to dramatically accelerate your productivity.

The future of development isn't just about writing code faster—it's about working smarter with AI that understands your context, your codebase, and your workflow. That future is here today with Gemini CLI.


Ready to experience Gemini alongside other leading AI models? Try Metir AI for unified access to Gemini, ChatGPT, Claude, and more—all in one powerful platform.

Sources

  • Gemini CLI Official Documentation
  • GitHub - google-gemini/gemini-cli
  • Hands-on with Gemini CLI | Google Codelabs
  • Gemini CLI: A Guide With Practical Examples | DataCamp
  • Google Gemini CLI Cheatsheet
  • Gemini CLI Tips & Tricks - by Addy Osmani
  • Testing AI coding agents (2025): Cursor vs. Claude, OpenAI, and Gemini | Render Blog
  • Gemini CLI 🤝 FastMCP: Simplifying MCP server development
  • MCP servers with the Gemini CLI | Gemini CLI
  • Best Practices for Using Gemini CLI

Ready to experience AI that adapts to you?

metir brings together the world's best AI models in one seamless experience. Start for free today.

Get Started Free
metir

Agentic Operating System for Professionals buried in meetings, emails and docs.

© 2026 metir. All rights reserved.

Product

  • Features
  • Pricing
  • Research
  • Blog
  • Enterprise

Company

  • Support
  • Careers

Legal

  • Terms of Service
  • Privacy Policy

Personalisation is powerful. Privacy is non-negotiable.

Status: All systems operational