βββ Uninstall.md Content:
Uninstalling the CLI
Your uninstall method depends on how you ran the CLI. Follow the instructions for either npx or a global npm installation.
Method 1: Using npx
npx runs packages from a temporary cache without a permanent installation. To "uninstall" the CLI, you must clear this cache, which will remove gemini-cli and any other packages previously executed with npx.
The npx cache is a directory named _npx inside your main npm cache folder. You can find your npm cache path by running npm config get cache.
For macOS / Linux
# The path is typically ~/.npm/_npx
rm -rf "$(npm config get cache)/_npx"
For Windows
Command Prompt
:: The path is typically %LocalAppData%\npm-cache\_npx
rmdir /s /q "%LocalAppData%\npm-cache\_npx"
PowerShell
# The path is typically $env:LocalAppData\npm-cache\_npx
Remove-Item -Path (Join-Path $env:LocalAppData "npm-cache\_npx") -Recurse -Force
Method 2: Using npm (Global Install)
If you installed the CLI globally (e.g., npm install -g @google/gemini-cli), use the npm uninstall command with the -g flag to remove it.
npm uninstall -g @google/gemini-cli
This command completely removes the package from your system.
βββ architecture.md Content:
Gemini CLI Architecture Overview
This document provides a high-level overview of the Gemini CLI's architecture.
Core components
The Gemini CLI is primarily composed of two main packages, along with a suite of tools that can be used by the system in the course of handling command-line input:
-
CLI package (
packages/cli):- Purpose: This contains the user-facing portion of the Gemini CLI, such as handling the initial user input, presenting the final output, and managing the overall user experience.
- Key functions contained in the package:
- Input processing
- History management
- Display rendering
- Theme and UI customization
- CLI configuration settings
-
Core package (
packages/core):- Purpose: This acts as the backend for the Gemini CLI. It receives requests sent from
packages/cli, orchestrates interactions with the Gemini API, and manages the execution of available tools. - Key functions contained in the package:
- API client for communicating with the Google Gemini API
- Prompt construction and management
- Tool registration and execution logic
- State management for conversations or sessions
- Server-side configuration
- Purpose: This acts as the backend for the Gemini CLI. It receives requests sent from
-
Tools (
packages/core/src/tools/):- Purpose: These are individual modules that extend the capabilities of the Gemini model, allowing it to interact with the local environment (e.g., file system, shell commands, web fetching).
- Interaction:
packages/coreinvokes these tools based on requests from the Gemini model.
Interaction Flow
A typical interaction with the Gemini CLI follows this flow:
- User input: The user types a prompt or command into the terminal, which is managed by
packages/cli. - Request to core:
packages/clisends the user's input topackages/core. - Request processed: The core package:
- Constructs an appropriate prompt for the Gemini API, possibly including conversation history and available tool definitions.
- Sends the prompt to the Gemini API.
- Gemini API response: The Gemini API processes the prompt and returns a response. This response might be a direct answer or a request to use one of the available tools.
- Tool execution (if applicable):
- When the Gemini API requests a tool, the core package prepares to execute it.
- If the requested tool can modify the file system or execute shell commands, the user is first given details of the tool and its arguments, and the user must approve the execution.
- Read-only operations, such as reading files, might not require explicit user confirmation to proceed.
- Once confirmed, or if confirmation is not required, the core package executes the relevant action within the relevant tool, and the result is sent back to the Gemini API by the core package.
- The Gemini API processes the tool result and generates a final response.
- Response to CLI: The core package sends the final response back to the CLI package.
- Display to user: The CLI package formats and displays the response to the user in the terminal.
Key Design Principles
- Modularity: Separating the CLI (frontend) from the Core (backend) allows for independent development and potential future extensions (e.g., different frontends for the same backend).
- Extensibility: The tool system is designed to be extensible, allowing new capabilities to be added.
- User experience: The CLI focuses on providing a rich and interactive terminal experience.
βββ assets/ βββ connected_devtools.png [Error processing file]
βββ gemini-screenshot.png [Error processing file]
βββ theme-ansi-light.png [Error processing file]
βββ theme-ansi.png [Error processing file]
βββ theme-atom-one.png [Error processing file]
βββ theme-ayu-light.png [Error processing file]
βββ theme-ayu.png [Error processing file]
βββ theme-custom.png [Error processing file]
βββ theme-default-light.png [Error processing file]
βββ theme-default.png [Error processing file]
βββ theme-dracula.png [Error processing file]
βββ theme-github-light.png [Error processing file]
βββ theme-github.png [Error processing file]
βββ theme-google-light.png [Error processing file]
βββ theme-xcode-light.png [Error processing file]
βββ checkpointing.md Content:
Checkpointing
The Gemini CLI includes a Checkpointing feature that automatically saves a snapshot of your project's state before any file modifications are made by AI-powered tools. This allows you to safely experiment with and apply code changes, knowing you can instantly revert back to the state before the tool was run.
How It Works
When you approve a tool that modifies the file system (like write_file or replace), the CLI automatically creates a "checkpoint." This checkpoint includes:
- A Git Snapshot: A commit is made in a special, shadow Git repository located in your home directory (
~/.gemini/history/<project_hash>). This snapshot captures the complete state of your project files at that moment. It does not interfere with your own project's Git repository. - Conversation History: The entire conversation you've had with the agent up to that point is saved.
- The Tool Call: The specific tool call that was about to be executed is also stored.
If you want to undo the change or simply go back, you can use the /restore command. Restoring a checkpoint will:
- Revert all files in your project to the state captured in the snapshot.
- Restore the conversation history in the CLI.
- Re-propose the original tool call, allowing you to run it again, modify it, or simply ignore it.
All checkpoint data, including the Git snapshot and conversation history, is stored locally on your machine. The Git snapshot is stored in the shadow repository while the conversation history and tool calls are saved in a JSON file in your project's temporary directory, typically located at ~/.gemini/tmp/<project_hash>/checkpoints.
Enabling the Feature
The Checkpointing feature is disabled by default. To enable it, you can either use a command-line flag or edit your settings.json file.
Using the Command-Line Flag
You can enable checkpointing for the current session by using the --checkpointing flag when starting the Gemini CLI:
gemini --checkpointing
Using the settings.json File
To enable checkpointing by default for all sessions, you need to edit your settings.json file.
Add the following key to your settings.json:
{
"checkpointing": {
"enabled": true
}
}
Using the /restore Command
Once enabled, checkpoints are created automatically. To manage them, you use the /restore command.
List Available Checkpoints
To see a list of all saved checkpoints for the current project, simply run:
/restore
The CLI will display a list of available checkpoint files. These file names are typically composed of a timestamp, the name of the file being modified, and the name of the tool that was about to be run (e.g., 2025-06-22T10-00-00_000Z-my-file.txt-write_file).
Restore a Specific Checkpoint
To restore your project to a specific checkpoint, use the checkpoint file from the list:
/restore <checkpoint_file>
For example:
/restore 2025-06-22T10-00-00_000Z-my-file.txt-write_file
After running the command, your files and conversation will be immediately restored to the state they were in when the checkpoint was created, and the original tool prompt will reappear.
βββ cli/ βββ authentication.md Content:
Authentication Setup
The Gemini CLI requires you to authenticate with Google's AI services. On initial startup you'll need to configure one of the following authentication methods:
-
Login with Google (Gemini Code Assist):
- Use this option to log in with your Google account.
- During initial startup, Gemini CLI will direct you to a webpage for authentication. Once authenticated, your credentials will be cached locally so the web login can be skipped on subsequent runs.
- Note that the web login must be done in a browser that can communicate with the machine Gemini CLI is being run from. (Specifically, the browser will be redirected to a localhost url that Gemini CLI will be listening on).
- Users may have to specify a GOOGLE_CLOUD_PROJECT if:
- You have a Google Workspace account. Google Workspace is a paid service for businesses and organizations that provides a suite of productivity tools, including a custom email domain (e.g. your-name@your-company.com), enhanced security features, and administrative controls. These accounts are often managed by an employer or school.
- You have received a Gemini Code Assist license through the Google Developer Program (including qualified Google Developer Experts)
- You have been assigned a license to a current Gemini Code Assist standard or enterprise subscription.
- You are using the product outside the supported regions for free individual usage.
- You are a Google account holder under the age of 18
- If you fall into one of these categories, you must first configure a Google Cloud Project ID to use, enable the Gemini for Cloud API and configure access permissions.
You can temporarily set the environment variable in your current shell session using the following command:
bash export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"- For repeated use, you can add the environment variable to your .env file or your shell's configuration file (like~/.bashrc,~/.zshrc, or~/.profile). For example, the following command adds the environment variable to a~/.bashrcfile:bash echo 'export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"' >> ~/.bashrc source ~/.bashrc -
- Obtain your API key from Google AI Studio: https://aistudio.google.com/app/apikey
- Set the
GEMINI_API_KEYenvironment variable. In the following methods, replaceYOUR_GEMINI_API_KEYwith the API key you obtained from Google AI Studio: - You can temporarily set the environment variable in your current shell session using the following command:
bash export GEMINI_API_KEY="YOUR_GEMINI_API_KEY" -
For repeated use, you can add the environment variable to your .env file.
-
Alternatively you can export the API key from your shell's configuration file (like
~/.bashrc,~/.zshrc, or~/.profile). For example, the following command adds the environment variable to a~/.bashrcfile:bash echo 'export GEMINI_API_KEY="YOUR_GEMINI_API_KEY"' >> ~/.bashrc source ~/.bashrc:warning: Be advised that when you export your API key inside your shell configuration file, any other process executed from the shell can read it.
-
Vertex AI:
- Obtain your Google Cloud API key: Get an API Key
- Set the
GOOGLE_API_KEYenvironment variable. In the following methods, replaceYOUR_GOOGLE_API_KEYwith your Vertex AI API key:- You can temporarily set these environment variables in your current shell session using the following commands:
bash export GOOGLE_API_KEY="YOUR_GOOGLE_API_KEY" - For repeated use, you can add the environment variables to your .env file or your shell's configuration file (like
~/.bashrc,~/.zshrc, or~/.profile). For example, the following commands add the environment variables to a~/.bashrcfile:bash echo 'export GOOGLE_API_KEY="YOUR_GOOGLE_API_KEY"' >> ~/.bashrc source ~/.bashrc
- You can temporarily set these environment variables in your current shell session using the following commands:
- To use Application Default Credentials (ADC), use the following command:
- Ensure you have a Google Cloud project and have enabled the Vertex AI API.
bash gcloud auth application-default loginFor more information, see Set up Application Default Credentials for Google Cloud. -
Set the
GOOGLE_CLOUD_PROJECTandGOOGLE_CLOUD_LOCATIONenvironment variables. In the following methods, replaceYOUR_PROJECT_IDandYOUR_PROJECT_LOCATIONwith the relevant values for your project:- You can temporarily set these environment variables in your current shell session using the following commands:
bash export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID" export GOOGLE_CLOUD_LOCATION="YOUR_PROJECT_LOCATION" # e.g., us-central1 -
For repeated use, you can add the environment variables to your .env file
-
Alternatively you can export the environment variables from your shell's configuration file (like
~/.bashrc,~/.zshrc, or~/.profile). For example, the following commands add the environment variables to a~/.bashrcfile:
bash echo 'export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"' >> ~/.bashrc echo 'export GOOGLE_CLOUD_LOCATION="YOUR_PROJECT_LOCATION"' >> ~/.bashrc source ~/.bashrc:warning: Be advised that when you export your API key inside your shell configuration file, any other process executed from the shell can read it.
- You can temporarily set these environment variables in your current shell session using the following commands:
-
Cloud Shell:
- This option is only available when running in a Google Cloud Shell environment.
- It automatically uses the credentials of the logged-in user in the Cloud Shell environment.
-
This is the default authentication method when running in Cloud Shell and no other method is configured.
:warning: Be advised that when you export your API key inside your shell configuration file, any other process executed from the shell can read it.
Persisting Environment Variables with .env Files
You can create a .gemini/.env file in your project directory or in your home directory. Creating a plain .env file also works, but .gemini/.env is recommended to keep Gemini variables isolated from other tools.
Important: Some environment variables (like DEBUG and DEBUG_MODE) are automatically excluded from project .env files to prevent interference with gemini-cli behavior. Use .gemini/.env files for gemini-cli specific variables.
Gemini CLI automatically loads environment variables from the first .env file it finds, using the following search order:
- Starting in the current directory and moving upward toward
/, for each directory it checks: .gemini/.env.env- If no file is found, it falls back to your home directory:
~/.gemini/.env~/.env
Important: The search stops at the first file encounteredβvariables are not merged across multiple files.
Examples
Project-specific overrides (take precedence when you are inside the project):
mkdir -p .gemini
echo 'GOOGLE_CLOUD_PROJECT="your-project-id"' >> .gemini/.env
User-wide settings (available in every directory):
mkdir -p ~/.gemini
cat >> ~/.gemini/.env <<'EOF'
GOOGLE_CLOUD_PROJECT="your-project-id"
GEMINI_API_KEY="your-gemini-api-key"
EOF
Non-Interactive Mode / Headless Environments
When running the Gemini CLI in a non-interactive environment, you cannot use the interactive login flow. Instead, you must configure authentication using environment variables.
The CLI will automatically detect if it is running in a non-interactive terminal and will use one of the following authentication methods if available:
-
Gemini API Key:
- Set the
GEMINI_API_KEYenvironment variable. - The CLI will use this key to authenticate with the Gemini API.
- Set the
-
Vertex AI:
- Set the
GOOGLE_GENAI_USE_VERTEXAI=trueenvironment variable. - Using an API Key: Set the
GOOGLE_API_KEYenvironment variable. - Using Application Default Credentials (ADC):
- Run
gcloud auth application-default loginin your environment to configure ADC. - Ensure the
GOOGLE_CLOUD_PROJECTandGOOGLE_CLOUD_LOCATIONenvironment variables are set.
- Set the
If none of these environment variables are set in a non-interactive session, the CLI will exit with an error.
βββ commands.md Content:
CLI Commands
Gemini CLI supports several built-in commands to help you manage your session, customize the interface, and control its behavior. These commands are prefixed with a forward slash (/), an at symbol (@), or an exclamation mark (!).
Slash commands (/)
Slash commands provide meta-level control over the CLI itself.
Built-in Commands
/bug-
Description: File an issue about Gemini CLI. By default, the issue is filed within the GitHub repository for Gemini CLI. The string you enter after
/bugwill become the headline for the bug being filed. The default/bugbehavior can be modified using thebugCommandsetting in your.gemini/settings.jsonfiles. -
/chat - Description: Save and resume conversation history for branching conversation state interactively, or resuming a previous state from a later session.
-
Sub-commands:
save- Description: Saves the current conversation history. You must add a
<tag>for identifying the conversation state. - Usage:
/chat save <tag> - Details on Checkpoint Location: The default locations for saved chat checkpoints are:
- Linux/macOS:
~/.config/google-generative-ai/checkpoints/ - Windows:
C:\Users\<YourUsername>\AppData\Roaming\google-generative-ai\checkpoints\ - When you run
/chat list, the CLI only scans these specific directories to find available checkpoints. - Note: These checkpoints are for manually saving and resuming conversation states. For automatic checkpoints created before file modifications, see the Checkpointing documentation.
- Linux/macOS:
resume- Description: Resumes a conversation from a previous save.
- Usage:
/chat resume <tag> list- Description: Lists available tags for chat state resumption.
delete- Description: Deletes a saved conversation checkpoint.
- Usage:
/chat delete <tag>
-
/clear - Description: Clear the terminal screen, including the visible session history and scrollback within the CLI. The underlying session data (for history recall) might be preserved depending on the exact implementation, but the visual display is cleared.
-
Keyboard shortcut: Press Ctrl+L at any time to perform a clear action.
-
/compress -
Description: Replace the entire chat context with a summary. This saves on tokens used for future tasks while retaining a high level summary of what has happened.
-
/copy -
Description: Copies the last output produced by Gemini CLI to your clipboard, for easy sharing or reuse.
-
/directory(or/dir) - Description: Manage workspace directories for multi-directory support.
-
Sub-commands:
add:- Description: Add a directory to the workspace. The path can be absolute or relative to the current working directory. Moreover, the reference from home directory is supported as well.
- Usage:
/directory add <path1>,<path2> - Note: Disabled in restrictive sandbox profiles. If you're using that, use
--include-directorieswhen starting the session instead. show:- Description: Display all directories added by
/directory addand--include-directories. - Usage:
/directory show
-
/editor -
Description: Open a dialog for selecting supported editors.
-
/extensions -
Description: Lists all active extensions in the current Gemini CLI session. See Gemini CLI Extensions.
-
/help(or/?) -
Description: Display help information about Gemini CLI, including available commands and their usage.
-
/mcp - Description: List configured Model Context Protocol (MCP) servers, their connection status, server details, and available tools.
- Sub-commands:
descordescriptions:- Description: Show detailed descriptions for MCP servers and tools.
nodescornodescriptions:- Description: Hide tool descriptions, showing only the tool names.
schema:- Description: Show the full JSON schema for the tool's configured parameters.
-
Keyboard Shortcut: Press Ctrl+T at any time to toggle between showing and hiding tool descriptions.
-
/memory - Description: Manage the AI's instructional context (hierarchical memory loaded from
GEMINI.mdfiles). -
Sub-commands:
add:- Description: Adds the following text to the AI's memory. Usage:
/memory add <text to remember> show:- Description: Display the full, concatenated content of the current hierarchical memory that has been loaded from all
GEMINI.mdfiles. This lets you inspect the instructional context being provided to the Gemini model. refresh:- Description: Reload the hierarchical instructional memory from all
GEMINI.mdfiles found in the configured locations (global, project/ancestors, and sub-directories). This command updates the model with the latestGEMINI.mdcontent. - Note: For more details on how
GEMINI.mdfiles contribute to hierarchical memory, see the CLI Configuration documentation.
-
/restore - Description: Restores the project files to the state they were in just before a tool was executed. This is particularly useful for undoing file edits made by a tool. If run without a tool call ID, it will list available checkpoints to restore from.
- Usage:
/restore [tool_call_id] -
Note: Only available if the CLI is invoked with the
--checkpointingoption or configured via settings. See Checkpointing documentation for more details. -
/stats -
Description: Display detailed statistics for the current Gemini CLI session, including token usage, cached token savings (when available), and session duration. Note: Cached token information is only displayed when cached tokens are being used, which occurs with API key authentication but not with OAuth authentication at this time.
-
Description: Open a dialog that lets you change the visual theme of Gemini CLI.
-
/auth -
Description: Open a dialog that lets you change the authentication method.
-
/about -
Description: Show version info. Please share this information when filing issues.
- Description: Display a list of tools that are currently available within Gemini CLI.
-
Sub-commands:
descordescriptions:- Description: Show detailed descriptions of each tool, including each tool's name with its full description as provided to the model.
nodescornodescriptions:- Description: Hide tool descriptions, showing only the tool names.
-
/privacy -
Description: Display the Privacy Notice and allow users to select whether they consent to the collection of their data for service improvement purposes.
-
/quit(or/exit) -
Description: Exit Gemini CLI.
-
/vim - Description: Toggle vim mode on or off. When vim mode is enabled, the input area supports vim-style navigation and editing commands in both NORMAL and INSERT modes.
- Features:
- NORMAL mode: Navigate with
h,j,k,l; jump by words withw,b,e; go to line start/end with0,$,^; go to specific lines withG(orggfor first line) - INSERT mode: Standard text input with escape to return to NORMAL mode
- Editing commands: Delete with
x, change withc, insert withi,a,o,O; complex operations likedd,cc,dw,cw - Count support: Prefix commands with numbers (e.g.,
3h,5w,10G) - Repeat last command: Use
.to repeat the last editing operation - Persistent setting: Vim mode preference is saved to
~/.gemini/settings.jsonand restored between sessions
- NORMAL mode: Navigate with
-
Status indicator: When enabled, shows
[NORMAL]or[INSERT]in the footer -
/init - Description: To help users easily create a
GEMINI.mdfile, this command analyzes the current directory and generates a tailored context file, making it simpler for them to provide project-specific instructions to the Gemini agent.
Custom Commands
For a quick start, see the example below.
Custom commands allow you to save and reuse your favorite or most frequently used prompts as personal shortcuts within Gemini CLI. You can create commands that are specific to a single project or commands that are available globally across all your projects, streamlining your workflow and ensuring consistency.
File Locations & Precedence
Gemini CLI discovers commands from two locations, loaded in a specific order:
- User Commands (Global): Located in
~/.gemini/commands/. These commands are available in any project you are working on. - Project Commands (Local): Located in
<your-project-root>/.gemini/commands/. These commands are specific to the current project and can be checked into version control to be shared with your team.
If a command in the project directory has the same name as a command in the user directory, the project command will always be used. This allows projects to override global commands with project-specific versions.
Naming and Namespacing
The name of a command is determined by its file path relative to its commands directory. Subdirectories are used to create namespaced commands, with the path separator (/ or \) being converted to a colon (:).
- A file at
~/.gemini/commands/test.tomlbecomes the command/test. - A file at
<project>/.gemini/commands/git/commit.tomlbecomes the namespaced command/git:commit.
TOML File Format (v1)
Your command definition files must be written in the TOML format and use the .toml file extension.
Required Fields
prompt(String): The prompt that will be sent to the Gemini model when the command is executed. This can be a single-line or multi-line string.
Optional Fields
description(String): A brief, one-line description of what the command does. This text will be displayed next to your command in the/helpmenu. If you omit this field, a generic description will be generated from the filename.
Handling Arguments
Custom commands support two powerful, low-friction methods for handling arguments. The CLI automatically chooses the correct method based on the content of your command's prompt.
1. Shorthand Injection with {{args}}
If your prompt contains the special placeholder {{args}}, the CLI will replace that exact placeholder with all the text the user typed after the command name. This is perfect for simple, deterministic commands where you need to inject user input into a specific place in a larger prompt template.
Example (git/fix.toml):
# In: ~/.gemini/commands/git/fix.toml
# Invoked via: /git:fix "Button is misaligned on mobile"
description = "Generates a fix for a given GitHub issue."
prompt = "Please analyze the staged git changes and provide a code fix for the issue described here: {{args}}."
The model will receive the final prompt: Please analyze the staged git changes and provide a code fix for the issue described here: "Button is misaligned on mobile".
2. Default Argument Handling
If your prompt does not contain the special placeholder {{args}}, the CLI uses a default behavior for handling arguments.
If you provide arguments to the command (e.g., /mycommand arg1), the CLI will append the full command you typed to the end of the prompt, separated by two newlines. This allows the model to see both the original instructions and the specific arguments you just provided.
If you do not provide any arguments (e.g., /mycommand), the prompt is sent to the model exactly as it is, with nothing appended.
Example (changelog.toml):
This example shows how to create a robust command by defining a role for the model, explaining where to find the user's input, and specifying the expected format and behavior.
# In: <project>/.gemini/commands/changelog.toml
# Invoked via: /changelog 1.2.0 added "Support for default argument parsing."
description = "Adds a new entry to the project's CHANGELOG.md file."
prompt = """
# Task: Update Changelog
You are an expert maintainer of this software project. A user has invoked a command to add a new entry to the changelog.
**The user's raw command is appended below your instructions.**
Your task is to parse the `<version>`, `<change_type>`, and `<message>` from their input and use the `write_file` tool to correctly update the `CHANGELOG.md` file.
## Expected Format
The command follows this format: `/changelog <version> <type> <message>`
- `<type>` must be one of: "added", "changed", "fixed", "removed".
## Behavior
1. Read the `CHANGELOG.md` file.
2. Find the section for the specified `<version>`.
3. Add the `<message>` under the correct `<type>` heading.
4. If the version or type section doesn't exist, create it.
5. Adhere strictly to the "Keep a Changelog" format.
"""
When you run /changelog 1.2.0 added "New feature", the final text sent to the model will be the original prompt followed by two newlines and the command you typed.
3. Executing Shell Commands with !{...}
You can make your commands dynamic by executing shell commands directly within your prompt and injecting their output. This is ideal for gathering context from your local environment, like reading file content or checking the status of Git.
When a custom command attempts to execute a shell command, Gemini CLI will now prompt you for confirmation before proceeding. This is a security measure to ensure that only intended commands can be run.
How It Works:
- Inject Commands: Use the
!{...}syntax in yourpromptto specify where the command should be run and its output injected. - Confirm Execution: When you run the command, a dialog will appear listing the shell commands the prompt wants to execute.
- Grant Permission: You can choose to:
- Allow once: The command(s) will run this one time.
- Allow always for this session: The command(s) will be added to a temporary allowlist for the current CLI session and will not require confirmation again.
- No: Cancel the execution of the shell command(s).
The CLI still respects the global excludeTools and coreTools settings. A command will be blocked without a confirmation prompt if it is explicitly disallowed in your configuration.
Example (git/commit.toml):
This command gets the staged git diff and uses it to ask the model to write a commit message.
# In: <project>/.gemini/commands/git/commit.toml
# Invoked via: /git:commit
description = "Generates a Git commit message based on staged changes."
# The prompt uses !{...} to execute the command and inject its output.
prompt = """
Please generate a Conventional Commit message based on the following git diff:
```diff
!{git diff --staged}
```
"""
When you run /git:commit, the CLI first executes git diff --staged, then replaces !{git diff --staged} with the output of that command before sending the final, complete prompt to the model.
Example: A "Pure Function" Refactoring Command
Let's create a global command that asks the model to refactor a piece of code.
1. Create the file and directories:
First, ensure the user commands directory exists, then create a refactor subdirectory for organization and the final TOML file.
mkdir -p ~/.gemini/commands/refactor
touch ~/.gemini/commands/refactor/pure.toml
2. Add the content to the file:
Open ~/.gemini/commands/refactor/pure.toml in your editor and add the following content. We are including the optional description for best practice.
# In: ~/.gemini/commands/refactor/pure.toml
# This command will be invoked via: /refactor:pure
description = "Asks the model to refactor the current context into a pure function."
prompt = """
Please analyze the code I've provided in the current context.
Refactor it into a pure function.
Your response should include:
1. The refactored, pure function code block.
2. A brief explanation of the key changes you made and why they contribute to purity.
"""
3. Run the Command:
That's it! You can now run your command in the CLI. First, you might add a file to the context, and then invoke your command:
> @my-messy-function.js
> /refactor:pure
Gemini CLI will then execute the multi-line prompt defined in your TOML file.
At commands (@)
At commands are used to include the content of files or directories as part of your prompt to Gemini. These commands include git-aware filtering.
@<path_to_file_or_directory>- Description: Inject the content of the specified file or files into your current prompt. This is useful for asking questions about specific code, text, or collections of files.
- Examples:
@path/to/your/file.txt Explain this text.@src/my_project/ Summarize the code in this directory.What is this file about? @README.md
- Details:
- If a path to a single file is provided, the content of that file is read.
- If a path to a directory is provided, the command attempts to read the content of files within that directory and any subdirectories.
- Spaces in paths should be escaped with a backslash (e.g.,
@My\ Documents/file.txt). - The command uses the
read_many_filestool internally. The content is fetched and then inserted into your query before being sent to the Gemini model. - Git-aware filtering: By default, git-ignored files (like
node_modules/,dist/,.env,.git/) are excluded. This behavior can be changed via thefileFilteringsettings. - File types: The command is intended for text-based files. While it might attempt to read any file, binary files or very large files might be skipped or truncated by the underlying
read_many_filestool to ensure performance and relevance. The tool indicates if files were skipped.
-
Output: The CLI will show a tool call message indicating that
read_many_fileswas used, along with a message detailing the status and the path(s) that were processed. -
@(Lone at symbol) - Description: If you type a lone
@symbol without a path, the query is passed as-is to the Gemini model. This might be useful if you are specifically talking about the@symbol in your prompt.
Error handling for @ commands
- If the path specified after
@is not found or is invalid, an error message will be displayed, and the query might not be sent to the Gemini model, or it will be sent without the file content. - If the
read_many_filestool encounters an error (e.g., permission issues), this will also be reported.
Shell mode & passthrough commands (!)
The ! prefix lets you interact with your system's shell directly from within Gemini CLI.
!<shell_command>- Description: Execute the given
<shell_command>usingbashon Linux/macOS orcmd.exeon Windows. Any output or errors from the command are displayed in the terminal. -
Examples:
!ls -la(executesls -laand returns to Gemini CLI)!git status(executesgit statusand returns to Gemini CLI)
-
!(Toggle shell mode) -
Description: Typing
!on its own toggles shell mode.- Entering shell mode:
- When active, shell mode uses a different coloring and a "Shell Mode Indicator".
- While in shell mode, text you type is interpreted directly as a shell command.
- Exiting shell mode:
- When exited, the UI reverts to its standard appearance and normal Gemini CLI behavior resumes.
-
Caution for all
!usage: Commands you execute in shell mode have the same permissions and impact as if you ran them directly in your terminal. -
Environment Variable: When a command is executed via
!or in shell mode, theGEMINI_CLI=1environment variable is set in the subprocess's environment. This allows scripts or tools to detect if they are being run from within the Gemini CLI.
βββ configuration.md Content:
Gemini CLI Configuration
Gemini CLI offers several ways to configure its behavior, including environment variables, command-line arguments, and settings files. This document outlines the different configuration methods and available settings.
Configuration layers
Configuration is applied in the following order of precedence (lower numbers are overridden by higher numbers):
- Default values: Hardcoded defaults within the application.
- User settings file: Global settings for the current user.
- Project settings file: Project-specific settings.
- System settings file: System-wide settings.
- Environment variables: System-wide or session-specific variables, potentially loaded from
.envfiles. - Command-line arguments: Values passed when launching the CLI.
Settings files
Gemini CLI uses settings.json files for persistent configuration. There are three locations for these files:
- User settings file:
- Location:
~/.gemini/settings.json(where~is your home directory). - Scope: Applies to all Gemini CLI sessions for the current user.
- Project settings file:
- Location:
.gemini/settings.jsonwithin your project's root directory. - Scope: Applies only when running Gemini CLI from that specific project. Project settings override user settings.
- System settings file:
- Location:
/etc/gemini-cli/settings.json(Linux),C:\ProgramData\gemini-cli\settings.json(Windows) or/Library/Application Support/GeminiCli/settings.json(macOS). The path can be overridden using theGEMINI_CLI_SYSTEM_SETTINGS_PATHenvironment variable. - Scope: Applies to all Gemini CLI sessions on the system, for all users. System settings override user and project settings. May be useful for system administrators at enterprises to have controls over users' Gemini CLI setups.
Note on environment variables in settings: String values within your settings.json files can reference environment variables using either $VAR_NAME or ${VAR_NAME} syntax. These variables will be automatically resolved when the settings are loaded. For example, if you have an environment variable MY_API_TOKEN, you could use it in settings.json like this: "apiKey": "$MY_API_TOKEN".
The .gemini directory in your project
In addition to a project settings file, a project's .gemini directory can contain other project-specific files related to Gemini CLI's operation, such as:
- Custom sandbox profiles (e.g.,
.gemini/sandbox-macos-custom.sb,.gemini/sandbox.Dockerfile).
Available settings in settings.json:
contextFileName(string or array of strings):- Description: Specifies the filename for context files (e.g.,
GEMINI.md,AGENTS.md). Can be a single filename or a list of accepted filenames. - Default:
GEMINI.md -
Example:
"contextFileName": "AGENTS.md" -
bugCommand(object): - Description: Overrides the default URL for the
/bugcommand. - Default:
"urlTemplate": "https://github.com/google-gemini/gemini-cli/issues/new?template=bug_report.yml&title={title}&info={info}" - Properties:
urlTemplate(string): A URL that can contain{title}and{info}placeholders.
-
Example:
json "bugCommand": { "urlTemplate": "https://bug.example.com/new?title={title}&info={info}" } -
fileFiltering(object): - Description: Controls git-aware file filtering behavior for @ commands and file discovery tools.
- Default:
"respectGitIgnore": true, "enableRecursiveFileSearch": true - Properties:
respectGitIgnore(boolean): Whether to respect .gitignore patterns when discovering files. When set totrue, git-ignored files (likenode_modules/,dist/,.env) are automatically excluded from @ commands and file listing operations.enableRecursiveFileSearch(boolean): Whether to enable searching recursively for filenames under the current tree when completing @ prefixes in the prompt.
-
Example:
json "fileFiltering": { "respectGitIgnore": true, "enableRecursiveFileSearch": false } -
coreTools(array of strings): - Description: Allows you to specify a list of core tool names that should be made available to the model. This can be used to restrict the set of built-in tools. See Built-in Tools for a list of core tools. You can also specify command-specific restrictions for tools that support it, like the
ShellTool. For example,"coreTools": ["ShellTool(ls -l)"]will only allow thels -lcommand to be executed. - Default: All tools available for use by the Gemini model.
-
Example:
"coreTools": ["ReadFileTool", "GlobTool", "ShellTool(ls)"]. -
excludeTools(array of strings): - Description: Allows you to specify a list of core tool names that should be excluded from the model. A tool listed in both
excludeToolsandcoreToolsis excluded. You can also specify command-specific restrictions for tools that support it, like theShellTool. For example,"excludeTools": ["ShellTool(rm -rf)"]will block therm -rfcommand. - Default: No tools excluded.
- Example:
"excludeTools": ["run_shell_command", "findFiles"]. -
Security Note: Command-specific restrictions in
excludeToolsforrun_shell_commandare based on simple string matching and can be easily bypassed. This feature is not a security mechanism and should not be relied upon to safely execute untrusted code. It is recommended to usecoreToolsto explicitly select commands that can be executed. -
allowMCPServers(array of strings): - Description: Allows you to specify a list of MCP server names that should be made available to the model. This can be used to restrict the set of MCP servers to connect to. Note that this will be ignored if
--allowed-mcp-server-namesis set. - Default: All MCP servers are available for use by the Gemini model.
- Example:
"allowMCPServers": ["myPythonServer"]. -
Security Note: This uses simple string matching on MCP server names, which can be modified. If you're a system administrator looking to prevent users from bypassing this, consider configuring the
mcpServersat the system settings level such that the user will not be able to configure any MCP servers of their own. This should not be used as an airtight security mechanism. -
excludeMCPServers(array of strings): - Description: Allows you to specify a list of MCP server names that should be excluded from the model. A server listed in both
excludeMCPServersandallowMCPServersis excluded. Note that this will be ignored if--allowed-mcp-server-namesis set. - Default: No MCP servers excluded.
- Example:
"excludeMCPServers": ["myNodeServer"]. -
Security Note: This uses simple string matching on MCP server names, which can be modified. If you're a system administrator looking to prevent users from bypassing this, consider configuring the
mcpServersat the system settings level such that the user will not be able to configure any MCP servers of their own. This should not be used as an airtight security mechanism. -
autoAccept(boolean): - Description: Controls whether the CLI automatically accepts and executes tool calls that are considered safe (e.g., read-only operations) without explicit user confirmation. If set to
true, the CLI will bypass the confirmation prompt for tools deemed safe. - Default:
false -
Example:
"autoAccept": true -
theme(string): - Description: Sets the visual theme for Gemini CLI.
- Default:
"Default" -
Example:
"theme": "GitHub" -
vimMode(boolean): - Description: Enables or disables vim mode for input editing. When enabled, the input area supports vim-style navigation and editing commands with NORMAL and INSERT modes. The vim mode status is displayed in the footer and persists between sessions.
- Default:
false -
Example:
"vimMode": true -
sandbox(boolean or string): - Description: Controls whether and how to use sandboxing for tool execution. If set to
true, Gemini CLI uses a pre-builtgemini-cli-sandboxDocker image. For more information, see Sandboxing. - Default:
false -
Example:
"sandbox": "docker" -
toolDiscoveryCommand(string): - Description: Defines a custom shell command for discovering tools from your project. The shell command must return on
stdouta JSON array of function declarations. Tool wrappers are optional. - Default: Empty
-
Example:
"toolDiscoveryCommand": "bin/get_tools" -
toolCallCommand(string): - Description: Defines a custom shell command for calling a specific tool that was discovered using
toolDiscoveryCommand. The shell command must meet the following criteria:- It must take function
name(exactly as in function declaration) as first command line argument. - It must read function arguments as JSON on
stdin, analogous tofunctionCall.args. - It must return function output as JSON on
stdout, analogous tofunctionResponse.response.content.
- It must take function
- Default: Empty
-
Example:
"toolCallCommand": "bin/call_tool" -
mcpServers(object): - Description: Configures connections to one or more Model-Context Protocol (MCP) servers for discovering and using custom tools. Gemini CLI attempts to connect to each configured MCP server to discover available tools. If multiple MCP servers expose a tool with the same name, the tool names will be prefixed with the server alias you defined in the configuration (e.g.,
serverAlias__actualToolName) to avoid conflicts. Note that the system might strip certain schema properties from MCP tool definitions for compatibility. - Default: Empty
- Properties:
<SERVER_NAME>(object): The server parameters for the named server.command(string, required): The command to execute to start the MCP server.args(array of strings, optional): Arguments to pass to the command.env(object, optional): Environment variables to set for the server process.cwd(string, optional): The working directory in which to start the server.timeout(number, optional): Timeout in milliseconds for requests to this MCP server.trust(boolean, optional): Trust this server and bypass all tool call confirmations.includeTools(array of strings, optional): List of tool names to include from this MCP server. When specified, only the tools listed here will be available from this server (whitelist behavior). If not specified, all tools from the server are enabled by default.excludeTools(array of strings, optional): List of tool names to exclude from this MCP server. Tools listed here will not be available to the model, even if they are exposed by the server. Note:excludeToolstakes precedence overincludeTools- if a tool is in both lists, it will be excluded.
-
Example:
json "mcpServers": { "myPythonServer": { "command": "python", "args": ["mcp_server.py", "--port", "8080"], "cwd": "./mcp_tools/python", "timeout": 5000, "includeTools": ["safe_tool", "file_reader"], }, "myNodeServer": { "command": "node", "args": ["mcp_server.js"], "cwd": "./mcp_tools/node", "excludeTools": ["dangerous_tool", "file_deleter"] }, "myDockerServer": { "command": "docker", "args": ["run", "-i", "--rm", "-e", "API_KEY", "ghcr.io/foo/bar"], "env": { "API_KEY": "$MY_API_TOKEN" } } } -
checkpointing(object): - Description: Configures the checkpointing feature, which allows you to save and restore conversation and file states. See the Checkpointing documentation for more details.
- Default:
{"enabled": false} -
Properties:
enabled(boolean): Whentrue, the/restorecommand is available.
-
preferredEditor(string): - Description: Specifies the preferred editor to use for viewing diffs.
- Default:
vscode -
Example:
"preferredEditor": "vscode" -
telemetry(object) - Description: Configures logging and metrics collection for Gemini CLI. For more information, see Telemetry.
- Default:
{"enabled": false, "target": "local", "otlpEndpoint": "http://localhost:4317", "logPrompts": true} - Properties:
enabled(boolean): Whether or not telemetry is enabled.target(string): The destination for collected telemetry. Supported values arelocalandgcp.otlpEndpoint(string): The endpoint for the OTLP Exporter.logPrompts(boolean): Whether or not to include the content of user prompts in the logs.
- Example:
json "telemetry": { "enabled": true, "target": "local", "otlpEndpoint": "http://localhost:16686", "logPrompts": false } usageStatisticsEnabled(boolean):- Description: Enables or disables the collection of usage statistics. See Usage Statistics for more information.
- Default:
true -
Example:
json "usageStatisticsEnabled": false -
hideTips(boolean): - Description: Enables or disables helpful tips in the CLI interface.
- Default:
false -
Example:
json "hideTips": true -
hideBanner(boolean): - Description: Enables or disables the startup banner (ASCII art logo) in the CLI interface.
- Default:
false -
Example:
json "hideBanner": true -
maxSessionTurns(number): - Description: Sets the maximum number of turns for a session. If the session exceeds this limit, the CLI will stop processing and start a new chat.
- Default:
-1(unlimited) -
Example:
json "maxSessionTurns": 10 -
summarizeToolOutput(object): - Description: Enables or disables the summarization of tool output. You can specify the token budget for the summarization using the
tokenBudgetsetting. - Note: Currently only the
run_shell_commandtool is supported. - Default:
{}(Disabled by default) -
Example:
json "summarizeToolOutput": { "run_shell_command": { "tokenBudget": 2000 } } -
excludedProjectEnvVars(array of strings): - Description: Specifies environment variables that should be excluded from being loaded from project
.envfiles. This prevents project-specific environment variables (likeDEBUG=true) from interfering with gemini-cli behavior. Variables from.gemini/.envfiles are never excluded. - Default:
["DEBUG", "DEBUG_MODE"] -
Example:
json "excludedProjectEnvVars": ["DEBUG", "DEBUG_MODE", "NODE_ENV"] -
includeDirectories(array of strings): - Description: Specifies an array of additional absolute or relative paths to include in the workspace context. This allows you to work with files across multiple directories as if they were one. Paths can use
~to refer to the user's home directory. This setting can be combined with the--include-directoriescommand-line flag. - Default:
[] -
Example:
json "includeDirectories": [ "/path/to/another/project", "../shared-library", "~/common-utils" ] -
loadMemoryFromIncludeDirectories(boolean): - Description: Controls the behavior of the
/memory refreshcommand. If set totrue,GEMINI.mdfiles should be loaded from all directories that are added. If set tofalse,GEMINI.mdshould only be loaded from the current directory. - Default:
false -
Example:
json "loadMemoryFromIncludeDirectories": true -
chatCompression(object): - Description: Controls the settings for chat history compression, both automatic and when manually invoked through the /compress command.
- Properties:
contextPercentageThreshold(number): A value between 0 and 1 that specifies the token threshold for compression as a percentage of the model's total token limit. For example, a value of0.6will trigger compression when the chat history exceeds 60% of the token limit.
- Example:
json "chatCompression": { "contextPercentageThreshold": 0.6 }
Example settings.json:
{
"theme": "GitHub",
"sandbox": "docker",
"toolDiscoveryCommand": "bin/get_tools",
"toolCallCommand": "bin/call_tool",
"mcpServers": {
"mainServer": {
"command": "bin/mcp_server.py"
},
"anotherServer": {
"command": "node",
"args": ["mcp_server.js", "--verbose"]
}
},
"telemetry": {
"enabled": true,
"target": "local",
"otlpEndpoint": "http://localhost:4317",
"logPrompts": true
},
"usageStatisticsEnabled": true,
"hideTips": false,
"hideBanner": false,
"maxSessionTurns": 10,
"summarizeToolOutput": {
"run_shell_command": {
"tokenBudget": 100
}
},
"excludedProjectEnvVars": ["DEBUG", "DEBUG_MODE", "NODE_ENV"],
"includeDirectories": ["path/to/dir1", "~/path/to/dir2", "../path/to/dir3"],
"loadMemoryFromIncludeDirectories": true
}
Shell History
The CLI keeps a history of shell commands you run. To avoid conflicts between different projects, this history is stored in a project-specific directory within your user's home folder.
- Location:
~/.gemini/tmp/<project_hash>/shell_history <project_hash>is a unique identifier generated from your project's root path.- The history is stored in a file named
shell_history.
Environment Variables & .env Files
Environment variables are a common way to configure applications, especially for sensitive information like API keys or for settings that might change between environments.
The CLI automatically loads environment variables from an .env file. The loading order is:
.envfile in the current working directory.- If not found, it searches upwards in parent directories until it finds an
.envfile or reaches the project root (identified by a.gitfolder) or the home directory. - If still not found, it looks for
~/.env(in the user's home directory).
Environment Variable Exclusion: Some environment variables (like DEBUG and DEBUG_MODE) are automatically excluded from being loaded from project .env files to prevent interference with gemini-cli behavior. Variables from .gemini/.env files are never excluded. You can customize this behavior using the excludedProjectEnvVars setting in your settings.json file.
GEMINI_API_KEY(Required):- Your API key for the Gemini API.
- Crucial for operation. The CLI will not function without it.
- Set this in your shell profile (e.g.,
~/.bashrc,~/.zshrc) or an.envfile. GEMINI_MODEL:- Specifies the default Gemini model to use.
- Overrides the hardcoded default
- Example:
export GEMINI_MODEL="gemini-2.5-flash" GOOGLE_API_KEY:- Your Google Cloud API key.
- Required for using Vertex AI in express mode.
- Ensure you have the necessary permissions.
- Example:
export GOOGLE_API_KEY="YOUR_GOOGLE_API_KEY". GOOGLE_CLOUD_PROJECT:- Your Google Cloud Project ID.
- Required for using Code Assist or Vertex AI.
- If using Vertex AI, ensure you have the necessary permissions in this project.
- Cloud Shell Note: When running in a Cloud Shell environment, this variable defaults to a special project allocated for Cloud Shell users. If you have
GOOGLE_CLOUD_PROJECTset in your global environment in Cloud Shell, it will be overridden by this default. To use a different project in Cloud Shell, you must defineGOOGLE_CLOUD_PROJECTin a.envfile. - Example:
export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID". GOOGLE_APPLICATION_CREDENTIALS(string):- Description: The path to your Google Application Credentials JSON file.
- Example:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/credentials.json" OTLP_GOOGLE_CLOUD_PROJECT:- Your Google Cloud Project ID for Telemetry in Google Cloud
- Example:
export OTLP_GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID". GOOGLE_CLOUD_LOCATION:- Your Google Cloud Project Location (e.g., us-central1).
- Required for using Vertex AI in non express mode.
- Example:
export GOOGLE_CLOUD_LOCATION="YOUR_PROJECT_LOCATION". GEMINI_SANDBOX:- Alternative to the
sandboxsetting insettings.json. - Accepts
true,false,docker,podman, or a custom command string. SEATBELT_PROFILE(macOS specific):- Switches the Seatbelt (
sandbox-exec) profile on macOS. permissive-open: (Default) Restricts writes to the project folder (and a few other folders, seepackages/cli/src/utils/sandbox-macos-permissive-open.sb) but allows other operations.strict: Uses a strict profile that declines operations by default.<profile_name>: Uses a custom profile. To define a custom profile, create a file namedsandbox-macos-<profile_name>.sbin your project's.gemini/directory (e.g.,my-project/.gemini/sandbox-macos-custom.sb).DEBUGorDEBUG_MODE(often used by underlying libraries or the CLI itself):- Set to
trueor1to enable verbose debug logging, which can be helpful for troubleshooting. - Note: These variables are automatically excluded from project
.envfiles by default to prevent interference with gemini-cli behavior. Use.gemini/.envfiles if you need to set these for gemini-cli specifically. NO_COLOR:- Set to any value to disable all color output in the CLI.
CLI_TITLE:- Set to a string to customize the title of the CLI.
CODE_ASSIST_ENDPOINT:- Specifies the endpoint for the code assist server.
- This is useful for development and testing.
Command-Line Arguments
Arguments passed directly when running the CLI can override other configurations for that specific session.
--model <model_name>(-m <model_name>):- Specifies the Gemini model to use for this session.
- Example:
npm start -- --model gemini-1.5-pro-latest --prompt <your_prompt>(-p <your_prompt>):- Used to pass a prompt directly to the command. This invokes Gemini CLI in a non-interactive mode.
--prompt-interactive <your_prompt>(-i <your_prompt>):- Starts an interactive session with the provided prompt as the initial input.
- The prompt is processed within the interactive session, not before it.
- Cannot be used when piping input from stdin.
- Example:
gemini -i "explain this code" --sandbox(-s):- Enables sandbox mode for this session.
--sandbox-image:- Sets the sandbox image URI.
--debug(-d):- Enables debug mode for this session, providing more verbose output.
--all-files(-a):- If set, recursively includes all files within the current directory as context for the prompt.
--help(or-h):- Displays help information about command-line arguments.
--show-memory-usage:- Displays the current memory usage.
--yolo:- Enables YOLO mode, which automatically approves all tool calls.
--telemetry:- Enables telemetry.
--telemetry-target:- Sets the telemetry target. See telemetry for more information.
--telemetry-otlp-endpoint:- Sets the OTLP endpoint for telemetry. See telemetry for more information.
--telemetry-log-prompts:- Enables logging of prompts for telemetry. See telemetry for more information.
--checkpointing:- Enables checkpointing.
--extensions <extension_name ...>(-e <extension_name ...>):- Specifies a list of extensions to use for the session. If not provided, all available extensions are used.
- Use the special term
gemini -e noneto disable all extensions. - Example:
gemini -e my-extension -e my-other-extension --list-extensions(-l):- Lists all available extensions and exits.
--proxy:- Sets the proxy for the CLI.
- Example:
--proxy http://localhost:7890. --include-directories <dir1,dir2,...>:- Includes additional directories in the workspace for multi-directory support.
- Can be specified multiple times or as comma-separated values.
- 5 directories can be added at maximum.
- Example:
--include-directories /path/to/project1,/path/to/project2or--include-directories /path/to/project1 --include-directories /path/to/project2 --version:- Displays the version of the CLI.
Context Files (Hierarchical Instructional Context)
While not strictly configuration for the CLI's behavior, context files (defaulting to GEMINI.md but configurable via the contextFileName setting) are crucial for configuring the instructional context (also referred to as "memory") provided to the Gemini model. This powerful feature allows you to give project-specific instructions, coding style guides, or any relevant background information to the AI, making its responses more tailored and accurate to your needs. The CLI includes UI elements, such as an indicator in the footer showing the number of loaded context files, to keep you informed about the active context.
- Purpose: These Markdown files contain instructions, guidelines, or context that you want the Gemini model to be aware of during your interactions. The system is designed to manage this instructional context hierarchically.
Example Context File Content (e.g., GEMINI.md)
Here's a conceptual example of what a context file at the root of a TypeScript project might contain:
# Project: My Awesome TypeScript Library
## General Instructions:
- When generating new TypeScript code, please follow the existing coding style.
- Ensure all new functions and classes have JSDoc comments.
- Prefer functional programming paradigms where appropriate.
- All code should be compatible with TypeScript 5.0 and Node.js 20+.
## Coding Style:
- Use 2 spaces for indentation.
- Interface names should be prefixed with `I` (e.g., `IUserService`).
- Private class members should be prefixed with an underscore (`_`).
- Always use strict equality (`===` and `!==`).
## Specific Component: `src/api/client.ts`
- This file handles all outbound API requests.
- When adding new API call functions, ensure they include robust error handling and logging.
- Use the existing `fetchWithRetry` utility for all GET requests.
## Regarding Dependencies:
- Avoid introducing new external dependencies unless absolutely necessary.
- If a new dependency is required, please state the reason.
This example demonstrates how you can provide general project context, specific coding conventions, and even notes about particular files or components. The more relevant and precise your context files are, the better the AI can assist you. Project-specific context files are highly encouraged to establish conventions and context.
- Hierarchical Loading and Precedence: The CLI implements a sophisticated hierarchical memory system by loading context files (e.g.,
GEMINI.md) from several locations. Content from files lower in this list (more specific) typically overrides or supplements content from files higher up (more general). The exact concatenation order and final context can be inspected using the/memory showcommand. The typical loading order is: - Global Context File:
- Location:
~/.gemini/<contextFileName>(e.g.,~/.gemini/GEMINI.mdin your user home directory). - Scope: Provides default instructions for all your projects.
- Location:
- Project Root & Ancestors Context Files:
- Location: The CLI searches for the configured context file in the current working directory and then in each parent directory up to either the project root (identified by a
.gitfolder) or your home directory. - Scope: Provides context relevant to the entire project or a significant portion of it.
- Location: The CLI searches for the configured context file in the current working directory and then in each parent directory up to either the project root (identified by a
- Sub-directory Context Files (Contextual/Local):
- Location: The CLI also scans for the configured context file in subdirectories below the current working directory (respecting common ignore patterns like
node_modules,.git, etc.). The breadth of this search is limited to 200 directories by default, but can be configured with amemoryDiscoveryMaxDirsfield in yoursettings.jsonfile. - Scope: Allows for highly specific instructions relevant to a particular component, module, or subsection of your project.
- Location: The CLI also scans for the configured context file in subdirectories below the current working directory (respecting common ignore patterns like
- Concatenation & UI Indication: The contents of all found context files are concatenated (with separators indicating their origin and path) and provided as part of the system prompt to the Gemini model. The CLI footer displays the count of loaded context files, giving you a quick visual cue about the active instructional context.
- Importing Content: You can modularize your context files by importing other Markdown files using the
@path/to/file.mdsyntax. For more details, see the Memory Import Processor documentation. - Commands for Memory Management:
- Use
/memory refreshto force a re-scan and reload of all context files from all configured locations. This updates the AI's instructional context. - Use
/memory showto display the combined instructional context currently loaded, allowing you to verify the hierarchy and content being used by the AI. - See the Commands documentation for full details on the
/memorycommand and its sub-commands (showandrefresh).
By understanding and utilizing these configuration layers and the hierarchical nature of context files, you can effectively manage the AI's memory and tailor the Gemini CLI's responses to your specific needs and projects.
Sandboxing
The Gemini CLI can execute potentially unsafe operations (like shell commands and file modifications) within a sandboxed environment to protect your system.
Sandboxing is disabled by default, but you can enable it in a few ways:
- Using
--sandboxor-sflag. - Setting
GEMINI_SANDBOXenvironment variable. - Sandbox is enabled in
--yolomode by default.
By default, it uses a pre-built gemini-cli-sandbox Docker image.
For project-specific sandboxing needs, you can create a custom Dockerfile at .gemini/sandbox.Dockerfile in your project's root directory. This Dockerfile can be based on the base sandbox image:
FROM gemini-cli-sandbox
# Add your custom dependencies or configurations here
# For example:
# RUN apt-get update && apt-get install -y some-package
# COPY ./my-config /app/my-config
When .gemini/sandbox.Dockerfile exists, you can use BUILD_SANDBOX environment variable when running Gemini CLI to automatically build the custom sandbox image:
BUILD_SANDBOX=1 gemini -s
Usage Statistics
To help us improve the Gemini CLI, we collect anonymized usage statistics. This data helps us understand how the CLI is used, identify common issues, and prioritize new features.
What we collect:
- Tool Calls: We log the names of the tools that are called, whether they succeed or fail, and how long they take to execute. We do not collect the arguments passed to the tools or any data returned by them.
- API Requests: We log the Gemini model used for each request, the duration of the request, and whether it was successful. We do not collect the content of the prompts or responses.
- Session Information: We collect information about the configuration of the CLI, such as the enabled tools and the approval mode.
What we DON'T collect:
- Personally Identifiable Information (PII): We do not collect any personal information, such as your name, email address, or API keys.
- Prompt and Response Content: We do not log the content of your prompts or the responses from the Gemini model.
- File Content: We do not log the content of any files that are read or written by the CLI.
How to opt out:
You can opt out of usage statistics collection at any time by setting the usageStatisticsEnabled property to false in your settings.json file:
{
"usageStatisticsEnabled": false
}
βββ index.md Content:
Gemini CLI
Within Gemini CLI, packages/cli is the frontend for users to send and receive prompts with the Gemini AI model and its associated tools. For a general overview of Gemini CLI, see the main documentation page.
Navigating this section
- Authentication: A guide to setting up authentication with Google's AI services.
- Commands: A reference for Gemini CLI commands (e.g.,
/help,/tools,/theme). - Configuration: A guide to tailoring Gemini CLI behavior using configuration files.
- Token Caching: Optimize API costs through token caching.
- Themes: A guide to customizing the CLI's appearance with different themes.
- Tutorials: A tutorial showing how to use Gemini CLI to automate a development task.
Non-interactive mode
Gemini CLI can be run in a non-interactive mode, which is useful for scripting and automation. In this mode, you pipe input to the CLI, it executes the command, and then it exits.
The following example pipes a command to Gemini CLI from your terminal:
echo "What is fine tuning?" | gemini
Gemini CLI executes the command and prints the output to your terminal. Note that you can achieve the same behavior by using the --prompt or -p flag. For example:
gemini -p "What is fine tuning?"
βββ themes.md Content:
Themes
Gemini CLI supports a variety of themes to customize its color scheme and appearance. You can change the theme to suit your preferences via the /theme command or "theme": configuration setting.
Available Themes
Gemini CLI comes with a selection of pre-defined themes, which you can list using the /theme command within Gemini CLI:
- Dark Themes:
ANSIAtom OneAyuDefaultDraculaGitHub- Light Themes:
ANSI LightAyu LightDefault LightGitHub LightGoogle CodeXcode
Changing Themes
- Enter
/themeinto Gemini CLI. - A dialog or selection prompt appears, listing the available themes.
- Using the arrow keys, select a theme. Some interfaces might offer a live preview or highlight as you select.
- Confirm your selection to apply the theme.
Theme Persistence
Selected themes are saved in Gemini CLI's configuration so your preference is remembered across sessions.
Custom Color Themes
Gemini CLI allows you to create your own custom color themes by specifying them in your settings.json file. This gives you full control over the color palette used in the CLI.
How to Define a Custom Theme
Add a customThemes block to your user, project, or system settings.json file. Each custom theme is defined as an object with a unique name and a set of color keys. For example:
{
"customThemes": {
"MyCustomTheme": {
"name": "MyCustomTheme",
"type": "custom",
"Background": "#181818",
"Foreground": "#F8F8F2",
"LightBlue": "#82AAFF",
"AccentBlue": "#61AFEF",
"AccentPurple": "#C678DD",
"AccentCyan": "#56B6C2",
"AccentGreen": "#98C379",
"AccentYellow": "#E5C07B",
"AccentRed": "#E06C75",
"Comment": "#5C6370",
"Gray": "#ABB2BF",
"DiffAdded": "#A6E3A1",
"DiffRemoved": "#F38BA8",
"DiffModified": "#89B4FA",
"GradientColors": ["#4796E4", "#847ACE", "#C3677F"]
}
}
}
Color keys:
BackgroundForegroundLightBlueAccentBlueAccentPurpleAccentCyanAccentGreenAccentYellowAccentRedCommentGrayDiffAdded(optional, for added lines in diffs)DiffRemoved(optional, for removed lines in diffs)DiffModified(optional, for modified lines in diffs)
Required Properties:
name(must match the key in thecustomThemesobject and be a string)type(must be the string"custom")BackgroundForegroundLightBlueAccentBlueAccentPurpleAccentCyanAccentGreenAccentYellowAccentRedCommentGray
You can use either hex codes (e.g., #FF0000) or standard CSS color names (e.g., coral, teal, blue) for any color value. See CSS color names for a full list of supported names.
You can define multiple custom themes by adding more entries to the customThemes object.
Example Custom Theme

Using Your Custom Theme
- Select your custom theme using the
/themecommand in Gemini CLI. Your custom theme will appear in the theme selection dialog. - Or, set it as the default by adding
"theme": "MyCustomTheme"to yoursettings.json. - Custom themes can be set at the user, project, or system level, and follow the same configuration precedence as other settings.
Dark Themes
ANSI

Atom OneDark

Ayu

Default

Dracula

GitHub

Light Themes
ANSI Light

Ayu Light

Default Light

GitHub Light

Google Code

Xcode

βββ token-caching.md Content:
Token Caching and Cost Optimization
Gemini CLI automatically optimizes API costs through token caching when using API key authentication (Gemini API key or Vertex AI). This feature reuses previous system instructions and context to reduce the number of tokens processed in subsequent requests.
Token caching is available for:
- API key users (Gemini API key)
- Vertex AI users (with project and location setup)
Token caching is not available for:
- OAuth users (Google Personal/Enterprise accounts) - the Code Assist API does not support cached content creation at this time
You can view your token usage and cached token savings using the /stats command. When cached tokens are available, they will be displayed in the stats output.
βββ tutorials.md Content:
Tutorials
This page contains tutorials for interacting with Gemini CLI.
Setting up a Model Context Protocol (MCP) server
[!CAUTION] Before using a third-party MCP server, ensure you trust its source and understand the tools it provides. Your use of third-party servers is at your own risk.
This tutorial demonstrates how to set up a MCP server, using the GitHub MCP server as an example. The GitHub MCP server provides tools for interacting with GitHub repositories, such as creating issues and commenting on pull requests.
Prerequisites
Before you begin, ensure you have the following installed and configured:
- Docker: Install and run Docker.
- GitHub Personal Access Token (PAT): Create a new classic or fine-grained PAT with the necessary scopes.
Guide
Configure the MCP server in settings.json
In your project's root directory, create or open the .gemini/settings.json file. Within the file, add the mcpServers configuration block, which provides instructions for how to launch the GitHub MCP server.
{
"mcpServers": {
"github": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e",
"GITHUB_PERSONAL_ACCESS_TOKEN",
"ghcr.io/github/github-mcp-server"
],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_PERSONAL_ACCESS_TOKEN}"
}
}
}
}
Set your GitHub token
[!CAUTION] Using a broadly scoped personal access token that has access to personal and private repositories can lead to information from the private repository being leaked into the public repository. We recommend using a fine-grained access token that doesn't share access to both public and private repositories.
Use an environment variable to store your GitHub PAT:
GITHUB_PERSONAL_ACCESS_TOKEN="pat_YourActualGitHubTokenHere"
Gemini CLI uses this value in the mcpServers configuration that you defined in the settings.json file.
Launch Gemini CLI and verify the connection
When you launch Gemini CLI, it automatically reads your configuration and launches the GitHub MCP server in the background. You can then use natural language prompts to ask Gemini CLI to perform GitHub actions. For example:
"get all open issues assigned to me in the 'foo/bar' repo and prioritize them"
βββ core/ βββ index.md Content:
Gemini CLI Core
Gemini CLI's core package (packages/core) is the backend portion of Gemini CLI, handling communication with the Gemini API, managing tools, and processing requests sent from packages/cli. For a general overview of Gemini CLI, see the main documentation page.
Navigating this section
- Core tools API: Information on how tools are defined, registered, and used by the core.
- Memory Import Processor: Documentation for the modular GEMINI.md import feature using @file.md syntax.
Role of the core
While the packages/cli portion of Gemini CLI provides the user interface, packages/core is responsible for:
- Gemini API interaction: Securely communicating with the Google Gemini API, sending user prompts, and receiving model responses.
- Prompt engineering: Constructing effective prompts for the Gemini model, potentially incorporating conversation history, tool definitions, and instructional context from
GEMINI.mdfiles. - Tool management & orchestration:
- Registering available tools (e.g., file system tools, shell command execution).
- Interpreting tool use requests from the Gemini model.
- Executing the requested tools with the provided arguments.
- Returning tool execution results to the Gemini model for further processing.
- Session and state management: Keeping track of the conversation state, including history and any relevant context required for coherent interactions.
- Configuration: Managing core-specific configurations, such as API key access, model selection, and tool settings.
Security considerations
The core plays a vital role in security:
- API key management: It handles the
GEMINI_API_KEYand ensures it's used securely when communicating with the Gemini API. - Tool execution: When tools interact with the local system (e.g.,
run_shell_command), the core (and its underlying tool implementations) must do so with appropriate caution, often involving sandboxing mechanisms to prevent unintended modifications.
Chat history compression
To ensure that long conversations don't exceed the token limits of the Gemini model, the core includes a chat history compression feature.
When a conversation approaches the token limit for the configured model, the core automatically compresses the conversation history before sending it to the model. This compression is designed to be lossless in terms of the information conveyed, but it reduces the overall number of tokens used.
You can find the token limits for each model in the Google AI documentation.
Model fallback
Gemini CLI includes a model fallback mechanism to ensure that you can continue to use the CLI even if the default "pro" model is rate-limited.
If you are using the default "pro" model and the CLI detects that you are being rate-limited, it automatically switches to the "flash" model for the current session. This allows you to continue working without interruption.
File discovery service
The file discovery service is responsible for finding files in the project that are relevant to the current context. It is used by the @ command and other tools that need to access files.
Memory discovery service
The memory discovery service is responsible for finding and loading the GEMINI.md files that provide context to the model. It searches for these files in a hierarchical manner, starting from the current working directory and moving up to the project root and the user's home directory. It also searches in subdirectories.
This allows you to have global, project-level, and component-level context files, which are all combined to provide the model with the most relevant information.
You can use the /memory command to show, add, and refresh the content of loaded GEMINI.md files.
βββ memport.md Content:
Memory Import Processor
The Memory Import Processor is a feature that allows you to modularize your GEMINI.md files by importing content from other files using the @file.md syntax.
Overview
This feature enables you to break down large GEMINI.md files into smaller, more manageable components that can be reused across different contexts. The import processor supports both relative and absolute paths, with built-in safety features to prevent circular imports and ensure file access security.
Syntax
Use the @ symbol followed by the path to the file you want to import:
# Main GEMINI.md file
This is the main content.
@./components/instructions.md
More content here.
@./shared/configuration.md
Supported Path Formats
Relative Paths
@./file.md- Import from the same directory@../file.md- Import from parent directory@./components/file.md- Import from subdirectory
Absolute Paths
@/absolute/path/to/file.md- Import using absolute path
Examples
Basic Import
# My GEMINI.md
Welcome to my project!
@./getting-started.md
## Features
@./features/overview.md
Nested Imports
The imported files can themselves contain imports, creating a nested structure:
# main.md
@./header.md
@./content.md
@./footer.md
# header.md
# Project Header
@./shared/title.md
Safety Features
Circular Import Detection
The processor automatically detects and prevents circular imports:
# file-a.md
@./file-b.md
# file-b.md
@./file-a.md <!-- This will be detected and prevented -->
File Access Security
The validateImportPath function ensures that imports are only allowed from specified directories, preventing access to sensitive files outside the allowed scope.
Maximum Import Depth
To prevent infinite recursion, there's a configurable maximum import depth (default: 5 levels).
Error Handling
Missing Files
If a referenced file doesn't exist, the import will fail gracefully with an error comment in the output.
File Access Errors
Permission issues or other file system errors are handled gracefully with appropriate error messages.
Code Region Detection
The import processor uses the marked library to detect code blocks and inline code spans, ensuring that @ imports inside these regions are properly ignored. This provides robust handling of nested code blocks and complex Markdown structures.
Import Tree Structure
The processor returns an import tree that shows the hierarchy of imported files, similar to Claude's /memory feature. This helps users debug problems with their GEMINI.md files by showing which files were read and their import relationships.
Example tree structure:
Memory Files
L project: GEMINI.md
L a.md
L b.md
L c.md
L d.md
L e.md
L f.md
L included.md
The tree preserves the order that files were imported and shows the complete import chain for debugging purposes.
Comparison to Claude Code's /memory (claude.md) Approach
Claude Code's /memory feature (as seen in claude.md) produces a flat, linear document by concatenating all included files, always marking file boundaries with clear comments and path names. It does not explicitly present the import hierarchy, but the LLM receives all file contents and paths, which is sufficient for reconstructing the hierarchy if needed.
Note: The import tree is mainly for clarity during development and has limited relevance to LLM consumption.
API Reference
processImports(content, basePath, debugMode?, importState?)
Processes import statements in GEMINI.md content.
Parameters:
content(string): The content to process for importsbasePath(string): The directory path where the current file is locateddebugMode(boolean, optional): Whether to enable debug logging (default: false)importState(ImportState, optional): State tracking for circular import prevention
Returns: Promise
ProcessImportsResult
interface ProcessImportsResult {
content: string; // The processed content with imports resolved
importTree: MemoryFile; // Tree structure showing the import hierarchy
}
MemoryFile
interface MemoryFile {
path: string; // The file path
imports?: MemoryFile[]; // Direct imports, in the order they were imported
}
validateImportPath(importPath, basePath, allowedDirectories)
Validates import paths to ensure they are safe and within allowed directories.
Parameters:
importPath(string): The import path to validatebasePath(string): The base directory for resolving relative pathsallowedDirectories(string[]): Array of allowed directory paths
Returns: boolean - Whether the import path is valid
findProjectRoot(startDir)
Finds the project root by searching for a .git directory upwards from the given start directory. Implemented as an async function using non-blocking file system APIs to avoid blocking the Node.js event loop.
Parameters:
startDir(string): The directory to start searching from
Returns: Promise.git is found)
Best Practices
- Use descriptive file names for imported components
- Keep imports shallow - avoid deeply nested import chains
- Document your structure - maintain a clear hierarchy of imported files
- Test your imports - ensure all referenced files exist and are accessible
- Use relative paths when possible for better portability
Troubleshooting
Common Issues
- Import not working: Check that the file exists and the path is correct
- Circular import warnings: Review your import structure for circular references
- Permission errors: Ensure the files are readable and within allowed directories
- Path resolution issues: Use absolute paths if relative paths aren't resolving correctly
Debug Mode
Enable debug mode to see detailed logging of the import process:
const result = await processImports(content, basePath, true);
βββ tools-api.md Content:
Gemini CLI Core: Tools API
The Gemini CLI core (packages/core) features a robust system for defining, registering, and executing tools. These tools extend the capabilities of the Gemini model, allowing it to interact with the local environment, fetch web content, and perform various actions beyond simple text generation.
Core Concepts
- Tool (
tools.ts): An interface and base class (BaseTool) that defines the contract for all tools. Each tool must have: name: A unique internal name (used in API calls to Gemini).displayName: A user-friendly name.description: A clear explanation of what the tool does, which is provided to the Gemini model.parameterSchema: A JSON schema defining the parameters that the tool accepts. This is crucial for the Gemini model to understand how to call the tool correctly.validateToolParams(): A method to validate incoming parameters.getDescription(): A method to provide a human-readable description of what the tool will do with specific parameters before execution.shouldConfirmExecute(): A method to determine if user confirmation is required before execution (e.g., for potentially destructive operations).-
execute(): The core method that performs the tool's action and returns aToolResult. -
ToolResult(tools.ts): An interface defining the structure of a tool's execution outcome: llmContent: The factual content to be included in the history sent back to the LLM for context. This can be a simple string or aPartListUnion(an array ofPartobjects and strings) for rich content.-
returnDisplay: A user-friendly string (often Markdown) or a special object (likeFileDiff) for display in the CLI. -
Returning Rich Content: Tools are not limited to returning simple text. The
llmContentcan be aPartListUnion, which is an array that can contain a mix ofPartobjects (for images, audio, etc.) andstrings. This allows a single tool execution to return multiple pieces of rich content. -
Tool Registry (
tool-registry.ts): A class (ToolRegistry) responsible for: - Registering Tools: Holding a collection of all available built-in tools (e.g.,
ReadFileTool,ShellTool). - Discovering Tools: It can also discover tools dynamically:
- Command-based Discovery: If
toolDiscoveryCommandis configured in settings, this command is executed. It's expected to output JSON describing custom tools, which are then registered asDiscoveredToolinstances. - MCP-based Discovery: If
mcpServerCommandis configured, the registry can connect to a Model Context Protocol (MCP) server to list and register tools (DiscoveredMCPTool).
- Command-based Discovery: If
- Providing Schemas: Exposing the
FunctionDeclarationschemas of all registered tools to the Gemini model, so it knows what tools are available and how to use them. - Retrieving Tools: Allowing the core to get a specific tool by name for execution.
Built-in Tools
The core comes with a suite of pre-defined tools, typically found in packages/core/src/tools/. These include:
- File System Tools:
LSTool(ls.ts): Lists directory contents.ReadFileTool(read-file.ts): Reads the content of a single file. It takes anabsolute_pathparameter, which must be an absolute path.WriteFileTool(write-file.ts): Writes content to a file.GrepTool(grep.ts): Searches for patterns in files.GlobTool(glob.ts): Finds files matching glob patterns.EditTool(edit.ts): Performs in-place modifications to files (often requiring confirmation).ReadManyFilesTool(read-many-files.ts): Reads and concatenates content from multiple files or glob patterns (used by the@command in CLI).- Execution Tools:
ShellTool(shell.ts): Executes arbitrary shell commands (requires careful sandboxing and user confirmation).- Web Tools:
WebFetchTool(web-fetch.ts): Fetches content from a URL.WebSearchTool(web-search.ts): Performs a web search.- Memory Tools:
MemoryTool(memoryTool.ts): Interacts with the AI's memory.
Each of these tools extends BaseTool and implements the required methods for its specific functionality.
Tool Execution Flow
- Model Request: The Gemini model, based on the user's prompt and the provided tool schemas, decides to use a tool and returns a
FunctionCallpart in its response, specifying the tool name and arguments. - Core Receives Request: The core parses this
FunctionCall. - Tool Retrieval: It looks up the requested tool in the
ToolRegistry. - Parameter Validation: The tool's
validateToolParams()method is called. - Confirmation (if needed):
- The tool's
shouldConfirmExecute()method is called. - If it returns details for confirmation, the core communicates this back to the CLI, which prompts the user.
- The user's decision (e.g., proceed, cancel) is sent back to the core.
- The tool's
- Execution: If validated and confirmed (or if no confirmation is needed), the core calls the tool's
execute()method with the provided arguments and anAbortSignal(for potential cancellation). - Result Processing: The
ToolResultfromexecute()is received by the core. - Response to Model: The
llmContentfrom theToolResultis packaged as aFunctionResponseand sent back to the Gemini model so it can continue generating a user-facing response. - Display to User: The
returnDisplayfrom theToolResultis sent to the CLI to show the user what the tool did.
Extending with Custom Tools
While direct programmatic registration of new tools by users isn't explicitly detailed as a primary workflow in the provided files for typical end-users, the architecture supports extension through:
- Command-based Discovery: Advanced users or project administrators can define a
toolDiscoveryCommandinsettings.json. This command, when run by the Gemini CLI core, should output a JSON array ofFunctionDeclarationobjects. The core will then make these available asDiscoveredToolinstances. The correspondingtoolCallCommandwould then be responsible for actually executing these custom tools. - MCP Server(s): For more complex scenarios, one or more MCP servers can be set up and configured via the
mcpServerssetting insettings.json. The Gemini CLI core can then discover and use tools exposed by these servers. As mentioned, if you have multiple MCP servers, the tool names will be prefixed with the server name from your configuration (e.g.,serverAlias__actualToolName).
This tool system provides a flexible and powerful way to augment the Gemini model's capabilities, making the Gemini CLI a versatile assistant for a wide range of tasks.
βββ deployment.md Content:
Gemini CLI Execution and Deployment
This document describes how to run Gemini CLI and explains the deployment architecture that Gemini CLI uses.
Running Gemini CLI
There are several ways to run Gemini CLI. The option you choose depends on how you intend to use Gemini CLI.
1. Standard installation (Recommended for typical users)
This is the recommended way for end-users to install Gemini CLI. It involves downloading the Gemini CLI package from the NPM registry.
- Global install:
bash
npm install -g @google/gemini-cli
Then, run the CLI from anywhere:
bash
gemini
- NPX execution:
bash
# Execute the latest version from NPM without a global install
npx @google/gemini-cli
2. Running in a sandbox (Docker/Podman)
For security and isolation, Gemini CLI can be run inside a container. This is the default way that the CLI executes tools that might have side effects.
- Directly from the Registry:
You can run the published sandbox image directly. This is useful for environments where you only have Docker and want to run the CLI.
bash # Run the published sandbox image docker run --rm -it us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.1.1 - Using the
--sandboxflag: If you have Gemini CLI installed locally (using the standard installation described above), you can instruct it to run inside the sandbox container.bash gemini --sandbox -y -p "your prompt here"
3. Running from source (Recommended for Gemini CLI contributors)
Contributors to the project will want to run the CLI directly from the source code.
- Development Mode:
This method provides hot-reloading and is useful for active development.
bash # From the root of the repository npm run start - Production-like mode (Linked package): This method simulates a global installation by linking your local package. It's useful for testing a local build in a production workflow.
```bash # Link the local cli package to your global node_modules npm link packages/cli
# Now you can run your local version using the gemini command
gemini
```
4. Running the latest Gemini CLI commit from GitHub
You can run the most recently committed version of Gemini CLI directly from the GitHub repository. This is useful for testing features still in development.
# Execute the CLI directly from the main branch on GitHub
npx https://github.com/google-gemini/gemini-cli
Deployment architecture
The execution methods described above are made possible by the following architectural components and processes:
NPM packages
Gemini CLI project is a monorepo that publishes two core packages to the NPM registry:
@google/gemini-cli-core: The backend, handling logic and tool execution.@google/gemini-cli: The user-facing frontend.
These packages are used when performing the standard installation and when running Gemini CLI from the source.
Build and packaging processes
There are two distinct build processes used, depending on the distribution channel:
-
NPM publication: For publishing to the NPM registry, the TypeScript source code in
@google/gemini-cli-coreand@google/gemini-cliis transpiled into standard JavaScript using the TypeScript Compiler (tsc). The resultingdist/directory is what gets published in the NPM package. This is a standard approach for TypeScript libraries. -
GitHub
npxexecution: When running the latest version of Gemini CLI directly from GitHub, a different process is triggered by thepreparescript inpackage.json. This script usesesbuildto bundle the entire application and its dependencies into a single, self-contained JavaScript file. This bundle is created on-the-fly on the user's machine and is not checked into the repository.
Docker sandbox image
The Docker-based execution method is supported by the gemini-cli-sandbox container image. This image is published to a container registry and contains a pre-installed, global version of Gemini CLI.
Release process
The release process is automated through GitHub Actions. The release workflow performs the following actions:
- Build the NPM packages using
tsc. - Publish the NPM packages to the artifact registry.
- Create GitHub releases with bundled assets.
βββ examples/ βββ proxy-script.md Content:
Example Proxy Script
The following is an example of a proxy script that can be used with the GEMINI_SANDBOX_PROXY_COMMAND environment variable. This script only allows HTTPS connections to example.com:443 and declines all other requests.
#!/usr/bin/env node
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
// Example proxy server that listens on :::8877 and only allows HTTPS connections to example.com.
// Set `GEMINI_SANDBOX_PROXY_COMMAND=scripts/example-proxy.js` to run proxy alongside sandbox
// Test via `curl https://example.com` inside sandbox (in shell mode or via shell tool)
import http from 'http';
import net from 'net';
import { URL } from 'url';
import console from 'console';
const PROXY_PORT = 8877;
const ALLOWED_DOMAINS = ['example.com', 'googleapis.com'];
const ALLOWED_PORT = '443';
const server = http.createServer((req, res) => {
// Deny all requests other than CONNECT for HTTPS
console.log(
`[PROXY] Denying non-CONNECT request for: ${req.method} ${req.url}`,
);
res.writeHead(405, { 'Content-Type': 'text/plain' });
res.end('Method Not Allowed');
});
server.on('connect', (req, clientSocket, head) => {
// req.url will be in the format "hostname:port" for a CONNECT request.
const { port, hostname } = new URL(`http://${req.url}`);
console.log(`[PROXY] Intercepted CONNECT request for: ${hostname}:${port}`);
if (
ALLOWED_DOMAINS.some(
(domain) => hostname == domain || hostname.endsWith(`.${domain}`),
) &&
port === ALLOWED_PORT
) {
console.log(`[PROXY] Allowing connection to ${hostname}:${port}`);
// Establish a TCP connection to the original destination.
const serverSocket = net.connect(port, hostname, () => {
clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
// Create a tunnel by piping data between the client and the destination server.
serverSocket.write(head);
serverSocket.pipe(clientSocket);
clientSocket.pipe(serverSocket);
});
serverSocket.on('error', (err) => {
console.error(`[PROXY] Error connecting to destination: ${err.message}`);
clientSocket.end(`HTTP/1.1 502 Bad Gateway\r\n\r\n`);
});
} else {
console.log(`[PROXY] Denying connection to ${hostname}:${port}`);
clientSocket.end('HTTP/1.1 403 Forbidden\r\n\r\n');
}
clientSocket.on('error', (err) => {
// This can happen if the client hangs up.
console.error(`[PROXY] Client socket error: ${err.message}`);
});
});
server.listen(PROXY_PORT, () => {
const address = server.address();
console.log(`[PROXY] Proxy listening on ${address.address}:${address.port}`);
console.log(
`[PROXY] Allowing HTTPS connections to domains: ${ALLOWED_DOMAINS.join(', ')}`,
);
});
βββ extension.md Content:
Gemini CLI Extensions
Gemini CLI supports extensions that can be used to configure and extend its functionality.
How it works
On startup, Gemini CLI looks for extensions in two locations:
<workspace>/.gemini/extensions<home>/.gemini/extensions
Gemini CLI loads all extensions from both locations. If an extension with the same name exists in both locations, the extension in the workspace directory takes precedence.
Within each location, individual extensions exist as a directory that contains a gemini-extension.json file. For example:
<workspace>/.gemini/extensions/my-extension/gemini-extension.json
gemini-extension.json
The gemini-extension.json file contains the configuration for the extension. The file has the following structure:
{
"name": "my-extension",
"version": "1.0.0",
"mcpServers": {
"my-server": {
"command": "node my-server.js"
}
},
"contextFileName": "GEMINI.md",
"excludeTools": ["run_shell_command"]
}
name: The name of the extension. This is used to uniquely identify the extension and for conflict resolution when extension commands have the same name as user or project commands.version: The version of the extension.mcpServers: A map of MCP servers to configure. The key is the name of the server, and the value is the server configuration. These servers will be loaded on startup just like MCP servers configured in asettings.jsonfile. If both an extension and asettings.jsonfile configure an MCP server with the same name, the server defined in thesettings.jsonfile takes precedence.contextFileName: The name of the file that contains the context for the extension. This will be used to load the context from the workspace. If this property is not used but aGEMINI.mdfile is present in your extension directory, then that file will be loaded.excludeTools: An array of tool names to exclude from the model. You can also specify command-specific restrictions for tools that support it, like therun_shell_commandtool. For example,"excludeTools": ["run_shell_command(rm -rf)"]will block therm -rfcommand.
When Gemini CLI starts, it loads all the extensions and merges their configurations. If there are any conflicts, the workspace configuration takes precedence.
Extension Commands
Extensions can provide custom commands by placing TOML files in a commands/ subdirectory within the extension directory. These commands follow the same format as user and project custom commands and use standard naming conventions.
Example
An extension named gcp with the following structure:
.gemini/extensions/gcp/
βββ gemini-extension.json
βββ commands/
βββ deploy.toml
βββ gcs/
βββ sync.toml
Would provide these commands:
/deploy- Shows as[gcp] Custom command from deploy.tomlin help/gcs:sync- Shows as[gcp] Custom command from sync.tomlin help
Conflict Resolution
Extension commands have the lowest precedence. When a conflict occurs with user or project commands:
- No conflict: Extension command uses its natural name (e.g.,
/deploy) - With conflict: Extension command is renamed with the extension prefix (e.g.,
/gcp.deploy)
For example, if both a user and the gcp extension define a deploy command:
/deploy- Executes the user's deploy command/gcp.deploy- Executes the extension's deploy command (marked with[gcp]tag)
βββ gemini-ignore.md Content:
Ignoring Files
This document provides an overview of the Gemini Ignore (.geminiignore) feature of the Gemini CLI.
The Gemini CLI includes the ability to automatically ignore files, similar to .gitignore (used by Git) and .aiexclude (used by Gemini Code Assist). Adding paths to your .geminiignore file will exclude them from tools that support this feature, although they will still be visible to other services (such as Git).
How it works
When you add a path to your .geminiignore file, tools that respect this file will exclude matching files and directories from their operations. For example, when you use the read_many_files command, any paths in your .geminiignore file will be automatically excluded.
For the most part, .geminiignore follows the conventions of .gitignore files:
- Blank lines and lines starting with
#are ignored. - Standard glob patterns are supported (such as
*,?, and[]). - Putting a
/at the end will only match directories. - Putting a
/at the beginning anchors the path relative to the.geminiignorefile. !negates a pattern.
You can update your .geminiignore file at any time. To apply the changes, you must restart your Gemini CLI session.
How to use .geminiignore
To enable .geminiignore:
- Create a file named
.geminiignorein the root of your project directory.
To add a file or directory to .geminiignore:
- Open your
.geminiignorefile. - Add the path or file you want to ignore, for example:
/archive/orapikeys.txt.
.geminiignore examples
You can use .geminiignore to ignore directories and files:
# Exclude your /packages/ directory and all subdirectories
/packages/
# Exclude your apikeys.txt file
apikeys.txt
You can use wildcards in your .geminiignore file with *:
# Exclude all .md files
*.md
Finally, you can exclude files and directories from exclusion with !:
# Exclude all .md files except README.md
*.md
!README.md
To remove paths from your .geminiignore file, delete the relevant lines.
βββ index.md Content:
Welcome to Gemini CLI documentation
This documentation provides a comprehensive guide to installing, using, and developing Gemini CLI. This tool lets you interact with Gemini models through a command-line interface.
Overview
Gemini CLI brings the capabilities of Gemini models to your terminal in an interactive Read-Eval-Print Loop (REPL) environment. Gemini CLI consists of a client-side application (packages/cli) that communicates with a local server (packages/core), which in turn manages requests to the Gemini API and its AI models. Gemini CLI also contains a variety of tools for tasks such as performing file system operations, running shells, and web fetching, which are managed by packages/core.
Navigating the documentation
This documentation is organized into the following sections:
- Execution and Deployment: Information for running Gemini CLI.
- Architecture Overview: Understand the high-level design of Gemini CLI, including its components and how they interact.
- CLI Usage: Documentation for
packages/cli. - CLI Introduction: Overview of the command-line interface.
- Commands: Description of available CLI commands.
- Configuration: Information on configuring the CLI.
- Checkpointing: Documentation for the checkpointing feature.
- Extensions: How to extend the CLI with new functionality.
- Telemetry: Overview of telemetry in the CLI.
- Core Details: Documentation for
packages/core. - Core Introduction: Overview of the core component.
- Tools API: Information on how the core manages and exposes tools.
- Tools:
- Tools Overview: Overview of the available tools.
- File System Tools: Documentation for the
read_fileandwrite_filetools. - Multi-File Read Tool: Documentation for the
read_many_filestool. - Shell Tool: Documentation for the
run_shell_commandtool. - Web Fetch Tool: Documentation for the
web_fetchtool. - Web Search Tool: Documentation for the
google_web_searchtool. - Memory Tool: Documentation for the
save_memorytool. - Contributing & Development Guide: Information for contributors and developers, including setup, building, testing, and coding conventions.
- NPM Workspaces and Publishing: Details on how the project's packages are managed and published.
- Troubleshooting Guide: Find solutions to common problems and FAQs.
- Terms of Service and Privacy Notice: Information on the terms of service and privacy notices applicable to your use of Gemini CLI.
We hope this documentation helps you make the most of the Gemini CLI!
βββ integration-tests.md Content:
Integration Tests
This document provides information about the integration testing framework used in this project.
Overview
The integration tests are designed to validate the end-to-end functionality of the Gemini CLI. They execute the built binary in a controlled environment and verify that it behaves as expected when interacting with the file system.
These tests are located in the integration-tests directory and are run using a custom test runner.
Running the tests
The integration tests are not run as part of the default npm run test command. They must be run explicitly using the npm run test:integration:all script.
The integration tests can also be run using the following shortcut:
npm run test:e2e
Running a specific set of tests
To run a subset of test files, you can use npm run <integration test command> <file_name1> .... where test:e2e or test:integration* and <file_name> is any of the .test.js files in the integration-tests/ directory. For example, the following command runs list_directory.test.js and write_file.test.js:
npm run test:e2e list_directory write_file
Running a single test by name
To run a single test by its name, use the --test-name-pattern flag:
npm run test:e2e -- --test-name-pattern "reads a file"
Running all tests
To run the entire suite of integration tests, use the following command:
npm run test:integration:all
Sandbox matrix
The all command will run tests for no sandboxing, docker and podman.
Each individual type can be run using the following commands:
npm run test:integration:sandbox:none
npm run test:integration:sandbox:docker
npm run test:integration:sandbox:podman
Diagnostics
The integration test runner provides several options for diagnostics to help track down test failures.
Keeping test output
You can preserve the temporary files created during a test run for inspection. This is useful for debugging issues with file system operations.
To keep the test output, you can either use the --keep-output flag or set the KEEP_OUTPUT environment variable to true.
# Using the flag
npm run test:integration:sandbox:none -- --keep-output
# Using the environment variable
KEEP_OUTPUT=true npm run test:integration:sandbox:none
When output is kept, the test runner will print the path to the unique directory for the test run.
Verbose output
For more detailed debugging, the --verbose flag streams the real-time output from the gemini command to the console.
npm run test:integration:sandbox:none -- --verbose
When using --verbose and --keep-output in the same command, the output is streamed to the console and also saved to a log file within the test's temporary directory.
The verbose output is formatted to clearly identify the source of the logs:
--- TEST: <file-name-without-js>:<test-name> ---
... output from the gemini command ...
--- END TEST: <file-name-without-js>:<test-name> ---
Linting and formatting
To ensure code quality and consistency, the integration test files are linted as part of the main build process. You can also manually run the linter and auto-fixer.
Running the linter
To check for linting errors, run the following command:
npm run lint
You can include the :fix flag in the command to automatically fix any fixable linting errors:
npm run lint:fix
Directory structure
The integration tests create a unique directory for each test run inside the .integration-tests directory. Within this directory, a subdirectory is created for each test file, and within that, a subdirectory is created for each individual test case.
This structure makes it easy to locate the artifacts for a specific test run, file, or case.
.integration-tests/
βββ <run-id>/
βββ <test-file-name>.test.js/
βββ <test-case-name>/
βββ output.log
βββ ...other test artifacts...
Continuous integration
To ensure the integration tests are always run, a GitHub Actions workflow is defined in .github/workflows/e2e.yml. This workflow automatically runs the integrations tests for pull requests against the main branch, or when a pull request is added to a merge queue.
The workflow runs the tests in different sandboxing environments to ensure Gemini CLI is tested across each:
sandbox:none: Runs the tests without any sandboxing.sandbox:docker: Runs the tests in a Docker container.sandbox:podman: Runs the tests in a Podman container.
βββ issue-and-pr-automation.md Content:
Automation and Triage Processes
This document provides a detailed overview of the automated processes we use to manage and triage issues and pull requests. Our goal is to provide prompt feedback and ensure that contributions are reviewed and integrated efficiently. Understanding this automation will help you as a contributor know what to expect and how to best interact with our repository bots.
Guiding Principle: Issues and Pull Requests
First and foremost, almost every Pull Request (PR) should be linked to a corresponding Issue. The issue describes the "what" and the "why" (the bug or feature), while the PR is the "how" (the implementation). This separation helps us track work, prioritize features, and maintain clear historical context. Our automation is built around this principle.
Detailed Automation Workflows
Here is a breakdown of the specific automation workflows that run in our repository.
1. When you open an Issue: Automated Issue Triage
This is the first bot you will interact with when you create an issue. Its job is to perform an initial analysis and apply the correct labels.
- Workflow File:
.github/workflows/gemini-automated-issue-triage.yml - When it runs: Immediately after an issue is created or reopened.
- What it does:
- It uses a Gemini model to analyze the issue's title and body against a detailed set of guidelines.
- Applies one
area/*label: Categorizes the issue into a functional area of the project (e.g.,area/ux,area/models,area/platform). - Applies one
kind/*label: Identifies the type of issue (e.g.,kind/bug,kind/enhancement,kind/question). - Applies one
priority/*label: Assigns a priority from P0 (critical) to P3 (low) based on the described impact. - May apply
status/need-information: If the issue lacks critical details (like logs or reproduction steps), it will be flagged for more information. - May apply
status/need-retesting: If the issue references a CLI version that is more than six versions old, it will be flagged for retesting on a current version. - What you should do:
- Fill out the issue template as completely as possible. The more detail you provide, the more accurate the triage will be.
- If the
status/need-informationlabel is added, please provide the requested details in a comment.
2. When you open a Pull Request: Continuous Integration (CI)
This workflow ensures that all changes meet our quality standards before they can be merged.
- Workflow File:
.github/workflows/ci.yml - When it runs: On every push to a pull request.
- What it does:
- Lint: Checks that your code adheres to our project's formatting and style rules.
- Test: Runs our full suite of automated tests across macOS, Windows, and Linux, and on multiple Node.js versions. This is the most time-consuming part of the CI process.
- Post Coverage Comment: After all tests have successfully passed, a bot will post a comment on your PR. This comment provides a summary of how well your changes are covered by tests.
- What you should do:
- Ensure all CI checks pass. A green checkmark β will appear next to your commit when everything is successful.
- If a check fails (a red "X" β), click the "Details" link next to the failed check to view the logs, identify the problem, and push a fix.
3. Ongoing Triage for Pull Requests: PR Auditing and Label Sync
This workflow runs periodically to ensure all open PRs are correctly linked to issues and have consistent labels.
- Workflow File:
.github/workflows/gemini-scheduled-pr-triage.yml - When it runs: Every 15 minutes on all open pull requests.
- What it does:
- Checks for a linked issue: The bot scans your PR description for a keyword that links it to an issue (e.g.,
Fixes #123,Closes #456). - Adds
status/need-issue: If no linked issue is found, the bot will add thestatus/need-issuelabel to your PR. This is a clear signal that an issue needs to be created and linked. - Synchronizes labels: If an issue is linked, the bot ensures the PR's labels perfectly match the issue's labels. It will add any missing labels and remove any that don't belong, and it will remove the
status/need-issuelabel if it was present. - What you should do:
- Always link your PR to an issue. This is the most important step. Add a line like
Resolves #<issue-number>to your PR description. - This will ensure your PR is correctly categorized and moves through the review process smoothly.
4. Ongoing Triage for Issues: Scheduled Issue Triage
This is a fallback workflow to ensure that no issue gets missed by the triage process.
- Workflow File:
.github/workflows/gemini-scheduled-issue-triage.yml - When it runs: Every hour on all open issues.
- What it does:
- It actively seeks out issues that either have no labels at all or still have the
status/need-triagelabel. - It then triggers the same powerful Gemini-based analysis as the initial triage bot to apply the correct labels.
- What you should do:
- You typically don't need to do anything. This workflow is a safety net to ensure every issue is eventually categorized, even if the initial triage fails.
5. Release Automation
This workflow handles the process of packaging and publishing new versions of the Gemini CLI.
- Workflow File:
.github/workflows/release.yml - When it runs: On a daily schedule for "nightly" releases, and manually for official patch/minor releases.
- What it does:
- Automatically builds the project, bumps the version numbers, and publishes the packages to npm.
- Creates a corresponding release on GitHub with generated release notes.
- What you should do:
- As a contributor, you don't need to do anything for this process. You can be confident that once your PR is merged into the
mainbranch, your changes will be included in the very next nightly release.
We hope this detailed overview is helpful. If you have any questions about our automation or processes, please don't hesitate to ask!
βββ keyboard-shortcuts.md Content:
Gemini CLI Keyboard Shortcuts
This document lists the available keyboard shortcuts in the Gemini CLI.
General
| Shortcut | Description |
|---|---|
Esc |
Close dialogs and suggestions. |
Ctrl+C |
Exit the application. Press twice to confirm. |
Ctrl+D |
Exit the application if the input is empty. Press twice to confirm. |
Ctrl+L |
Clear the screen. |
Ctrl+O |
Toggle the display of the debug console. |
Ctrl+S |
Allows long responses to print fully, disabling truncation. Use your terminal's scrollback to view the entire output. |
Ctrl+T |
Toggle the display of tool descriptions. |
Ctrl+Y |
Toggle auto-approval (YOLO mode) for all tool calls. |
Input Prompt
| Shortcut | Description |
|---|---|
! |
Toggle shell mode when the input is empty. |
\ (at end of line) + Enter |
Insert a newline. |
Down Arrow |
Navigate down through the input history. |
Enter |
Submit the current prompt. |
Meta+Delete / Ctrl+Delete |
Delete the word to the right of the cursor. |
Tab |
Autocomplete the current suggestion if one exists. |
Up Arrow |
Navigate up through the input history. |
Ctrl+A / Home |
Move the cursor to the beginning of the line. |
Ctrl+B / Left Arrow |
Move the cursor one character to the left. |
Ctrl+C |
Clear the input prompt |
Ctrl+D / Delete |
Delete the character to the right of the cursor. |
Ctrl+E / End |
Move the cursor to the end of the line. |
Ctrl+F / Right Arrow |
Move the cursor one character to the right. |
Ctrl+H / Backspace |
Delete the character to the left of the cursor. |
Ctrl+K |
Delete from the cursor to the end of the line. |
Ctrl+Left Arrow / Meta+Left Arrow / Meta+B |
Move the cursor one word to the left. |
Ctrl+N |
Navigate down through the input history. |
Ctrl+P |
Navigate up through the input history. |
Ctrl+Right Arrow / Meta+Right Arrow / Meta+F |
Move the cursor one word to the right. |
Ctrl+U |
Delete from the cursor to the beginning of the line. |
Ctrl+V |
Paste clipboard content. If the clipboard contains an image, it will be saved and a reference to it will be inserted in the prompt. |
Ctrl+W / Meta+Backspace / Ctrl+Backspace |
Delete the word to the left of the cursor. |
Ctrl+X / Meta+Enter |
Open the current input in an external editor. |
Suggestions
| Shortcut | Description |
|---|---|
Down Arrow |
Navigate down through the suggestions. |
Tab / Enter |
Accept the selected suggestion. |
Up Arrow |
Navigate up through the suggestions. |
Radio Button Select
| Shortcut | Description |
|---|---|
Down Arrow / j |
Move selection down. |
Enter |
Confirm selection. |
Up Arrow / k |
Move selection up. |
1-9 |
Select an item by its number. |
| (multi-digit) | For items with numbers greater than 9, press the digits in quick succession to select the corresponding item. |
βββ npm.md Content:
Package Overview
This monorepo contains two main packages: @google/gemini-cli and @google/gemini-cli-core.
@google/gemini-cli
This is the main package for the Gemini CLI. It is responsible for the user interface, command parsing, and all other user-facing functionality.
When this package is published, it is bundled into a single executable file. This bundle includes all of the package's dependencies, including @google/gemini-cli-core. This means that whether a user installs the package with npm install -g @google/gemini-cli or runs it directly with npx @google/gemini-cli, they are using this single, self-contained executable.
@google/gemini-cli-core
This package contains the core logic for interacting with the Gemini API. It is responsible for making API requests, handling authentication, and managing the local cache.
This package is not bundled. When it is published, it is published as a standard Node.js package with its own dependencies. This allows it to be used as a standalone package in other projects, if needed. All transpiled js code in the dist folder is included in the package.
Release Process
This project follows a structured release process to ensure that all packages are versioned and published correctly. The process is designed to be as automated as possible.
How To Release
Releases are managed through the release.yml GitHub Actions workflow. To perform a manual release for a patch or hotfix:
- Navigate to the Actions tab of the repository.
- Select the Release workflow from the list.
- Click the Run workflow dropdown button.
- Fill in the required inputs:
- Version: The exact version to release (e.g.,
v0.2.1). - Ref: The branch or commit SHA to release from (defaults to
main). - Dry Run: Leave as
trueto test the workflow without publishing, or set tofalseto perform a live release.
- Version: The exact version to release (e.g.,
- Click Run workflow.
Nightly Releases
In addition to manual releases, this project has an automated nightly release process to provide the latest "bleeding edge" version for testing and development.
Process
Every night at midnight UTC, the Release workflow runs automatically on a schedule. It performs the following steps:
- Checks out the latest code from the
mainbranch. - Installs all dependencies.
- Runs the full suite of
preflightchecks and integration tests. - If all tests succeed, it calculates the next nightly version number (e.g.,
v0.2.1-nightly.20230101). - It then builds and publishes the packages to npm with the
nightlydist-tag. - Finally, it creates a GitHub Release for the nightly version.
Failure Handling
If any step in the nightly workflow fails, it will automatically create a new issue in the repository with the labels bug and nightly-failure. The issue will contain a link to the failed workflow run for easy debugging.
How to Use the Nightly Build
To install the latest nightly build, use the @nightly tag:
npm install -g @google/gemini-cli@nightly
We also run a Google cloud build called release-docker.yml. Which publishes the sandbox docker to match your release. This will also be moved to GH and combined with the main release file once service account permissions are sorted out.
After the Release
After the workflow has successfully completed, you can monitor its progress in the GitHub Actions tab. Once complete, you should:
- Go to the pull requests page of the repository.
- Create a new pull request from the
release/vX.Y.Zbranch tomain. - Review the pull request (it should only contain version updates in
package.jsonfiles) and merge it. This keeps the version inmainup-to-date.
Release Validation
After pushing a new release smoke testing should be performed to ensure that the packages are working as expected. This can be done by installing the packages locally and running a set of tests to ensure that they are functioning correctly.
npx -y @google/gemini-cli@latest --versionto validate the push worked as expected if you were not doing a rc or dev tagnpx -y @google/gemini-cli@<release tag> --versionto validate the tag pushed appropriately- This is destructive locally
npm uninstall @google/gemini-cli && npm uninstall -g @google/gemini-cli && npm cache clean --force && npm install @google/gemini-cli@<version> - Smoke testing a basic run through of exercising a few llm commands and tools is recommended to ensure that the packages are working as expected. We'll codify this more in the future.
When to merge the version change, or not?
The above pattern for creating patch or hotfix releases from current or older commits leaves the repository in the following state:
- The Tag (
vX.Y.Z-patch.1): This tag correctly points to the original commit on main that contains the stable code you intended to release. This is crucial. Anyone checking out this tag gets the exact code that was published. - The Branch (
release-vX.Y.Z-patch.1): This branch contains one new commit on top of the tagged commit. That new commit only contains the version number change in package.json (and other related files like package-lock.json).
This separation is good. It keeps your main branch history clean of release-specific version bumps until you decide to merge them.
This is the critical decision, and it depends entirely on the nature of the release.
Merge Back for Stable Patches and Hotfixes
You almost always want to merge the release-<tag> branch back into main for any
stable patch or hotfix release.
- Why? The primary reason is to update the version in main's package.json. If you release v1.2.1 from an older commit but never merge the version bump back, your main branch's package.json will still say "version": "1.2.0". The next developer who starts work for the next feature release (v1.3.0) will be branching from a codebase that has an incorrect, older version number. This leads to confusion and requires manual version bumping later.
- The Process: After the release-v1.2.1 branch is created and the package is successfully published, you should open a pull request to merge release-v1.2.1 into main. This PR will contain just one commit: "chore: bump version to v1.2.1". It's a clean, simple integration that keeps your main branch in sync with the latest released version.
Do NOT Merge Back for Pre-Releases (RC, Beta, Dev)
You typically do not merge release branches for pre-releases back into main.
- Why? Pre-release versions (e.g., v1.3.0-rc.1, v1.3.0-rc.2) are, by definition, not stable and are temporary. You don't want to pollute your main branch's history with a series of version bumps for release candidates. The package.json in main should reflect the latest stable release version, not an RC.
- The Process: The release-v1.3.0-rc.1 branch is created, the npm publish --tag rc happens, and then... the branch has served its purpose. You can simply delete it. The code for the RC is already on main (or a feature branch), so no functional code is lost. The release branch was just a temporary vehicle for the version number.
Local Testing and Validation: Changes to the Packaging and Publishing Process
If you need to test the release process without actually publishing to NPM or creating a public GitHub release, you can trigger the workflow manually from the GitHub UI.
- Go to the Actions tab of the repository.
- Click on the "Run workflow" dropdown.
- Leave the
dry_runoption checked (true). - Click the "Run workflow" button.
This will run the entire release process but will skip the npm publish and gh release create steps. You can inspect the workflow logs to ensure everything is working as expected.
It is crucial to test any changes to the packaging and publishing process locally before committing them. This ensures that the packages will be published correctly and that they will work as expected when installed by a user.
To validate your changes, you can perform a dry run of the publishing process. This will simulate the publishing process without actually publishing the packages to the npm registry.
npm_package_version=9.9.9 SANDBOX_IMAGE_REGISTRY="registry" SANDBOX_IMAGE_NAME="thename" npm run publish:npm --dry-run
This command will do the following:
- Build all the packages.
- Run all the prepublish scripts.
- Create the package tarballs that would be published to npm.
- Print a summary of the packages that would be published.
You can then inspect the generated tarballs to ensure that they contain the correct files and that the package.json files have been updated correctly. The tarballs will be created in the root of each package's directory (e.g., packages/cli/google-gemini-cli-0.1.6.tgz).
By performing a dry run, you can be confident that your changes to the packaging process are correct and that the packages will be published successfully.
Release Deep Dive
The main goal of the release process is to take the source code from the packages/ directory, build it, and assemble a
clean, self-contained package in a temporary bundle directory at the root of the project. This bundle directory is what
actually gets published to NPM.
Here are the key stages:
Stage 1: Pre-Release Sanity Checks and Versioning
- What happens: Before any files are moved, the process ensures the project is in a good state. This involves running tests, linting, and type-checking (npm run preflight). The version number in the root package.json and packages/cli/package.json is updated to the new release version.
- Why: This guarantees that only high-quality, working code is released. Versioning is the first step to signify a new release.
Stage 2: Building the Source Code
- What happens: The TypeScript source code in packages/core/src and packages/cli/src is compiled into JavaScript.
- File movement:
- packages/core/src/*/.ts -> compiled to -> packages/core/dist/
- packages/cli/src/*/.ts -> compiled to -> packages/cli/dist/
- Why: The TypeScript code written during development needs to be converted into plain JavaScript that can be run by Node.js. The core package is built first as the cli package depends on it.
Stage 3: Assembling the Final Publishable Package
This is the most critical stage where files are moved and transformed into their final state for publishing. A temporary
bundle folder is created at the project root to house the final package contents.
-
The
package.jsonis Transformed:- What happens: The package.json from packages/cli/ is read, modified, and written into the root
bundle/ directory. - File movement: packages/cli/package.json -> (in-memory transformation) ->
bundle/package.json - Why: The final package.json must be different from the one used in development. Key changes include:
- Removing devDependencies.
- Removing workspace-specific "dependencies": { "@gemini-cli/core": "workspace:*" } and ensuring the core code is bundled directly into the final JavaScript file.
- Ensuring the bin, main, and files fields point to the correct locations within the final package structure.
- What happens: The package.json from packages/cli/ is read, modified, and written into the root
-
The JavaScript Bundle is Created:
- What happens: The built JavaScript from both packages/core/dist and packages/cli/dist are bundled into a single, executable JavaScript file.
- File movement: packages/cli/dist/index.js + packages/core/dist/index.js -> (bundled by esbuild) ->
bundle/gemini.js (or a similar name). - Why: This creates a single, optimized file that contains all the necessary application code. It simplifies the package by removing the need for the core package to be a separate dependency on NPM, as its code is now included directly.
-
Static and Supporting Files are Copied:
- What happens: Essential files that are not part of the source code but are required for the package to work correctly
or be well-described are copied into the
bundledirectory. - File movement:
- README.md ->
bundle/README.md - LICENSE ->
bundle/LICENSE - packages/cli/src/utils/*.sb (sandbox profiles) ->
bundle/ - Why:
- The README.md and LICENSE are standard files that should be included in any NPM package.
- The sandbox profiles (.sb files) are critical runtime assets required for the CLI's sandboxing feature to function. They must be located next to the final executable.
- What happens: Essential files that are not part of the source code but are required for the package to work correctly
or be well-described are copied into the
Stage 4: Publishing to NPM
- What happens: The npm publish command is run from inside the root
bundledirectory. - Why: By running npm publish from within the
bundledirectory, only the files we carefully assembled in Stage 3 are uploaded to the NPM registry. This prevents any source code, test files, or development configurations from being accidentally published, resulting in a clean and minimal package for users.
Summary of File Flow
graph TD
subgraph "Source Files"
A["packages/core/src/*.ts<br/>packages/cli/src/*.ts"]
B["packages/cli/package.json"]
C["README.md<br/>LICENSE<br/>packages/cli/src/utils/*.sb"]
end
subgraph "Process"
D(Build)
E(Transform)
F(Assemble)
G(Publish)
end
subgraph "Artifacts"
H["Bundled JS"]
I["Final package.json"]
J["bundle/"]
end
subgraph "Destination"
K["NPM Registry"]
end
A --> D --> H
B --> E --> I
C --> F
H --> F
I --> F
F --> J
J --> G --> K
This process ensures that the final published artifact is a purpose-built, clean, and efficient representation of the project, rather than a direct copy of the development workspace.
NPM Workspaces
This project uses NPM Workspaces to manage the packages within this monorepo. This simplifies development by allowing us to manage dependencies and run scripts across multiple packages from the root of the project.
How it Works
The root package.json file defines the workspaces for this project:
{
"workspaces": ["packages/*"]
}
This tells NPM that any folder inside the packages directory is a separate package that should be managed as part of the workspace.
Benefits of Workspaces
- Simplified Dependency Management: Running
npm installfrom the root of the project will install all dependencies for all packages in the workspace and link them together. This means you don't need to runnpm installin each package's directory. - Automatic Linking: Packages within the workspace can depend on each other. When you run
npm install, NPM will automatically create symlinks between the packages. This means that when you make changes to one package, the changes are immediately available to other packages that depend on it. - Simplified Script Execution: You can run scripts in any package from the root of the project using the
--workspaceflag. For example, to run thebuildscript in theclipackage, you can runnpm run build --workspace @google/gemini-cli.
βββ quota-and-pricing.md Content:
Gemini CLI: Quotas and Pricing
Your Gemini CLI quotas and pricing depend on the type of account you use to authenticate with Google. Additionally, both quotas and pricing may be calculated differently based on the model version, requests, and tokens used. A summary of model usage is available through the /stats command and presented on exit at the end of a session. See privacy and terms for details on Privacy policy and Terms of Service. Note: published prices are list price; additional negotiated commercial discounting may apply.
This article outlines the specific quotas and pricing applicable to the Gemini CLI when using different authentication methods.
1. Log in with Google (Gemini Code Assist Free Tier)
For users who authenticate by using their Google account to access Gemini Code Assist for individuals:
- Quota:
- 60 requests per minute
- 1000 requests per day
- Token usage is not applicable
- Cost: Free
- Details: Gemini Code Assist Quotas
- Notes: A specific quota for different models is not specified; model fallback may occur to preserve shared experience quality.
2. Gemini API Key (Unpaid)
If you are using a Gemini API key for the free tier:
- Quota:
- Flash model only
- 10 requests per minute
- 250 requests per day
- Cost: Free
- Details: Gemini API Rate Limits
3. Gemini API Key (Paid)
If you are using a Gemini API key with a paid plan:
- Quota: Varies by pricing tier.
- Cost: Varies by pricing tier and model/token usage.
- Details: Gemini API Rate Limits, Gemini API Pricing
4. Login with Google (for Workspace or Licensed Code Assist users)
For users of Standard or Enterprise editions of Gemini Code Assist, quotas and pricing are based on a fixed price subscription with assigned license seats:
- Standard Tier:
- Quota: 120 requests per minute, 1500 per day
- Enterprise Tier:
- Quota: 120 requests per minute, 2000 per day
- Cost: Fixed price included with your Gemini for Google Workspace or Gemini Code Assist subscription.
- Details: Gemini Code Assist Quotas, Gemini Code Assist Pricing
- Notes:
- Specific quota for different models is not specified; model fallback may occur to preserve shared experience quality.
- Members of the Google Developer Program may have Gemini Code Assist licenses through their membership.
5. Vertex AI (Express Mode)
If you are using Vertex AI in Express Mode:
- Quota: Quotas are variable and specific to your account. See the source for more details.
- Cost: After your Express Mode usage is consumed and you enable billing for your project, cost is based on standard Vertex AI Pricing.
- Details: Vertex AI Express Mode Quotas
6. Vertex AI (Regular Mode)
If you are using the standard Vertex AI service:
- Quota: Governed by a dynamic shared quota system or pre-purchased provisioned throughput.
- Cost: Based on model and token usage. See Vertex AI Pricing.
- Details: Vertex AI Dynamic Shared Quota
7. Google One and Ultra plans, Gemini for Workspace plans
These plans currently apply only to the use of Gemini web-based products provided by Google-based experiences (for example, the Gemini web app or the Flow video editor). These plans do not apply to the API usage which powers the Gemini CLI. Supporting these plans is under active consideration for future support.
βββ sandbox.md Content:
Sandboxing in the Gemini CLI
This document provides a guide to sandboxing in the Gemini CLI, including prerequisites, quickstart, and configuration.
Prerequisites
Before using sandboxing, you need to install and set up the Gemini CLI:
npm install -g @google/gemini-cli
To verify the installation
gemini --version
Overview of sandboxing
Sandboxing isolates potentially dangerous operations (such as shell commands or file modifications) from your host system, providing a security barrier between AI operations and your environment.
The benefits of sandboxing include:
- Security: Prevent accidental system damage or data loss.
- Isolation: Limit file system access to project directory.
- Consistency: Ensure reproducible environments across different systems.
- Safety: Reduce risk when working with untrusted code or experimental commands.
Sandboxing methods
Your ideal method of sandboxing may differ depending on your platform and your preferred container solution.
1. macOS Seatbelt (macOS only)
Lightweight, built-in sandboxing using sandbox-exec.
Default profile: permissive-open - restricts writes outside project directory but allows most other operations.
2. Container-based (Docker/Podman)
Cross-platform sandboxing with complete process isolation.
Note: Requires building the sandbox image locally or using a published image from your organization's registry.
Quickstart
# Enable sandboxing with command flag
gemini -s -p "analyze the code structure"
# Use environment variable
export GEMINI_SANDBOX=true
gemini -p "run the test suite"
# Configure in settings.json
{
"sandbox": "docker"
}
Configuration
Enable sandboxing (in order of precedence)
- Command flag:
-sor--sandbox - Environment variable:
GEMINI_SANDBOX=true|docker|podman|sandbox-exec - Settings file:
"sandbox": trueinsettings.json
macOS Seatbelt profiles
Built-in profiles (set via SEATBELT_PROFILE env var):
permissive-open(default): Write restrictions, network allowedpermissive-closed: Write restrictions, no networkpermissive-proxied: Write restrictions, network via proxyrestrictive-open: Strict restrictions, network allowedrestrictive-closed: Maximum restrictions
Custom Sandbox Flags
For container-based sandboxing, you can inject custom flags into the docker or podman command using the SANDBOX_FLAGS environment variable. This is useful for advanced configurations, such as disabling security features for specific use cases.
Example (Podman):
To disable SELinux labeling for volume mounts, you can set the following:
export SANDBOX_FLAGS="--security-opt label=disable"
Multiple flags can be provided as a space-separated string:
export SANDBOX_FLAGS="--flag1 --flag2=value"
Linux UID/GID handling
The sandbox automatically handles user permissions on Linux. Override these permissions with:
export SANDBOX_SET_UID_GID=true # Force host UID/GID
export SANDBOX_SET_UID_GID=false # Disable UID/GID mapping
Troubleshooting
Common issues
"Operation not permitted"
- Operation requires access outside sandbox.
- Try more permissive profile or add mount points.
Missing commands
- Add to custom Dockerfile.
- Install via
sandbox.bashrc.
Network issues
- Check sandbox profile allows network.
- Verify proxy configuration.
Debug mode
DEBUG=1 gemini -s -p "debug command"
Note: If you have DEBUG=true in a project's .env file, it won't affect gemini-cli due to automatic exclusion. Use .gemini/.env files for gemini-cli specific debug settings.
Inspect sandbox
# Check environment
gemini -s -p "run shell command: env | grep SANDBOX"
# List mounts
gemini -s -p "run shell command: mount | grep workspace"
Security notes
- Sandboxing reduces but doesn't eliminate all risks.
- Use the most restrictive profile that allows your work.
- Container overhead is minimal after first build.
- GUI applications may not work in sandboxes.
Related documentation
- Configuration: Full configuration options.
- Commands: Available commands.
- Troubleshooting: General troubleshooting.
βββ telemetry.md Content:
Gemini CLI Observability Guide
Telemetry provides data about Gemini CLI's performance, health, and usage. By enabling it, you can monitor operations, debug issues, and optimize tool usage through traces, metrics, and structured logs.
Gemini CLI's telemetry system is built on the OpenTelemetry (OTEL) standard, allowing you to send data to any compatible backend.
Enabling telemetry
You can enable telemetry in multiple ways. Configuration is primarily managed via the .gemini/settings.json file and environment variables, but CLI flags can override these settings for a specific session.
Order of precedence
The following lists the precedence for applying telemetry settings, with items listed higher having greater precedence:
-
CLI flags (for
geminicommand):--telemetry/--no-telemetry: Overridestelemetry.enabled.--telemetry-target <local|gcp>: Overridestelemetry.target.--telemetry-otlp-endpoint <URL>: Overridestelemetry.otlpEndpoint.--telemetry-log-prompts/--no-telemetry-log-prompts: Overridestelemetry.logPrompts.--telemetry-outfile <path>: Redirects telemetry output to a file. See Exporting to a file.
-
Environment variables:
OTEL_EXPORTER_OTLP_ENDPOINT: Overridestelemetry.otlpEndpoint.
-
Workspace settings file (
.gemini/settings.json): Values from thetelemetryobject in this project-specific file. -
User settings file (
~/.gemini/settings.json): Values from thetelemetryobject in this global user file. -
Defaults: applied if not set by any of the above.
telemetry.enabled:falsetelemetry.target:localtelemetry.otlpEndpoint:http://localhost:4317telemetry.logPrompts:true
For the npm run telemetry -- --target=<gcp|local> script:
The --target argument to this script only overrides the telemetry.target for the duration and purpose of that script (i.e., choosing which collector to start). It does not permanently change your settings.json. The script will first look at settings.json for a telemetry.target to use as its default.
Example settings
The following code can be added to your workspace (.gemini/settings.json) or user (~/.gemini/settings.json) settings to enable telemetry and send the output to Google Cloud:
{
"telemetry": {
"enabled": true,
"target": "gcp"
},
"sandbox": false
}
Exporting to a file
You can export all telemetry data to a file for local inspection.
To enable file export, use the --telemetry-outfile flag with a path to your desired output file. This must be run using --telemetry-target=local.
# Set your desired output file path
TELEMETRY_FILE=".gemini/telemetry.log"
# Run Gemini CLI with local telemetry
# NOTE: --telemetry-otlp-endpoint="" is required to override the default
# OTLP exporter and ensure telemetry is written to the local file.
gemini --telemetry \
--telemetry-target=local \
--telemetry-otlp-endpoint="" \
--telemetry-outfile="$TELEMETRY_FILE" \
--prompt "What is OpenTelemetry?"
Running an OTEL Collector
An OTEL Collector is a service that receives, processes, and exports telemetry data. The CLI sends data using the OTLP/gRPC protocol.
Learn more about OTEL exporter standard configuration in documentation.
Local
Use the npm run telemetry -- --target=local command to automate the process of setting up a local telemetry pipeline, including configuring the necessary settings in your .gemini/settings.json file. The underlying script installs otelcol-contrib (the OpenTelemetry Collector) and jaeger (The Jaeger UI for viewing traces). To use it:
-
Run the command: Execute the command from the root of the repository:
bash npm run telemetry -- --target=localThe script will: - Download Jaeger and OTEL if needed. - Start a local Jaeger instance. - Start an OTEL collector configured to receive data from Gemini CLI. - Automatically enable telemetry in your workspace settings. - On exit, disable telemetry.
-
View traces: Open your web browser and navigate to http://localhost:16686 to access the Jaeger UI. Here you can inspect detailed traces of Gemini CLI operations.
-
Inspect logs and metrics: The script redirects the OTEL collector output (which includes logs and metrics) to
~/.gemini/tmp/<projectHash>/otel/collector.log. The script will provide links to view and a command to tail your telemetry data (traces, metrics, logs) locally. -
Stop the services: Press
Ctrl+Cin the terminal where the script is running to stop the OTEL Collector and Jaeger services.
Google Cloud
Use the npm run telemetry -- --target=gcp command to automate setting up a local OpenTelemetry collector that forwards data to your Google Cloud project, including configuring the necessary settings in your .gemini/settings.json file. The underlying script installs otelcol-contrib. To use it:
-
Prerequisites:
- Have a Google Cloud project ID.
- Export the
GOOGLE_CLOUD_PROJECTenvironment variable to make it available to the OTEL collector.bash export OTLP_GOOGLE_CLOUD_PROJECT="your-project-id" - Authenticate with Google Cloud (e.g., run
gcloud auth application-default loginor ensureGOOGLE_APPLICATION_CREDENTIALSis set). - Ensure your Google Cloud account/service account has the necessary IAM roles: "Cloud Trace Agent", "Monitoring Metric Writer", and "Logs Writer".
-
Run the command: Execute the command from the root of the repository:
bash npm run telemetry -- --target=gcpThe script will: - Download the
otelcol-contribbinary if needed. - Start an OTEL collector configured to receive data from Gemini CLI and export it to your specified Google Cloud project. - Automatically enable telemetry and disable sandbox mode in your workspace settings (.gemini/settings.json). - Provide direct links to view traces, metrics, and logs in your Google Cloud Console. - On exit (Ctrl+C), it will attempt to restore your original telemetry and sandbox settings. -
Run Gemini CLI: In a separate terminal, run your Gemini CLI commands. This generates telemetry data that the collector captures.
-
View telemetry in Google Cloud: Use the links provided by the script to navigate to the Google Cloud Console and view your traces, metrics, and logs.
-
Inspect local collector logs: The script redirects the local OTEL collector output to
~/.gemini/tmp/<projectHash>/otel/collector-gcp.log. The script provides links to view and command to tail your collector logs locally. -
Stop the service: Press
Ctrl+Cin the terminal where the script is running to stop the OTEL Collector.
Logs and metric reference
The following section describes the structure of logs and metrics generated for Gemini CLI.
- A
sessionIdis included as a common attribute on all logs and metrics.
Logs
Logs are timestamped records of specific events. The following events are logged for Gemini CLI:
gemini_cli.config: This event occurs once at startup with the CLI's configuration.-
Attributes:
model(string)embedding_model(string)sandbox_enabled(boolean)core_tools_enabled(string)approval_mode(string)api_key_enabled(boolean)vertex_ai_enabled(boolean)code_assist_enabled(boolean)log_prompts_enabled(boolean)file_filtering_respect_git_ignore(boolean)debug_mode(boolean)mcp_servers(string)
-
gemini_cli.user_prompt: This event occurs when a user submits a prompt. -
Attributes:
prompt_lengthprompt(this attribute is excluded iflog_prompts_enabledis configured to befalse)auth_type
-
gemini_cli.tool_call: This event occurs for each function call. -
Attributes:
function_namefunction_argsduration_mssuccess(boolean)decision(string: "accept", "reject", "auto_accept", or "modify", if applicable)error(if applicable)error_type(if applicable)metadata(if applicable, dictionary of string -> any)
-
gemini_cli.api_request: This event occurs when making a request to Gemini API. -
Attributes:
modelrequest_text(if applicable)
-
gemini_cli.api_error: This event occurs if the API request fails. -
Attributes:
modelerrorerror_typestatus_codeduration_msauth_type
-
gemini_cli.api_response: This event occurs upon receiving a response from Gemini API. -
Attributes:
modelstatus_codeduration_mserror(optional)input_token_countoutput_token_countcached_content_token_countthoughts_token_counttool_token_countresponse_text(if applicable)auth_type
-
gemini_cli.flash_fallback: This event occurs when Gemini CLI switches to flash as fallback. -
Attributes:
auth_type
-
gemini_cli.slash_command: This event occurs when a user executes a slash command. - Attributes:
command(string)subcommand(string, if applicable)
Metrics
Metrics are numerical measurements of behavior over time. The following metrics are collected for Gemini CLI:
-
gemini_cli.session.count(Counter, Int): Incremented once per CLI startup. -
gemini_cli.tool.call.count(Counter, Int): Counts tool calls. -
Attributes:
function_namesuccess(boolean)decision(string: "accept", "reject", or "modify", if applicable)
-
gemini_cli.tool.call.latency(Histogram, ms): Measures tool call latency. -
Attributes:
function_namedecision(string: "accept", "reject", or "modify", if applicable)
-
gemini_cli.api.request.count(Counter, Int): Counts all API requests. -
Attributes:
modelstatus_codeerror_type(if applicable)
-
gemini_cli.api.request.latency(Histogram, ms): Measures API request latency. -
Attributes:
model
-
gemini_cli.token.usage(Counter, Int): Counts the number of tokens used. -
Attributes:
modeltype(string: "input", "output", "thought", "cache", or "tool")
-
gemini_cli.file.operation.count(Counter, Int): Counts file operations. - Attributes:
operation(string: "create", "read", "update"): The type of file operation.lines(Int, if applicable): Number of lines in the file.mimetype(string, if applicable): Mimetype of the file.extension(string, if applicable): File extension of the file.ai_added_lines(Int, if applicable): Number of lines added/changed by AI.ai_removed_lines(Int, if applicable): Number of lines removed/changed by AI.user_added_lines(Int, if applicable): Number of lines added/changed by user in AI proposed changes.user_removed_lines(Int, if applicable): Number of lines removed/changed by user in AI proposed changes.
βββ tools/ βββ file-system.md Content:
Gemini CLI file system tools
The Gemini CLI provides a comprehensive suite of tools for interacting with the local file system. These tools allow the Gemini model to read from, write to, list, search, and modify files and directories, all under your control and typically with confirmation for sensitive operations.
Note: All file system tools operate within a rootDirectory (usually the current working directory where you launched the CLI) for security. Paths that you provide to these tools are generally expected to be absolute or are resolved relative to this root directory.
1. list_directory (ReadFolder)
list_directory lists the names of files and subdirectories directly within a specified directory path. It can optionally ignore entries matching provided glob patterns.
- Tool name:
list_directory - Display name: ReadFolder
- File:
ls.ts - Parameters:
path(string, required): The absolute path to the directory to list.ignore(array of strings, optional): A list of glob patterns to exclude from the listing (e.g.,["*.log", ".git"]).respect_git_ignore(boolean, optional): Whether to respect.gitignorepatterns when listing files. Defaults totrue.- Behavior:
- Returns a list of file and directory names.
- Indicates whether each entry is a directory.
- Sorts entries with directories first, then alphabetically.
- Output (
llmContent): A string like:Directory listing for /path/to/your/folder:\n[DIR] subfolder1\nfile1.txt\nfile2.png - Confirmation: No.
2. read_file (ReadFile)
read_file reads and returns the content of a specified file. This tool handles text, images (PNG, JPG, GIF, WEBP, SVG, BMP), and PDF files. For text files, it can read specific line ranges. Other binary file types are generally skipped.
- Tool name:
read_file - Display name: ReadFile
- File:
read-file.ts - Parameters:
path(string, required): The absolute path to the file to read.offset(number, optional): For text files, the 0-based line number to start reading from. Requireslimitto be set.limit(number, optional): For text files, the maximum number of lines to read. If omitted, reads a default maximum (e.g., 2000 lines) or the entire file if feasible.- Behavior:
- For text files: Returns the content. If
offsetandlimitare used, returns only that slice of lines. Indicates if content was truncated due to line limits or line length limits. - For image and PDF files: Returns the file content as a base64-encoded data structure suitable for model consumption.
- For other binary files: Attempts to identify and skip them, returning a message indicating it's a generic binary file.
- Output: (
llmContent): - For text files: The file content, potentially prefixed with a truncation message (e.g.,
[File content truncated: showing lines 1-100 of 500 total lines...]\nActual file content...). - For image/PDF files: An object containing
inlineDatawithmimeTypeand base64data(e.g.,{ inlineData: { mimeType: 'image/png', data: 'base64encodedstring' } }). - For other binary files: A message like
Cannot display content of binary file: /path/to/data.bin. - Confirmation: No.
3. write_file (WriteFile)
write_file writes content to a specified file. If the file exists, it will be overwritten. If the file doesn't exist, it (and any necessary parent directories) will be created.
- Tool name:
write_file - Display name: WriteFile
- File:
write-file.ts - Parameters:
file_path(string, required): The absolute path to the file to write to.content(string, required): The content to write into the file.- Behavior:
- Writes the provided
contentto thefile_path. - Creates parent directories if they don't exist.
- Output (
llmContent): A success message, e.g.,Successfully overwrote file: /path/to/your/file.txtorSuccessfully created and wrote to new file: /path/to/new/file.txt. - Confirmation: Yes. Shows a diff of changes and asks for user approval before writing.
4. glob (FindFiles)
glob finds files matching specific glob patterns (e.g., src/**/*.ts, *.md), returning absolute paths sorted by modification time (newest first).
- Tool name:
glob - Display name: FindFiles
- File:
glob.ts - Parameters:
pattern(string, required): The glob pattern to match against (e.g.,"*.py","src/**/*.js").path(string, optional): The absolute path to the directory to search within. If omitted, searches the tool's root directory.case_sensitive(boolean, optional): Whether the search should be case-sensitive. Defaults tofalse.respect_git_ignore(boolean, optional): Whether to respect .gitignore patterns when finding files. Defaults totrue.- Behavior:
- Searches for files matching the glob pattern within the specified directory.
- Returns a list of absolute paths, sorted with the most recently modified files first.
- Ignores common nuisance directories like
node_modulesand.gitby default. - Output (
llmContent): A message like:Found 5 file(s) matching "*.ts" within src, sorted by modification time (newest first):\nsrc/file1.ts\nsrc/subdir/file2.ts... - Confirmation: No.
5. search_file_content (SearchText)
search_file_content searches for a regular expression pattern within the content of files in a specified directory. Can filter files by a glob pattern. Returns the lines containing matches, along with their file paths and line numbers.
- Tool name:
search_file_content - Display name: SearchText
- File:
grep.ts - Parameters:
pattern(string, required): The regular expression (regex) to search for (e.g.,"function\s+myFunction").path(string, optional): The absolute path to the directory to search within. Defaults to the current working directory.include(string, optional): A glob pattern to filter which files are searched (e.g.,"*.js","src/**/*.{ts,tsx}"). If omitted, searches most files (respecting common ignores).- Behavior:
- Uses
git grepif available in a Git repository for speed; otherwise, falls back to systemgrepor a JavaScript-based search. - Returns a list of matching lines, each prefixed with its file path (relative to the search directory) and line number.
- Output (
llmContent): A formatted string of matches, e.g.: ``` Found 3 matches for pattern "myFunction" in path "." (filter: "*.ts"):
File: src/utils.ts L15: export function myFunction() { L22: myFunction.call();
File: src/index.ts L5: import { myFunction } from './utils';
``` - Confirmation: No.
6. replace (Edit)
replace replaces text within a file. By default, replaces a single occurrence, but can replace multiple occurrences when expected_replacements is specified. This tool is designed for precise, targeted changes and requires significant context around the old_string to ensure it modifies the correct location.
- Tool name:
replace - Display name: Edit
- File:
edit.ts - Parameters:
file_path(string, required): The absolute path to the file to modify.-
old_string(string, required): The exact literal text to replace.CRITICAL: This string must uniquely identify the single instance to change. It should include at least 3 lines of context before and after the target text, matching whitespace and indentation precisely. If
old_stringis empty, the tool attempts to create a new file atfile_pathwithnew_stringas content. -
new_string(string, required): The exact literal text to replaceold_stringwith. -
expected_replacements(number, optional): The number of occurrences to replace. Defaults to1. -
Behavior:
- If
old_stringis empty andfile_pathdoes not exist, creates a new file withnew_stringas content. - If
old_stringis provided, it reads thefile_pathand attempts to find exactly one occurrence ofold_string. - If one occurrence is found, it replaces it with
new_string. - Enhanced Reliability (Multi-Stage Edit Correction): To significantly improve the success rate of edits, especially when the model-provided
old_stringmight not be perfectly precise, the tool incorporates a multi-stage edit correction mechanism.- If the initial
old_stringisn't found or matches multiple locations, the tool can leverage the Gemini model to iteratively refineold_string(and potentiallynew_string). - This self-correction process attempts to identify the unique segment the model intended to modify, making the
replaceoperation more robust even with slightly imperfect initial context.
- If the initial
- Failure conditions: Despite the correction mechanism, the tool will fail if:
file_pathis not absolute or is outside the root directory.old_stringis not empty, but thefile_pathdoes not exist.old_stringis empty, but thefile_pathalready exists.old_stringis not found in the file after attempts to correct it.old_stringis found multiple times, and the self-correction mechanism cannot resolve it to a single, unambiguous match.- Output (
llmContent): - On success:
Successfully modified file: /path/to/file.txt (1 replacements).orCreated new file: /path/to/new_file.txt with provided content. - On failure: An error message explaining the reason (e.g.,
Failed to edit, 0 occurrences found...,Failed to edit, expected 1 occurrences but found 2...). - Confirmation: Yes. Shows a diff of the proposed changes and asks for user approval before writing to the file.
These file system tools provide a foundation for the Gemini CLI to understand and interact with your local project context.
βββ index.md Content:
Gemini CLI tools
The Gemini CLI includes built-in tools that the Gemini model uses to interact with your local environment, access information, and perform actions. These tools enhance the CLI's capabilities, enabling it to go beyond text generation and assist with a wide range of tasks.
Overview of Gemini CLI tools
In the context of the Gemini CLI, tools are specific functions or modules that the Gemini model can request to be executed. For example, if you ask Gemini to "Summarize the contents of my_document.txt," the model will likely identify the need to read that file and will request the execution of the read_file tool.
The core component (packages/core) manages these tools, presents their definitions (schemas) to the Gemini model, executes them when requested, and returns the results to the model for further processing into a user-facing response.
These tools provide the following capabilities:
- Access local information: Tools allow Gemini to access your local file system, read file contents, list directories, etc.
- Execute commands: With tools like
run_shell_command, Gemini can run shell commands (with appropriate safety measures and user confirmation). - Interact with the web: Tools can fetch content from URLs.
- Take actions: Tools can modify files, write new files, or perform other actions on your system (again, typically with safeguards).
- Ground responses: By using tools to fetch real-time or specific local data, Gemini's responses can be more accurate, relevant, and grounded in your actual context.
How to use Gemini CLI tools
To use Gemini CLI tools, provide a prompt to the Gemini CLI. The process works as follows:
- You provide a prompt to the Gemini CLI.
- The CLI sends the prompt to the core.
- The core, along with your prompt and conversation history, sends a list of available tools and their descriptions/schemas to the Gemini API.
- The Gemini model analyzes your request. If it determines that a tool is needed, its response will include a request to execute a specific tool with certain parameters.
- The core receives this tool request, validates it, and (often after user confirmation for sensitive operations) executes the tool.
- The output from the tool is sent back to the Gemini model.
- The Gemini model uses the tool's output to formulate its final answer, which is then sent back through the core to the CLI and displayed to you.
You will typically see messages in the CLI indicating when a tool is being called and whether it succeeded or failed.
Security and confirmation
Many tools, especially those that can modify your file system or execute commands (write_file, edit, run_shell_command), are designed with safety in mind. The Gemini CLI will typically:
- Require confirmation: Prompt you before executing potentially sensitive operations, showing you what action is about to be taken.
- Utilize sandboxing: All tools are subject to restrictions enforced by sandboxing (see Sandboxing in the Gemini CLI). This means that when operating in a sandbox, any tools (including MCP servers) you wish to use must be available inside the sandbox environment. For example, to run an MCP server through
npx, thenpxexecutable must be installed within the sandbox's Docker image or be available in thesandbox-execenvironment.
It's important to always review confirmation prompts carefully before allowing a tool to proceed.
Learn more about Gemini CLI's tools
Gemini CLI's built-in tools can be broadly categorized as follows:
- File System Tools: For interacting with files and directories (reading, writing, listing, searching, etc.).
- Shell Tool (
run_shell_command): For executing shell commands. - Web Fetch Tool (
web_fetch): For retrieving content from URLs. - Web Search Tool (
web_search): For searching the web. - Multi-File Read Tool (
read_many_files): A specialized tool for reading content from multiple files or directories, often used by the@command. - Memory Tool (
save_memory): For saving and recalling information across sessions.
Additionally, these tools incorporate:
- MCP servers: MCP servers act as a bridge between the Gemini model and your local environment or other services like APIs.
- Sandboxing: Sandboxing isolates the model and its changes from your environment to reduce potential risk.
βββ mcp-server.md Content:
MCP servers with the Gemini CLI
This document provides a guide to configuring and using Model Context Protocol (MCP) servers with the Gemini CLI.
What is an MCP server?
An MCP server is an application that exposes tools and resources to the Gemini CLI through the Model Context Protocol, allowing it to interact with external systems and data sources. MCP servers act as a bridge between the Gemini model and your local environment or other services like APIs.
An MCP server enables the Gemini CLI to:
- Discover tools: List available tools, their descriptions, and parameters through standardized schema definitions.
- Execute tools: Call specific tools with defined arguments and receive structured responses.
- Access resources: Read data from specific resources (though the Gemini CLI primarily focuses on tool execution).
With an MCP server, you can extend the Gemini CLI's capabilities to perform actions beyond its built-in features, such as interacting with databases, APIs, custom scripts, or specialized workflows.
Core Integration Architecture
The Gemini CLI integrates with MCP servers through a sophisticated discovery and execution system built into the core package (packages/core/src/tools/):
Discovery Layer (mcp-client.ts)
The discovery process is orchestrated by discoverMcpTools(), which:
- Iterates through configured servers from your
settings.jsonmcpServersconfiguration - Establishes connections using appropriate transport mechanisms (Stdio, SSE, or Streamable HTTP)
- Fetches tool definitions from each server using the MCP protocol
- Sanitizes and validates tool schemas for compatibility with the Gemini API
- Registers tools in the global tool registry with conflict resolution
Execution Layer (mcp-tool.ts)
Each discovered MCP tool is wrapped in a DiscoveredMCPTool instance that:
- Handles confirmation logic based on server trust settings and user preferences
- Manages tool execution by calling the MCP server with proper parameters
- Processes responses for both the LLM context and user display
- Maintains connection state and handles timeouts
Transport Mechanisms
The Gemini CLI supports three MCP transport types:
- Stdio Transport: Spawns a subprocess and communicates via stdin/stdout
- SSE Transport: Connects to Server-Sent Events endpoints
- Streamable HTTP Transport: Uses HTTP streaming for communication
How to set up your MCP server
The Gemini CLI uses the mcpServers configuration in your settings.json file to locate and connect to MCP servers. This configuration supports multiple servers with different transport mechanisms.
Configure the MCP server in settings.json
You can configure MCP servers at the global level in the ~/.gemini/settings.json file or in your project's root directory, create or open the .gemini/settings.json file. Within the file, add the mcpServers configuration block.
Configuration Structure
Add an mcpServers object to your settings.json file:
{ ...file contains other config objects
"mcpServers": {
"serverName": {
"command": "path/to/server",
"args": ["--arg1", "value1"],
"env": {
"API_KEY": "$MY_API_TOKEN"
},
"cwd": "./server-directory",
"timeout": 30000,
"trust": false
}
}
}
Configuration Properties
Each server configuration supports the following properties:
Required (one of the following)
command(string): Path to the executable for Stdio transporturl(string): SSE endpoint URL (e.g.,"http://localhost:8080/sse")httpUrl(string): HTTP streaming endpoint URL
Optional
args(string[]): Command-line arguments for Stdio transportheaders(object): Custom HTTP headers when usingurlorhttpUrlenv(object): Environment variables for the server process. Values can reference environment variables using$VAR_NAMEor${VAR_NAME}syntaxcwd(string): Working directory for Stdio transporttimeout(number): Request timeout in milliseconds (default: 600,000ms = 10 minutes)trust(boolean): Whentrue, bypasses all tool call confirmations for this server (default:false)includeTools(string[]): List of tool names to include from this MCP server. When specified, only the tools listed here will be available from this server (whitelist behavior). If not specified, all tools from the server are enabled by default.excludeTools(string[]): List of tool names to exclude from this MCP server. Tools listed here will not be available to the model, even if they are exposed by the server. Note:excludeToolstakes precedence overincludeTools- if a tool is in both lists, it will be excluded.
OAuth Support for Remote MCP Servers
The Gemini CLI supports OAuth 2.0 authentication for remote MCP servers using SSE or HTTP transports. This enables secure access to MCP servers that require authentication.
Automatic OAuth Discovery
For servers that support OAuth discovery, you can omit the OAuth configuration and let the CLI discover it automatically:
{
"mcpServers": {
"discoveredServer": {
"url": "https://api.example.com/sse"
}
}
}
The CLI will automatically:
- Detect when a server requires OAuth authentication (401 responses)
- Discover OAuth endpoints from server metadata
- Perform dynamic client registration if supported
- Handle the OAuth flow and token management
Authentication Flow
When connecting to an OAuth-enabled server:
- Initial connection attempt fails with 401 Unauthorized
- OAuth discovery finds authorization and token endpoints
- Browser opens for user authentication (requires local browser access)
- Authorization code is exchanged for access tokens
- Tokens are stored securely for future use
- Connection retry succeeds with valid tokens
Browser Redirect Requirements
Important: OAuth authentication requires that your local machine can:
- Open a web browser for authentication
- Receive redirects on
http://localhost:7777/oauth/callback
This feature will not work in:
- Headless environments without browser access
- Remote SSH sessions without X11 forwarding
- Containerized environments without browser support
Managing OAuth Authentication
Use the /mcp auth command to manage OAuth authentication:
# List servers requiring authentication
/mcp auth
# Authenticate with a specific server
/mcp auth serverName
# Re-authenticate if tokens expire
/mcp auth serverName
OAuth Configuration Properties
enabled(boolean): Enable OAuth for this serverclientId(string): OAuth client identifier (optional with dynamic registration)clientSecret(string): OAuth client secret (optional for public clients)authorizationUrl(string): OAuth authorization endpoint (auto-discovered if omitted)tokenUrl(string): OAuth token endpoint (auto-discovered if omitted)scopes(string[]): Required OAuth scopesredirectUri(string): Custom redirect URI (defaults tohttp://localhost:7777/oauth/callback)tokenParamName(string): Query parameter name for tokens in SSE URLsaudiences(string[]): Audiences the token is valid for
Token Management
OAuth tokens are automatically:
- Stored securely in
~/.gemini/mcp-oauth-tokens.json - Refreshed when expired (if refresh tokens are available)
- Validated before each connection attempt
- Cleaned up when invalid or expired
Authentication Provider Type
You can specify the authentication provider type using the authProviderType property:
authProviderType(string): Specifies the authentication provider. Can be one of the following:dynamic_discovery(default): The CLI will automatically discover the OAuth configuration from the server.google_credentials: The CLI will use the Google Application Default Credentials (ADC) to authenticate with the server. When using this provider, you must specify the required scopes.
{
"mcpServers": {
"googleCloudServer": {
"httpUrl": "https://my-gcp-service.run.app/mcp",
"authProviderType": "google_credentials",
"oauth": {
"scopes": ["https://www.googleapis.com/auth/userinfo.email"]
}
}
}
}
Example Configurations
Python MCP Server (Stdio)
{
"mcpServers": {
"pythonTools": {
"command": "python",
"args": ["-m", "my_mcp_server", "--port", "8080"],
"cwd": "./mcp-servers/python",
"env": {
"DATABASE_URL": "$DB_CONNECTION_STRING",
"API_KEY": "${EXTERNAL_API_KEY}"
},
"timeout": 15000
}
}
}
Node.js MCP Server (Stdio)
{
"mcpServers": {
"nodeServer": {
"command": "node",
"args": ["dist/server.js", "--verbose"],
"cwd": "./mcp-servers/node",
"trust": true
}
}
}
Docker-based MCP Server
{
"mcpServers": {
"dockerizedServer": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e",
"API_KEY",
"-v",
"${PWD}:/workspace",
"my-mcp-server:latest"
],
"env": {
"API_KEY": "$EXTERNAL_SERVICE_TOKEN"
}
}
}
}
HTTP-based MCP Server
{
"mcpServers": {
"httpServer": {
"httpUrl": "http://localhost:3000/mcp",
"timeout": 5000
}
}
}
HTTP-based MCP Server with Custom Headers
{
"mcpServers": {
"httpServerWithAuth": {
"httpUrl": "http://localhost:3000/mcp",
"headers": {
"Authorization": "Bearer your-api-token",
"X-Custom-Header": "custom-value",
"Content-Type": "application/json"
},
"timeout": 5000
}
}
}
MCP Server with Tool Filtering
{
"mcpServers": {
"filteredServer": {
"command": "python",
"args": ["-m", "my_mcp_server"],
"includeTools": ["safe_tool", "file_reader", "data_processor"],
// "excludeTools": ["dangerous_tool", "file_deleter"],
"timeout": 30000
}
}
}
Discovery Process Deep Dive
When the Gemini CLI starts, it performs MCP server discovery through the following detailed process:
1. Server Iteration and Connection
For each configured server in mcpServers:
- Status tracking begins: Server status is set to
CONNECTING - Transport selection: Based on configuration properties:
httpUrlβStreamableHTTPClientTransporturlβSSEClientTransportcommandβStdioClientTransport- Connection establishment: The MCP client attempts to connect with the configured timeout
- Error handling: Connection failures are logged and the server status is set to
DISCONNECTED
2. Tool Discovery
Upon successful connection:
- Tool listing: The client calls the MCP server's tool listing endpoint
- Schema validation: Each tool's function declaration is validated
- Tool filtering: Tools are filtered based on
includeToolsandexcludeToolsconfiguration - Name sanitization: Tool names are cleaned to meet Gemini API requirements:
- Invalid characters (non-alphanumeric, underscore, dot, hyphen) are replaced with underscores
- Names longer than 63 characters are truncated with middle replacement (
___)
3. Conflict Resolution
When multiple servers expose tools with the same name:
- First registration wins: The first server to register a tool name gets the unprefixed name
- Automatic prefixing: Subsequent servers get prefixed names:
serverName__toolName - Registry tracking: The tool registry maintains mappings between server names and their tools
4. Schema Processing
Tool parameter schemas undergo sanitization for Gemini API compatibility:
$schemaproperties are removedadditionalPropertiesare strippedanyOfwithdefaulthave their default values removed (Vertex AI compatibility)- Recursive processing applies to nested schemas
5. Connection Management
After discovery:
- Persistent connections: Servers that successfully register tools maintain their connections
- Cleanup: Servers that provide no usable tools have their connections closed
- Status updates: Final server statuses are set to
CONNECTEDorDISCONNECTED
Tool Execution Flow
When the Gemini model decides to use an MCP tool, the following execution flow occurs:
1. Tool Invocation
The model generates a FunctionCall with:
- Tool name: The registered name (potentially prefixed)
- Arguments: JSON object matching the tool's parameter schema
2. Confirmation Process
Each DiscoveredMCPTool implements sophisticated confirmation logic:
Trust-based Bypass
if (this.trust) {
return false; // No confirmation needed
}
Dynamic Allow-listing
The system maintains internal allow-lists for:
- Server-level:
serverNameβ All tools from this server are trusted - Tool-level:
serverName.toolNameβ This specific tool is trusted
User Choice Handling
When confirmation is required, users can choose:
- Proceed once: Execute this time only
- Always allow this tool: Add to tool-level allow-list
- Always allow this server: Add to server-level allow-list
- Cancel: Abort execution
3. Execution
Upon confirmation (or trust bypass):
- Parameter preparation: Arguments are validated against the tool's schema
- MCP call: The underlying
CallableToolinvokes the server with:
typescript
const functionCalls = [
{
name: this.serverToolName, // Original server tool name
args: params,
},
];
- Response processing: Results are formatted for both LLM context and user display
4. Response Handling
The execution result contains:
llmContent: Raw response parts for the language model's contextreturnDisplay: Formatted output for user display (often JSON in markdown code blocks)
How to interact with your MCP server
Using the /mcp Command
The /mcp command provides comprehensive information about your MCP server setup:
/mcp
This displays:
- Server list: All configured MCP servers
- Connection status:
CONNECTED,CONNECTING, orDISCONNECTED - Server details: Configuration summary (excluding sensitive data)
- Available tools: List of tools from each server with descriptions
- Discovery state: Overall discovery process status
Example /mcp Output
MCP Servers Status:
π‘ pythonTools (CONNECTED)
Command: python -m my_mcp_server --port 8080
Working Directory: ./mcp-servers/python
Timeout: 15000ms
Tools: calculate_sum, file_analyzer, data_processor
π nodeServer (DISCONNECTED)
Command: node dist/server.js --verbose
Error: Connection refused
π³ dockerizedServer (CONNECTED)
Command: docker run -i --rm -e API_KEY my-mcp-server:latest
Tools: docker__deploy, docker__status
Discovery State: COMPLETED
Tool Usage
Once discovered, MCP tools are available to the Gemini model like built-in tools. The model will automatically:
- Select appropriate tools based on your requests
- Present confirmation dialogs (unless the server is trusted)
- Execute tools with proper parameters
- Display results in a user-friendly format
Status Monitoring and Troubleshooting
Connection States
The MCP integration tracks several states:
Server Status (MCPServerStatus)
DISCONNECTED: Server is not connected or has errorsCONNECTING: Connection attempt in progressCONNECTED: Server is connected and ready
Discovery State (MCPDiscoveryState)
NOT_STARTED: Discovery hasn't begunIN_PROGRESS: Currently discovering serversCOMPLETED: Discovery finished (with or without errors)
Common Issues and Solutions
Server Won't Connect
Symptoms: Server shows DISCONNECTED status
Troubleshooting:
- Check configuration: Verify
command,args, andcwdare correct - Test manually: Run the server command directly to ensure it works
- Check dependencies: Ensure all required packages are installed
- Review logs: Look for error messages in the CLI output
- Verify permissions: Ensure the CLI can execute the server command
No Tools Discovered
Symptoms: Server connects but no tools are available
Troubleshooting:
- Verify tool registration: Ensure your server actually registers tools
- Check MCP protocol: Confirm your server implements the MCP tool listing correctly
- Review server logs: Check stderr output for server-side errors
- Test tool listing: Manually test your server's tool discovery endpoint
Tools Not Executing
Symptoms: Tools are discovered but fail during execution
Troubleshooting:
- Parameter validation: Ensure your tool accepts the expected parameters
- Schema compatibility: Verify your input schemas are valid JSON Schema
- Error handling: Check if your tool is throwing unhandled exceptions
- Timeout issues: Consider increasing the
timeoutsetting
Sandbox Compatibility
Symptoms: MCP servers fail when sandboxing is enabled
Solutions:
- Docker-based servers: Use Docker containers that include all dependencies
- Path accessibility: Ensure server executables are available in the sandbox
- Network access: Configure sandbox to allow necessary network connections
- Environment variables: Verify required environment variables are passed through
Debugging Tips
- Enable debug mode: Run the CLI with
--debugfor verbose output - Check stderr: MCP server stderr is captured and logged (INFO messages filtered)
- Test isolation: Test your MCP server independently before integrating
- Incremental setup: Start with simple tools before adding complex functionality
- Use
/mcpfrequently: Monitor server status during development
Important Notes
Security Considerations
- Trust settings: The
trustoption bypasses all confirmation dialogs. Use cautiously and only for servers you completely control - Access tokens: Be security-aware when configuring environment variables containing API keys or tokens
- Sandbox compatibility: When using sandboxing, ensure MCP servers are available within the sandbox environment
- Private data: Using broadly scoped personal access tokens can lead to information leakage between repositories
Performance and Resource Management
- Connection persistence: The CLI maintains persistent connections to servers that successfully register tools
- Automatic cleanup: Connections to servers providing no tools are automatically closed
- Timeout management: Configure appropriate timeouts based on your server's response characteristics
- Resource monitoring: MCP servers run as separate processes and consume system resources
Schema Compatibility
- Property stripping: The system automatically removes certain schema properties (
$schema,additionalProperties) for Gemini API compatibility - Name sanitization: Tool names are automatically sanitized to meet API requirements
- Conflict resolution: Tool name conflicts between servers are resolved through automatic prefixing
This comprehensive integration makes MCP servers a powerful way to extend the Gemini CLI's capabilities while maintaining security, reliability, and ease of use.
Returning Rich Content from Tools
MCP tools are not limited to returning simple text. You can return rich, multi-part content, including text, images, audio, and other binary data in a single tool response. This allows you to build powerful tools that can provide diverse information to the model in a single turn.
All data returned from the tool is processed and sent to the model as context for its next generation, enabling it to reason about or summarize the provided information.
How It Works
To return rich content, your tool's response must adhere to the MCP specification for a CallToolResult. The content field of the result should be an array of ContentBlock objects. The Gemini CLI will correctly process this array, separating text from binary data and packaging it for the model.
You can mix and match different content block types in the content array. The supported block types include:
textimageaudioresource(embedded content)resource_link
Example: Returning Text and an Image
Here is an example of a valid JSON response from an MCP tool that returns both a text description and an image:
{
"content": [
{
"type": "text",
"text": "Here is the logo you requested."
},
{
"type": "image",
"data": "BASE64_ENCODED_IMAGE_DATA_HERE",
"mimeType": "image/png"
},
{
"type": "text",
"text": "The logo was created in 2025."
}
]
}
When the Gemini CLI receives this response, it will:
- Extract all the text and combine it into a single
functionResponsepart for the model. - Present the image data as a separate
inlineDatapart. - Provide a clean, user-friendly summary in the CLI, indicating that both text and an image were received.
This enables you to build sophisticated tools that can provide rich, multi-modal context to the Gemini model.
MCP Prompts as Slash Commands
In addition to tools, MCP servers can expose predefined prompts that can be executed as slash commands within the Gemini CLI. This allows you to create shortcuts for common or complex queries that can be easily invoked by name.
Defining Prompts on the Server
Here's a small example of a stdio MCP server that defines prompts:
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
const server = new McpServer({
name: 'prompt-server',
version: '1.0.0',
});
server.registerPrompt(
'poem-writer',
{
title: 'Poem Writer',
description: 'Write a nice haiku',
argsSchema: { title: z.string(), mood: z.string().optional() },
},
({ title, mood }) => ({
messages: [
{
role: 'user',
content: {
type: 'text',
text: `Write a haiku${mood ? ` with the mood ${mood}` : ''} called ${title}. Note that a haiku is 5 syllables followed by 7 syllables followed by 5 syllables `,
},
},
],
}),
);
const transport = new StdioServerTransport();
await server.connect(transport);
This can be included in settings.json under mcpServers with:
"nodeServer": {
"command": "node",
"args": ["filename.ts"],
}
Invoking Prompts
Once a prompt is discovered, you can invoke it using its name as a slash command. The CLI will automatically handle parsing arguments.
/poem-writer --title="Gemini CLI" --mood="reverent"
or, using positional arguments:
/poem-writer "Gemini CLI" reverent
When you run this command, the Gemini CLI executes the prompts/get method on the MCP server with the provided arguments. The server is responsible for substituting the arguments into the prompt template and returning the final prompt text. The CLI then sends this prompt to the model for execution. This provides a convenient way to automate and share common workflows.
Managing MCP Servers with gemini mcp
While you can always configure MCP servers by manually editing your settings.json file, the Gemini CLI provides a convenient set of commands to manage your server configurations programmatically. These commands streamline the process of adding, listing, and removing MCP servers without needing to directly edit JSON files.
Adding a Server (gemini mcp add)
The add command configures a new MCP server in your settings.json. Based on the scope (-s, --scope), it will be added to either the user config ~/.gemini/settings.json or the project config .gemini/settings.json file.
Command:
gemini mcp add [options] <name> <commandOrUrl> [args...]
<name>: A unique name for the server.<commandOrUrl>: The command to execute (forstdio) or the URL (forhttp/sse).[args...]: Optional arguments for astdiocommand.
Options (Flags):
-s, --scope: Configuration scope (user or project). [default: "project"]-t, --transport: Transport type (stdio, sse, http). [default: "stdio"]-e, --env: Set environment variables (e.g. -e KEY=value).-H, --header: Set HTTP headers for SSE and HTTP transports (e.g. -H "X-Api-Key: abc123" -H "Authorization: Bearer abc123").--timeout: Set connection timeout in milliseconds.--trust: Trust the server (bypass all tool call confirmation prompts).--description: Set the description for the server.--include-tools: A comma-separated list of tools to include.--exclude-tools: A comma-separated list of tools to exclude.
Adding an stdio server
This is the default transport for running local servers.
# Basic syntax
gemini mcp add <name> <command> [args...]
# Example: Adding a local server
gemini mcp add my-stdio-server -e API_KEY=123 /path/to/server arg1 arg2 arg3
# Example: Adding a local python server
gemini mcp add python-server python server.py --port 8080
Adding an HTTP server
This transport is for servers that use the streamable HTTP transport.
# Basic syntax
gemini mcp add --transport http <name> <url>
# Example: Adding an HTTP server
gemini mcp add --transport http http-server https://api.example.com/mcp/
# Example: Adding an HTTP server with an authentication header
gemini mcp add --transport http secure-http https://api.example.com/mcp/ --header "Authorization: Bearer abc123"
Adding an SSE server
This transport is for servers that use Server-Sent Events (SSE).
# Basic syntax
gemini mcp add --transport sse <name> <url>
# Example: Adding an SSE server
gemini mcp add --transport sse sse-server https://api.example.com/sse/
# Example: Adding an SSE server with an authentication header
gemini mcp add --transport sse secure-sse https://api.example.com/sse/ --header "Authorization: Bearer abc123"
Listing Servers (gemini mcp list)
To view all MCP servers currently configured, use the list command. It displays each server's name, configuration details, and connection status.
Command:
gemini mcp list
Example Output:
β stdio-server: command: python3 server.py (stdio) - Connected
β http-server: https://api.example.com/mcp (http) - Connected
β sse-server: https://api.example.com/sse (sse) - Disconnected
Removing a Server (gemini mcp remove)
To delete a server from your configuration, use the remove command with the server's name.
Command:
gemini mcp remove <name>
Example:
gemini mcp remove my-server
This will find and delete the "my-server" entry from the mcpServers object in the appropriate settings.json file based on the scope (-s, --scope).
βββ memory.md Content:
Memory Tool (save_memory)
This document describes the save_memory tool for the Gemini CLI.
Description
Use save_memory to save and recall information across your Gemini CLI sessions. With save_memory, you can direct the CLI to remember key details across sessions, providing personalized and directed assistance.
Arguments
save_memory takes one argument:
fact(string, required): The specific fact or piece of information to remember. This should be a clear, self-contained statement written in natural language.
How to use save_memory with the Gemini CLI
The tool appends the provided fact to a special GEMINI.md file located in the user's home directory (~/.gemini/GEMINI.md). This file can be configured to have a different name.
Once added, the facts are stored under a ## Gemini Added Memories section. This file is loaded as context in subsequent sessions, allowing the CLI to recall the saved information.
Usage:
save_memory(fact="Your fact here.")
save_memory examples
Remember a user preference:
save_memory(fact="My preferred programming language is Python.")
Store a project-specific detail:
save_memory(fact="The project I'm currently working on is called 'gemini-cli'.")
Important notes
- General usage: This tool should be used for concise, important facts. It is not intended for storing large amounts of data or conversational history.
- Memory file: The memory file is a plain text Markdown file, so you can view and edit it manually if needed.
βββ multi-file.md Content:
Multi File Read Tool (read_many_files)
This document describes the read_many_files tool for the Gemini CLI.
Description
Use read_many_files to read content from multiple files specified by paths or glob patterns. The behavior of this tool depends on the provided files:
- For text files, this tool concatenates their content into a single string.
- For image (e.g., PNG, JPEG), PDF, audio (MP3, WAV), and video (MP4, MOV) files, it reads and returns them as base64-encoded data, provided they are explicitly requested by name or extension.
read_many_files can be used to perform tasks such as getting an overview of a codebase, finding where specific functionality is implemented, reviewing documentation, or gathering context from multiple configuration files.
Note: read_many_files looks for files following the provided paths or glob patterns. A directory path such as "/docs" will return an empty result; the tool requires a pattern such as "/docs/*" or "/docs/*.md" to identify the relevant files.
Arguments
read_many_files takes the following arguments:
paths(list[string], required): An array of glob patterns or paths relative to the tool's target directory (e.g.,["src/**/*.ts"],["README.md", "docs/*", "assets/logo.png"]).exclude(list[string], optional): Glob patterns for files/directories to exclude (e.g.,["**/*.log", "temp/"]). These are added to default excludes ifuseDefaultExcludesis true.include(list[string], optional): Additional glob patterns to include. These are merged withpaths(e.g.,["*.test.ts"]to specifically add test files if they were broadly excluded, or["images/*.jpg"]to include specific image types).recursive(boolean, optional): Whether to search recursively. This is primarily controlled by**in glob patterns. Defaults totrue.useDefaultExcludes(boolean, optional): Whether to apply a list of default exclusion patterns (e.g.,node_modules,.git, non image/pdf binary files). Defaults totrue.respect_git_ignore(boolean, optional): Whether to respect .gitignore patterns when finding files. Defaults to true.
How to use read_many_files with the Gemini CLI
read_many_files searches for files matching the provided paths and include patterns, while respecting exclude patterns and default excludes (if enabled).
- For text files: it reads the content of each matched file (attempting to skip binary files not explicitly requested as image/PDF) and concatenates it into a single string, with a separator
--- {filePath} ---between the content of each file. Uses UTF-8 encoding by default. - For image and PDF files: if explicitly requested by name or extension (e.g.,
paths: ["logo.png"]orinclude: ["*.pdf"]), the tool reads the file and returns its content as a base64 encoded string. - The tool attempts to detect and skip other binary files (those not matching common image/PDF types or not explicitly requested) by checking for null bytes in their initial content.
Usage:
read_many_files(paths=["Your files or paths here."], include=["Additional files to include."], exclude=["Files to exclude."], recursive=False, useDefaultExcludes=false, respect_git_ignore=true)
read_many_files examples
Read all TypeScript files in the src directory:
read_many_files(paths=["src/**/*.ts"])
Read the main README, all Markdown files in the docs directory, and a specific logo image, excluding a specific file:
read_many_files(paths=["README.md", "docs/**/*.md", "assets/logo.png"], exclude=["docs/OLD_README.md"])
Read all JavaScript files but explicitly include test files and all JPEGs in an images folder:
read_many_files(paths=["**/*.js"], include=["**/*.test.js", "images/**/*.jpg"], useDefaultExcludes=False)
Important notes
- Binary file handling:
- Image/PDF/Audio/Video files: The tool can read common image types (PNG, JPEG, etc.), PDF, audio (mp3, wav), and video (mp4, mov) files, returning them as base64 encoded data. These files must be explicitly targeted by the
pathsorincludepatterns (e.g., by specifying the exact filename likevideo.mp4or a pattern like*.mov). - Other binary files: The tool attempts to detect and skip other types of binary files by examining their initial content for null bytes. The tool excludes these files from its output.
- Performance: Reading a very large number of files or very large individual files can be resource-intensive.
- Path specificity: Ensure paths and glob patterns are correctly specified relative to the tool's target directory. For image/PDF files, ensure the patterns are specific enough to include them.
- Default excludes: Be aware of the default exclusion patterns (like
node_modules,.git) and useuseDefaultExcludes=Falseif you need to override them, but do so cautiously.
βββ shell.md Content:
Shell Tool (run_shell_command)
This document describes the run_shell_command tool for the Gemini CLI.
Description
Use run_shell_command to interact with the underlying system, run scripts, or perform command-line operations. run_shell_command executes a given shell command. On Windows, the command will be executed with cmd.exe /c. On other platforms, the command will be executed with bash -c.
Arguments
run_shell_command takes the following arguments:
command(string, required): The exact shell command to execute.description(string, optional): A brief description of the command's purpose, which will be shown to the user.directory(string, optional): The directory (relative to the project root) in which to execute the command. If not provided, the command runs in the project root.
How to use run_shell_command with the Gemini CLI
When using run_shell_command, the command is executed as a subprocess. run_shell_command can start background processes using &. The tool returns detailed information about the execution, including:
Command: The command that was executed.Directory: The directory where the command was run.Stdout: Output from the standard output stream.Stderr: Output from the standard error stream.Error: Any error message reported by the subprocess.Exit Code: The exit code of the command.Signal: The signal number if the command was terminated by a signal.Background PIDs: A list of PIDs for any background processes started.
Usage:
run_shell_command(command="Your commands.", description="Your description of the command.", directory="Your execution directory.")
run_shell_command examples
List files in the current directory:
run_shell_command(command="ls -la")
Run a script in a specific directory:
run_shell_command(command="./my_script.sh", directory="scripts", description="Run my custom script")
Start a background server:
run_shell_command(command="npm run dev &", description="Start development server in background")
Important notes
- Security: Be cautious when executing commands, especially those constructed from user input, to prevent security vulnerabilities.
- Interactive commands: Avoid commands that require interactive user input, as this can cause the tool to hang. Use non-interactive flags if available (e.g.,
npm init -y). - Error handling: Check the
Stderr,Error, andExit Codefields to determine if a command executed successfully. - Background processes: When a command is run in the background with
&, the tool will return immediately and the process will continue to run in the background. TheBackground PIDsfield will contain the process ID of the background process.
Environment Variables
When run_shell_command executes a command, it sets the GEMINI_CLI=1 environment variable in the subprocess's environment. This allows scripts or tools to detect if they are being run from within the Gemini CLI.
Command Restrictions
You can restrict the commands that can be executed by the run_shell_command tool by using the coreTools and excludeTools settings in your configuration file.
coreTools: To restrictrun_shell_commandto a specific set of commands, add entries to thecoreToolslist in the formatrun_shell_command(<command>). For example,"coreTools": ["run_shell_command(git)"]will only allowgitcommands. Including the genericrun_shell_commandacts as a wildcard, allowing any command not explicitly blocked.excludeTools: To block specific commands, add entries to theexcludeToolslist in the formatrun_shell_command(<command>). For example,"excludeTools": ["run_shell_command(rm)"]will blockrmcommands.
The validation logic is designed to be secure and flexible:
- Command Chaining Disabled: The tool automatically splits commands chained with
&&,||, or;and validates each part separately. If any part of the chain is disallowed, the entire command is blocked. - Prefix Matching: The tool uses prefix matching. For example, if you allow
git, you can rungit statusorgit log. - Blocklist Precedence: The
excludeToolslist is always checked first. If a command matches a blocked prefix, it will be denied, even if it also matches an allowed prefix incoreTools.
Command Restriction Examples
Allow only specific command prefixes
To allow only git and npm commands, and block all others:
{
"coreTools": ["run_shell_command(git)", "run_shell_command(npm)"]
}
git status: Allowednpm install: Allowedls -l: Blocked
Block specific command prefixes
To block rm and allow all other commands:
{
"coreTools": ["run_shell_command"],
"excludeTools": ["run_shell_command(rm)"]
}
rm -rf /: Blockedgit status: Allowednpm install: Allowed
Blocklist takes precedence
If a command prefix is in both coreTools and excludeTools, it will be blocked.
{
"coreTools": ["run_shell_command(git)"],
"excludeTools": ["run_shell_command(git push)"]
}
git push origin main: Blockedgit status: Allowed
Block all shell commands
To block all shell commands, add the run_shell_command wildcard to excludeTools:
{
"excludeTools": ["run_shell_command"]
}
ls -l: Blockedany other command: Blocked
Security Note for excludeTools
Command-specific restrictions in excludeTools for run_shell_command are based on simple string matching and can be easily bypassed. This feature is not a security mechanism and should not be relied upon to safely execute untrusted code. It is recommended to use coreTools to explicitly select commands
that can be executed.
βββ web-fetch.md Content:
Web Fetch Tool (web_fetch)
This document describes the web_fetch tool for the Gemini CLI.
Description
Use web_fetch to summarize, compare, or extract information from web pages. The web_fetch tool processes content from one or more URLs (up to 20) embedded in a prompt. web_fetch takes a natural language prompt and returns a generated response.
Arguments
web_fetch takes one argument:
prompt(string, required): A comprehensive prompt that includes the URL(s) (up to 20) to fetch and specific instructions on how to process their content. For example:"Summarize https://example.com/article and extract key points from https://another.com/data". The prompt must contain at least one URL starting withhttp://orhttps://.
How to use web_fetch with the Gemini CLI
To use web_fetch with the Gemini CLI, provide a natural language prompt that contains URLs. The tool will ask for confirmation before fetching any URLs. Once confirmed, the tool will process URLs through Gemini API's urlContext.
If the Gemini API cannot access the URL, the tool will fall back to fetching content directly from the local machine. The tool will format the response, including source attribution and citations where possible. The tool will then provide the response to the user.
Usage:
web_fetch(prompt="Your prompt, including a URL such as https://google.com.")
web_fetch examples
Summarize a single article:
web_fetch(prompt="Can you summarize the main points of https://example.com/news/latest")
Compare two articles:
web_fetch(prompt="What are the differences in the conclusions of these two papers: https://arxiv.org/abs/2401.0001 and https://arxiv.org/abs/2401.0002?")
Important notes
- URL processing:
web_fetchrelies on the Gemini API's ability to access and process the given URLs. - Output quality: The quality of the output will depend on the clarity of the instructions in the prompt.
βββ web-search.md Content:
Web Search Tool (google_web_search)
This document describes the google_web_search tool.
Description
Use google_web_search to perform a web search using Google Search via the Gemini API. The google_web_search tool returns a summary of web results with sources.
Arguments
google_web_search takes one argument:
query(string, required): The search query.
How to use google_web_search with the Gemini CLI
The google_web_search tool sends a query to the Gemini API, which then performs a web search. google_web_search will return a generated response based on the search results, including citations and sources.
Usage:
google_web_search(query="Your query goes here.")
google_web_search examples
Get information on a topic:
google_web_search(query="latest advancements in AI-powered code generation")
Important notes
- Response returned: The
google_web_searchtool returns a processed summary, not a raw list of search results. - Citations: The response includes citations to the sources used to generate the summary.
βββ tos-privacy.md Content:
Gemini CLI: Terms of Service and Privacy Notice
Gemini CLI is an open-source tool that lets you interact with Google's powerful language models directly from your command-line interface. The Terms of Service and Privacy Notices that apply to your usage of the Gemini CLI depend on the type of account you use to authenticate with Google.
This article outlines the specific terms and privacy policies applicable for different account types and authentication methods. Note: See quotas and pricing for the quota and pricing details that apply to your usage of the Gemini CLI.
How to determine your authentication method
Your authentication method refers to the method you use to log into and access the Gemini CLI. There are four ways to authenticate:
- Logging in with your Google account to Gemini Code Assist for Individuals
- Logging in with your Google account to Gemini Code Assist for Workspace, Standard, or Enterprise Users
- Using an API key with Gemini Developer
- Using an API key with Vertex AI GenAI API
For each of these four methods of authentication, different Terms of Service and Privacy Notices may apply.
| Authentication | Account | Terms of Service | Privacy Notice |
|---|---|---|---|
| Gemini Code Assist via Google | Individual | Google Terms of Service | Gemini Code Assist Privacy Notice for Individuals |
| Gemini Code Assist via Google | Standard/Enterprise | Google Cloud Platform Terms of Service | Gemini Code Assist Privacy Notice for Standard and Enterprise |
| Gemini Developer API | Unpaid | Gemini API Terms of Service - Unpaid Services | Google Privacy Policy |
| Gemini Developer API | Paid | Gemini API Terms of Service - Paid Services | Google Privacy Policy |
| Vertex AI Gen API | Google Cloud Platform Service Terms | Google Cloud Privacy Notice |
1. If you have logged in with your Google account to Gemini Code Assist for Individuals
For users who use their Google account to access Gemini Code Assist for Individuals, these Terms of Service and Privacy Notice documents apply:
- Terms of Service: Your use of the Gemini CLI is governed by the Google Terms of Service.
- Privacy Notice: The collection and use of your data is described in the Gemini Code Assist Privacy Notice for Individuals.
2. If you have logged in with your Google account to Gemini Code Assist for Workspace, Standard, or Enterprise Users
For users who use their Google account to access the Standard or Enterprise edition of Gemini Code Assist, these Terms of Service and Privacy Notice documents apply:
- Terms of Service: Your use of the Gemini CLI is governed by the Google Cloud Platform Terms of Service.
- Privacy Notice: The collection and use of your data is described in the Gemini Code Assist Privacy Notices for Standard and Enterprise Users.
3. If you have logged in with a Gemini API key to the Gemini Developer API
If you are using a Gemini API key for authentication with the Gemini Developer API, these Terms of Service and Privacy Notice documents apply:
- Terms of Service: Your use of the Gemini CLI is governed by the Gemini API Terms of Service. These terms may differ depending on whether you are using an unpaid or paid service:
- For unpaid services, refer to the Gemini API Terms of Service - Unpaid Services.
- For paid services, refer to the Gemini API Terms of Service - Paid Services.
- Privacy Notice: The collection and use of your data is described in the Google Privacy Policy.
4. If you have logged in with a Gemini API key to the Vertex AI GenAI API
If you are using a Gemini API key for authentication with a Vertex AI GenAI API backend, these Terms of Service and Privacy Notice documents apply:
- Terms of Service: Your use of the Gemini CLI is governed by the Google Cloud Platform Service Terms.
- Privacy Notice: The collection and use of your data is described in the Google Cloud Privacy Notice.
Usage Statistics Opt-Out
You may opt-out from sending Usage Statistics to Google by following the instructions available here: Usage Statistics Configuration.
Frequently Asked Questions (FAQ) for the Gemini CLI
1. Is my code, including prompts and answers, used to train Google's models?
Whether your code, including prompts and answers, is used to train Google's models depends on the type of authentication method you use and your account type.
By default (if you have not opted out):
- Google account with Gemini Code Assist for Individuals: Yes. When you use your personal Google account, the Gemini Code Assist Privacy Notice for Individuals applies. Under this notice, your prompts, answers, and related code are collected and may be used to improve Google's products, including for model training.
- Google account with Gemini Code Assist for Workspace, Standard, or Enterprise: No. For these accounts, your data is governed by the Gemini Code Assist Privacy Notices terms, which treat your inputs as confidential. Your prompts, answers, and related code are not collected and are not used to train models.
- Gemini API key via the Gemini Developer API: Whether your code is collected or used depends on whether you are using an unpaid or paid service.
- Unpaid services: Yes. When you use the Gemini API key via the Gemini Developer API with an unpaid service, the Gemini API Terms of Service - Unpaid Services terms apply. Under this notice, your prompts, answers, and related code are collected and may be used to improve Google's products, including for model training.
- Paid services: No. When you use the Gemini API key via the Gemini Developer API with a paid service, the Gemini API Terms of Service - Paid Services terms apply, which treats your inputs as confidential. Your prompts, answers, and related code are not collected and are not used to train models.
- Gemini API key via the Vertex AI GenAI API: No. For these accounts, your data is governed by the Google Cloud Privacy Notice terms, which treat your inputs as confidential. Your prompts, answers, and related code are not collected and are not used to train models.
For more information about opting out, refer to the next question.
2. What are Usage Statistics and what does the opt-out control?
The Usage Statistics setting is the single control for all optional data collection in the Gemini CLI.
The data it collects depends on your account and authentication type:
- Google account with Gemini Code Assist for Individuals: When enabled, this setting allows Google to collect both anonymous telemetry (for example, commands run and performance metrics) and your prompts and answers, including code, for model improvement.
- Google account with Gemini Code Assist for Workspace, Standard, or Enterprise: This setting only controls the collection of anonymous telemetry. Your prompts and answers, including code, are never collected, regardless of this setting.
- Gemini API key via the Gemini Developer API: Unpaid services: When enabled, this setting allows Google to collect both anonymous telemetry (like commands run and performance metrics) and your prompts and answers, including code, for model improvement. When disabled we will use your data as described in How Google Uses Your Data. Paid services: This setting only controls the collection of anonymous telemetry. Google logs prompts and responses for a limited period of time, solely for the purpose of detecting violations of the Prohibited Use Policy and any required legal or regulatory disclosures.
- Gemini API key via the Vertex AI GenAI API: This setting only controls the collection of anonymous telemetry. Your prompts and answers, including code, are never collected, regardless of this setting.
Please refer to the Privacy Notice that applies to your authentication method for more information about what data is collected and how this data is used.
You can disable Usage Statistics for any account type by following the instructions in the Usage Statistics Configuration documentation.
βββ troubleshooting.md Content:
Troubleshooting guide
This guide provides solutions to common issues and debugging tips, including topics on:
- Authentication or login errors
- Frequently asked questions (FAQs)
- Debugging tips
- Existing GitHub Issues similar to yours or creating new Issues
Authentication or login errors
- Error:
Failed to login. Message: Request contains an invalid argument - Users with Google Workspace accounts or Google Cloud accounts associated with their Gmail accounts may not be able to activate the free tier of the Google Code Assist plan.
- For Google Cloud accounts, you can work around this by setting
GOOGLE_CLOUD_PROJECTto your project ID. - Alternatively, you can obtain the Gemini API key from Google AI Studio, which also includes a separate free tier.
Frequently asked questions (FAQs)
- Q: How do I update Gemini CLI to the latest version?
-
A: If you installed it globally via
npm, update it using the commandnpm install -g @google/gemini-cli@latest. If you compiled it from source, pull the latest changes from the repository, and then rebuild using the commandnpm run build. -
Q: Where are the Gemini CLI configuration or settings files stored?
-
A: The Gemini CLI configuration is stored in two
settings.jsonfiles:- In your home directory:
~/.gemini/settings.json. - In your project's root directory:
./.gemini/settings.json.
Refer to Gemini CLI Configuration for more details.
- In your home directory:
-
Q: Why don't I see cached token counts in my stats output?
- A: Cached token information is only displayed when cached tokens are being used. This feature is available for API key users (Gemini API key or Google Cloud Vertex AI) but not for OAuth users (such as Google Personal/Enterprise accounts like Google Gmail or Google Workspace, respectively). This is because the Gemini Code Assist API does not support cached content creation. You can still view your total token usage using the
/statscommand in Gemini CLI.
Common error messages and solutions
- Error:
EADDRINUSE(Address already in use) when starting an MCP server. - Cause: Another process is already using the port that the MCP server is trying to bind to.
-
Solution: Either stop the other process that is using the port or configure the MCP server to use a different port.
-
Error: Command not found (when attempting to run Gemini CLI with
gemini). - Cause: Gemini CLI is not correctly installed or it is not in your system's
PATH. -
Solution: The update depends on how you installed Gemini CLI:
- If you installed
geminiglobally, check that yournpmglobal binary directory is in yourPATH. You can update Gemini CLI using the commandnpm install -g @google/gemini-cli@latest. - If you are running
geminifrom source, ensure you are using the correct command to invoke it (e.g.,node packages/cli/dist/index.js ...). To update Gemini CLI, pull the latest changes from the repository, and then rebuild using the commandnpm run build.
- If you installed
-
Error:
MODULE_NOT_FOUNDor import errors. - Cause: Dependencies are not installed correctly, or the project hasn't been built.
-
Solution:
- Run
npm installto ensure all dependencies are present. - Run
npm run buildto compile the project. - Verify that the build completed successfully with
npm run start.
- Run
-
Error: "Operation not permitted", "Permission denied", or similar.
- Cause: When sandboxing is enabled, Gemini CLI may attempt operations that are restricted by your sandbox configuration, such as writing outside the project directory or system temp directory.
-
Solution: Refer to the Configuration: Sandboxing documentation for more information, including how to customize your sandbox configuration.
-
Gemini CLI is not running in interactive mode in "CI" environments
- Issue: The Gemini CLI does not enter interactive mode (no prompt appears) if an environment variable starting with
CI_(e.g.,CI_TOKEN) is set. This is because theis-in-cipackage, used by the underlying UI framework, detects these variables and assumes a non-interactive CI environment. - Cause: The
is-in-cipackage checks for the presence ofCI,CONTINUOUS_INTEGRATION, or any environment variable with aCI_prefix. When any of these are found, it signals that the environment is non-interactive, which prevents the Gemini CLI from starting in its interactive mode. -
Solution: If the
CI_prefixed variable is not needed for the CLI to function, you can temporarily unset it for the command. e.g.,env -u CI_TOKEN gemini -
DEBUG mode not working from project .env file
- Issue: Setting
DEBUG=truein a project's.envfile doesn't enable debug mode for gemini-cli. - Cause: The
DEBUGandDEBUG_MODEvariables are automatically excluded from project.envfiles to prevent interference with gemini-cli behavior. - Solution: Use a
.gemini/.envfile instead, or configure theexcludedProjectEnvVarssetting in yoursettings.jsonto exclude fewer variables.
Debugging Tips
- CLI debugging:
- Use the
--verboseflag (if available) with CLI commands for more detailed output. -
Check the CLI logs, often found in a user-specific configuration or cache directory.
-
Core debugging:
- Check the server console output for error messages or stack traces.
- Increase log verbosity if configurable.
-
Use Node.js debugging tools (e.g.,
node --inspect) if you need to step through server-side code. -
Tool issues:
- If a specific tool is failing, try to isolate the issue by running the simplest possible version of the command or operation the tool performs.
- For
run_shell_command, check that the command works directly in your shell first. -
For file system tools, verify that paths are correct and check the permissions.
-
Pre-flight checks:
- Always run
npm run preflightbefore committing code. This can catch many common issues related to formatting, linting, and type errors.
Existing GitHub Issues similar to yours or creating new Issues
If you encounter an issue that was not covered here in this Troubleshooting guide, consider searching the Gemini CLI Issue tracker on GitHub. If you can't find an issue similar to yours, consider creating a new GitHub Issue with a detailed description. Pull requests are also welcome!