### Install Gemini CLI using npm Source: https://geminicli.com/docs/get-started Installs the Gemini CLI globally using npm. This is the standard method for setting up the tool. Ensure you have Node.js and npm installed. ```bash npm install -g @google/gemini-cli ``` -------------------------------- ### Start Gemini CLI Source: https://geminicli.com/docs/resources/troubleshooting Verifies that the project has been built successfully and the Gemini CLI can be started. Use this command after installing dependencies and building the project. ```bash npm run start ``` -------------------------------- ### Run Gemini CLI after installation Source: https://geminicli.com/docs/get-started Executes the Gemini CLI from the command line after it has been installed. This command initiates the CLI, allowing you to interact with it. ```bash gemini ``` -------------------------------- ### Install Project Dependencies Source: https://geminicli.com/docs/contributing Installs all project dependencies, including those defined in the root package.json and individual package dependencies. Requires Node.js and npm to be installed. ```bash npm install ``` -------------------------------- ### Ask User Tool: Text Input Question Example Source: https://geminicli.com/docs/tools/ask-user.md Illustrates the configuration for a text input question using the ask_user tool. This setup includes the question text, a header, the 'text' type, and an optional placeholder for user guidance. ```json { "questions": [ { "header": "Project Name", "question": "What is the name of your new project?", "type": "text", "placeholder": "e.g., my-awesome-app" } ] } ``` -------------------------------- ### Example TOML Policy Rule (Ask User for Git Commands) Source: https://geminicli.com/docs/reference/policy-engine.md This TOML policy rule prompts the user for confirmation before executing any command starting with 'git '. It demonstrates how to use a command prefix for broader matching and set the decision to 'ask_user'. ```toml [[rule]] toolName = "run_shell_command" commandPrefix = "git " decision = "ask_user" priority = 100 ``` -------------------------------- ### Create Skill Directory Structure (macOS/Linux) Source: https://geminicli.com/docs/cli/tutorials/skills-getting-started Creates the necessary directory structure for a new Gemini CLI skill on macOS and Linux systems. This includes the main skill directory and a subdirectory for scripts. ```bash mkdir -p .gemini/skills/api-auditor/scripts ``` -------------------------------- ### Start Genkit Telemetry Server Source: https://geminicli.com/docs/local-development Starts the Genkit telemetry server for viewing traces and other telemetry data in the Genkit Developer UI. This command is run in the terminal. ```bash npm run telemetry -- --target=genkit ``` -------------------------------- ### Example Gemini CLI settings.json Configuration Source: https://geminicli.com/docs/reference/configuration.md A comprehensive example of a `settings.json` file for Gemini CLI, demonstrating various configuration sections including general settings, UI preferences, tool configurations, MCP server connections, telemetry, privacy, model settings, context management, and advanced options. ```json { "general": { "vimMode": true, "preferredEditor": "code", "sessionRetention": { "enabled": true, "maxAge": "30d", "maxCount": 100 } }, "ui": { "theme": "GitHub", "hideBanner": true, "hideTips": false, "customWittyPhrases": [ "You forget a thousand things every day. Make sure this is one of ’em", "Connecting to AGI" ] }, "tools": { "sandbox": "docker", "discoveryCommand": "bin/get_tools", "callCommand": "bin/call_tool", "exclude": ["write_file"] }, "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 }, "privacy": { "usageStatisticsEnabled": true }, "model": { "name": "gemini-1.5-pro-latest", "maxSessionTurns": 10, "summarizeToolOutput": { "run_shell_command": { "tokenBudget": 100 } } }, "context": { "fileName": ["CONTEXT.md", "GEMINI.md"], "includeDirectories": ["path/to/dir1", "~/path/to/dir2", "../path/to/dir3"], "loadFromIncludeDirectories": true, "fileFiltering": { "respectGitIgnore": false } }, "advanced": { "excludedEnvVars": ["DEBUG", "DEBUG_MODE", "NODE_ENV"] } } ``` -------------------------------- ### Install Preview Gemini CLI with npm Source: https://geminicli.com/docs/get-started/installation Installs the weekly preview release of Gemini CLI globally using npm. This version may contain regressions and is recommended for testing new features. ```bash npm install -g @google/gemini-cli@preview ``` -------------------------------- ### Install Extension Dependencies Source: https://geminicli.com/docs/extensions/writing-extensions Installs the necessary Node.js dependencies for a Gemini CLI extension using npm. This command should be run within the extension's root directory. ```bash cd my-first-extension npm install ``` -------------------------------- ### Create Skill Directory Structure (Windows PowerShell) Source: https://geminicli.com/docs/cli/tutorials/skills-getting-started Creates the necessary directory structure for a new Gemini CLI skill on Windows using PowerShell. This includes the main skill directory and a subdirectory for scripts. ```powershell New-Item -ItemType Directory -Force -Path ".gemini\skills\api-auditor\scripts" ``` -------------------------------- ### Creating a .env file for Gemini CLI Source: https://geminicli.com/docs/reference/configuration.md Provides an example of a `.env` file used by the Gemini CLI to load environment variables. This file should be placed in the project's root directory or a parent directory. ```dotenv GEMINI_API_KEY=YOUR_GEMINI_API_KEY GEMINI_MODEL=gemini-1.5-pro-preview-0409 GOOGLE_API_KEY=YOUR_GOOGLE_API_KEY GOOGLE_CLOUD_PROJECT=your-gcp-project-id GEMINI_CLI_HOME=/path/to/custom/gemini/home GEMINI_TELEMETRY_ENABLED=true ``` -------------------------------- ### Example GEMINI.md with Imports Source: https://geminicli.com/docs/cli/gemini-md Demonstrates how to modularize GEMINI.md content by importing from other markdown files using the @file.md syntax. Supports relative and absolute paths. ```markdown # Main GEMINI.md file This is the main content. @./components/instructions.md More content here. @../shared/style-guide.md ``` -------------------------------- ### Installing Gemini CLI Extensions via Git Source: https://geminicli.com/docs/extensions/best-practices Bash commands to install Gemini CLI extensions directly from a Git repository, showing how to install the stable version and a development version. ```bash # Install the stable version (default branch) gemini extensions install github.com/user/repo # Install the development version gemini extensions install github.com/user/repo --ref dev ``` -------------------------------- ### API Auditor Tool Logic (audit.js) Source: https://geminicli.com/docs/cli/tutorials/skills-getting-started Provides the JavaScript code for the 'audit.js' utility, which is bundled with the 'api-auditor' skill. This script takes a URL as a command-line argument, attempts to fetch it using a HEAD request, and logs the success or failure status. ```javascript // .gemini/skills/api-auditor/scripts/audit.js const url = process.argv[2]; if (!url) { console.error('Usage: node audit.js '); process.exit(1); } console.log(`Auditing ${url}...`); fetch(url, { method: 'HEAD' }) .then((r) => console.log(`Result: Success (Status ${r.status})`)) .catch((e) => console.error(`Result: Failed (${e.message})`)); ``` -------------------------------- ### Example GEMINI.md for TypeScript Project Source: https://geminicli.com/docs/cli/gemini-md An example of a GEMINI.md file that provides general instructions and coding style guidelines for a TypeScript project. It specifies indentation, interface naming conventions, and equality checks. ```markdown # Project: My TypeScript Library ## General Instructions - When you generate new TypeScript code, follow the existing coding style. - Ensure all new functions and classes have JSDoc comments. - Prefer functional programming paradigms where appropriate. ## Coding Style - Use 2 spaces for indentation. - Prefix interface names with `I` (for example, `IUserService`). - Always use strict equality (`===` and `!==`). ``` -------------------------------- ### Start Local Telemetry Export with npm Script Source: https://geminicli.com/docs/cli/telemetry This bash command initiates the local telemetry export process using an npm script. It downloads and starts necessary tools like Jaeger and an OTEL collector, configures the workspace, and provides UI access for viewing traces. ```bash npm run telemetry -- --target=local ``` -------------------------------- ### Ask User Tool: Yes/No Question Example Source: https://geminicli.com/docs/tools/ask-user.md Shows how to set up a Yes/No confirmation question using the ask_user tool. This configuration specifies the question text, a header, and the 'yesno' type for a simple binary user response. ```json { "questions": [ { "header": "Deploy", "question": "Do you want to deploy the application now?", "type": "yesno" } ] } ``` -------------------------------- ### Install Gemini CLI IDE Companion Extension Source: https://geminicli.com/docs/ide-integration Manually install the Gemini CLI IDE companion extension using the command line. This command automatically detects and installs the correct extension for your IDE. ```bash /ide install ``` -------------------------------- ### Check Gemini CLI token usage and quota Source: https://geminicli.com/docs/get-started Displays current token usage and quota information for supported models within the Gemini CLI. This command is useful for monitoring resource consumption. ```bash /stats model ``` -------------------------------- ### Run Telemetry Automation Script (npm) Source: https://geminicli.com/docs/cli/telemetry Executes an npm script to start a local OpenTelemetry collector for forwarding telemetry data to Google Cloud. This script also configures the workspace and provides links to view telemetry data. ```bash npm run telemetry -- --target=gcp ``` -------------------------------- ### Manual Build and Publish for Gemini CLI Source: https://geminicli.com/docs/contributing Perform a manual build and publish of the Gemini CLI artifact to the internal registry. This process involves cleaning the project, installing dependencies, authenticating, running a pre-release build, and then publishing all workspaces. ```bash npm run clean npm install npm run auth npm run prerelease:dev npm publish --workspaces ``` -------------------------------- ### Example SKILL.md structure for Gemini CLI skills Source: https://geminicli.com/docs/cli/creating-skills Demonstrates the recommended folder structure for organizing a Gemini CLI skill. This includes the required SKILL.md file and optional directories for scripts, references, and assets. ```text my-skill/ ├── SKILL.md (Required) Instructions and metadata ├── scripts/ (Optional) Executable scripts ├── references/ (Optional) Static documentation └── assets/ (Optional) Templates and other resources ``` -------------------------------- ### Relative Path Import Examples in Markdown Source: https://geminicli.com/docs/reference/memport Illustrates various ways to use relative paths for importing files within a GEMINI.md project. This includes importing from the same directory, parent directory, and subdirectories. ```markdown # My GEMINI.md Welcome to my project! @./get-started.md ## Features @./features/overview.md ``` -------------------------------- ### Install and Run React DevTools (Bash) Source: https://geminicli.com/docs/contributing Installs and runs React DevTools version 6 globally, which is compatible with the CLI's React version. This tool allows for inspection and debugging of the CLI's React-based UI components. ```bash npm install -g react-devtools@6 react-devtools ``` -------------------------------- ### Install an Extension Source: https://geminicli.com/docs/extensions/reference Installs a Gemini CLI extension from a GitHub repository URL or a local file path. Supports specifying a git ref, enabling auto-updates, installing pre-release versions, and bypassing confirmation prompts. ```APIDOC ## Install an Extension ### Description Installs a Gemini CLI extension from a GitHub repository URL or a local file path. Supports specifying a git ref, enabling auto-updates, installing pre-release versions, and bypassing confirmation prompts. ### Method `gemini extensions install` ### Endpoint N/A (CLI command) ### Parameters #### Command Arguments - **``** (string) - Required - The GitHub URL or local path of the extension. - **`--ref`** (string) - Optional - The git ref (branch, tag, or commit) to install. - **`--auto-update`** (boolean) - Optional - Enable automatic updates for this extension. - **`--pre-release`** (boolean) - Optional - Enable installation of pre-release versions. - **`--consent`** (boolean) - Optional - Acknowledge security risks and skip the confirmation prompt. ### Request Example ```bash gemini extensions install https://github.com/example/my-extension --ref main --auto-update ``` ### Response N/A (CLI command output) ``` -------------------------------- ### Install Monday.com Extension for Gemini CLI Source: https://geminicli.com/docs/changelogs This command installs the Monday.com extension for the Gemini CLI, enabling analysis of sprints and management of task boards. Prerequisites include a working Gemini CLI installation. ```bash gemini extensions install https://github.com/mondaycom/mcp ``` -------------------------------- ### findProjectRoot Source: https://geminicli.com/docs/reference/memport Asynchronously finds the project root directory by searching for a '.git' directory upwards from a specified start directory. ```APIDOC ## `findProjectRoot(startDir)` ### Description 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 #### Path Parameters - **startDir** (string) - Required - The directory to start searching from ### Returns - **Promise<string>** - The project root directory (or the start directory if no `.git` is found) ``` -------------------------------- ### Node.js Initialization Script (init.js) Source: https://geminicli.com/docs/hooks/writing-hooks This Node.js script is designed to run during the `SessionStart` hook. It performs initial setup tasks for the assistant, such as initializing a database or other necessary resources. The script logs a message to stderr indicating initialization and outputs a JSON object to stdout containing a system message for the assistant. ```javascript #!/usr/bin/env node // Initialize DB or resources console.error('Initializing assistant...'); // Output to user console.log( JSON.stringify({ systemMessage: '🧠 Smart Assistant Loaded', }), ); ``` -------------------------------- ### Example System settings.json Configuration Source: https://geminicli.com/docs/cli/enterprise A comprehensive example of a system `settings.json` file that combines multiple configurations for a secure and controlled Gemini CLI environment. It includes sandbox settings, tool allowlists, MCP server definitions, telemetry configuration, bug command redirection, and usage statistics control. ```json { "tools": { "sandbox": "docker", "core": [ "ReadFileTool", "GlobTool", "ShellTool(ls)", "ShellTool(cat)", "ShellTool(grep)" ] }, "mcp": { "allowed": ["corp-tools"] }, "mcpServers": { "corp-tools": { "command": "/opt/gemini-tools/start.sh", "timeout": 5000 } }, "telemetry": { "enabled": true, "target": "gcp", "otlpEndpoint": "https://telemetry-prod.example.com:4317", "logPrompts": false }, "advanced": { "bugCommand": { "urlTemplate": "https://servicedesk.example.com/new-ticket?title={title}&details={info}" } }, "privacy": { "usageStatisticsEnabled": false } } ``` -------------------------------- ### Install Latest Stable Gemini CLI with npm Source: https://geminicli.com/docs/get-started/installation Installs the latest stable release of Gemini CLI globally using npm. The '@latest' tag is optional as it's the default behavior. ```bash # Both commands install the latest stable release. npm install -g @google/gemini-cli npm install -g @google/gemini-cli@latest ``` -------------------------------- ### Define API Auditor Skill (SKILL.md) Source: https://geminicli.com/docs/cli/tutorials/skills-getting-started Defines the 'api-auditor' skill for Gemini CLI. It specifies when the skill should be used based on user queries and provides instructions for the agent on how to behave when the skill is active, including using a bundled script. ```markdown --- name: api-auditor description: Expertise in auditing and testing API endpoints. Use when the user asks to "check", "test", or "audit" a URL or API. --- # API Auditor Instructions You act as a QA engineer specialized in API reliability. When this skill is active, you MUST: 1. **Audit**: Use the bundled `scripts/audit.js` utility to check the status of the provided URL. 2. **Report**: Analyze the output (status codes, latency) and explain any failures in plain English. 3. **Secure**: Remind the user if they are testing a sensitive endpoint without an `https://` protocol. ``` -------------------------------- ### Run Gemini CLI from Source Source: https://geminicli.com/docs/contributing Starts the Gemini CLI directly from the source code after it has been built. This command is used for testing and development purposes. Requires Node.js and a successful build. ```bash npm start ``` -------------------------------- ### Run Gemini CLI from Source (Linked Package) Source: https://geminicli.com/docs/get-started/installation Simulates a global installation of a locally built Gemini CLI package by linking it to the global node_modules. Useful for testing local changes in a production-like workflow. Requires Node.js and npm. ```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 ``` -------------------------------- ### Absolute Path Import Example in Markdown Source: https://geminicli.com/docs/reference/memport Shows how to import content using an absolute path in GEMINI.md files. This provides a way to reference files regardless of the current file's location. ```markdown # Main GEMINI.md file This is the main content. @/absolute/path/to/file.md More content here. ``` -------------------------------- ### Install Gemini CLI with Homebrew Source: https://geminicli.com/docs/get-started/installation Installs the Gemini CLI globally using Homebrew, a popular package manager for macOS and Linux. This command requires Homebrew to be installed. ```bash brew install gemini-cli ``` -------------------------------- ### Install Gemini CLI Extension Source: https://geminicli.com/docs/extensions/reference Installs a Gemini CLI extension from a GitHub repository URL or a local file path. Requires `git` to be installed for GitHub sources. Updates take effect after restarting the CLI session. Options include specifying a git ref, enabling auto-updates, installing pre-release versions, and bypassing confirmation prompts. ```bash gemini extensions install [--ref ] [--auto-update] [--pre-release] [--consent] ``` -------------------------------- ### Create User-Wide .env File for Gemini CLI (macOS/Linux) Source: https://geminicli.com/docs/get-started/authentication Creates a ~/.gemini/.env file and adds the GOOGLE_CLOUD_PROJECT variable to it. Gemini CLI automatically loads variables from this file, providing a way to manage settings across sessions. ```bash mkdir -p ~/.gemini cat >> ~/.gemini/.env <<'EOF' GOOGLE_CLOUD_PROJECT="your-project-id" # Add other variables like GEMINI_API_KEY as needed EOF ``` -------------------------------- ### Clone Gemini CLI Repository Source: https://geminicli.com/docs/contributing Clones the Gemini CLI repository from GitHub. This is the first step to setting up your local development environment. It requires Git to be installed. ```bash git clone https://github.com/google-gemini/gemini-cli.git # Or your fork's URL cd gemini-cli ``` -------------------------------- ### Run Gemini CLI from Source Source: https://geminicli.com/docs/resources/troubleshooting When running Gemini CLI directly from source, use this command to invoke the CLI. This is useful for development or when a global installation is not desired. ```bash node packages/cli/dist/index.js ... ``` -------------------------------- ### Install Gemini CLI with MacPorts Source: https://geminicli.com/docs/get-started/installation Installs the Gemini CLI globally using MacPorts, another package manager for macOS. This command requires MacPorts to be installed and may require sudo privileges. ```bash sudo port install gemini-cli ``` -------------------------------- ### Ask User Tool: Multiple Choice Question Example Source: https://geminicli.com/docs/tools/ask-user.md Demonstrates how to configure the ask_user tool to present a multiple-choice question to the user. This includes defining the question, header, type, and selectable options with labels and descriptions. ```json { "questions": [ { "header": "Database", "question": "Which database would you like to use?", "type": "choice", "options": [ { "label": "PostgreSQL", "description": "Powerful, open source object-relational database system." }, { "label": "SQLite", "description": "C-library that implements a SQL database engine." } ] } ] } ``` -------------------------------- ### Install Nightly Gemini CLI with npm Source: https://geminicli.com/docs/get-started/installation Installs the daily nightly release of Gemini CLI globally using npm. This version includes the latest changes from the main branch and should be assumed to have pending validations and issues. ```bash npm install -g @google/gemini-cli@nightly ``` -------------------------------- ### Start Gemini CLI in Development Mode (Bash) Source: https://geminicli.com/docs/contributing Starts the Gemini CLI in development mode, typically enabling features for easier development and debugging, such as hot-reloading or enhanced logging. This is often used in conjunction with React DevTools. ```bash DEV=true npm start ``` -------------------------------- ### Run Gemini CLI Instantly with npx Source: https://geminicli.com/docs/get-started/installation Executes the Gemini CLI without permanent installation using npx. This is useful for trying out the CLI or running specific versions. ```bash # Using npx (no installation required) npx @google/gemini-cli ``` -------------------------------- ### Install a Gemini CLI Extension from GitHub Source: https://geminicli.com/docs/extensions Install a new Gemini CLI extension by providing the GitHub repository URL. This command adds new capabilities to your Gemini CLI. ```bash gemini extensions install https://github.com/gemini-cli-extensions/workspace ``` -------------------------------- ### List Installed Extensions Source: https://geminicli.com/docs/extensions/reference Views a list of all installed Gemini CLI extensions. ```APIDOC ## List Installed Extensions ### Description Views a list of all installed Gemini CLI extensions. ### Method `gemini extensions list` ### Endpoint N/A (CLI command) ### Parameters N/A ### Request Example ```bash gemini extensions list ``` ### Response N/A (CLI command output) ``` -------------------------------- ### Install Gemini CLI with Anaconda Source: https://geminicli.com/docs/get-started/installation Installs Gemini CLI within a dedicated Conda environment, suitable for restricted environments. It first creates and activates an environment with Node.js, then installs the CLI via npm. ```bash # Create and activate a new environment conda create -y -n gemini_env -c conda-forge nodejs conda activate gemini_env # Install Gemini CLI globally via npm (inside the environment) npm install -g @google/gemini-cli ``` -------------------------------- ### Create User-Wide .env File for Gemini CLI (Windows PowerShell) Source: https://geminicli.com/docs/get-started/authentication Creates a .gemini/.env file in the user's profile directory and adds the GOOGLE_CLOUD_PROJECT variable to it. Gemini CLI automatically loads variables from this file, providing a way to manage settings across sessions. ```powershell New-Item -ItemType Directory -Force -Path "$env:USERPROFILE\.gemini" @" GOOGLE_CLOUD_PROJECT="your-project-id" # Add other variables like GEMINI_API_KEY as needed "@ | Out-File -FilePath "$env:USERPROFILE\.gemini\.env" -Encoding utf8 -Append ``` -------------------------------- ### Install Hugging Face Extension for Gemini CLI Source: https://geminicli.com/docs/changelogs This command installs the Hugging Face extension for the Gemini CLI, allowing access to the Hugging Face hub. Ensure you have the Gemini CLI installed and configured. ```bash gemini extensions install https://github.com/huggingface/hf-mcp-server ``` -------------------------------- ### Install Data Commons Extension for Gemini CLI Source: https://geminicli.com/docs/changelogs This command installs the Data Commons extension for the Gemini CLI, facilitating queries on public datasets and grounding responses with Data Commons information. The Gemini CLI must be installed. ```bash gemini extensions install https://github.com/gemini-cli-extensions/datacommons ``` -------------------------------- ### Configuring MCP Server in settings.json Source: https://geminicli.com/docs/tools/mcp-server.md Example of how to include an MCP server configuration in the `settings.json` file. This specifies the command to run the server and its arguments. ```json { "mcpServers": { "nodeServer": { "command": "node", "args": ["filename.ts"] } } } ``` -------------------------------- ### Install Extension from Git Repository Source: https://geminicli.com/docs/extensions/releasing Installs a Gemini CLI extension directly from a Git repository URL. Users can specify a particular branch, tag, or commit using the --ref argument for version control. ```bash gemini extensions install gemini extensions install --ref=stable ``` -------------------------------- ### Install Latest Gemini CLI Source: https://geminicli.com/docs/get-started/gemini-3 This command upgrades the Gemini CLI to the latest version using npm. Ensure you have Node.js and npm installed. ```bash npm install -g @google/gemini-cli@latest ``` -------------------------------- ### Run Gemini CLI with Sandbox Flag Source: https://geminicli.com/docs/get-started/installation Instructs a locally installed Gemini CLI to run inside a sandbox container. This enhances security and isolation for potentially impactful commands. Requires a local installation of Gemini CLI. ```bash gemini --sandbox -y -p "your prompt here" ``` -------------------------------- ### Configure Container Sandboxing with Gemini CLI Source: https://geminicli.com/docs/contributing Enable container-based sandboxing for enhanced security on macOS and other platforms by setting the GEMINI_SANDBOX environment variable. This variable can be set to 'true' (which defaults to Docker or Podman) or a specific command for the container runtime. The specified command must be installed on the host. This feature builds a minimal container image for building and running the CLI, with initial build times around 20-30 seconds. ```bash export GEMINI_SANDBOX=true # or export GEMINI_SANDBOX=docker # or export GEMINI_SANDBOX=podman # or export GEMINI_SANDBOX= ``` -------------------------------- ### Run Gemini CLI from GitHub with npx Source: https://geminicli.com/docs/get-started/installation Executes the Gemini CLI directly from the main branch on GitHub using npx. This is helpful for testing features that are still in development. ```bash npx https://github.com/google-gemini/gemini-cli ``` -------------------------------- ### Set Vertex AI Environment Variables (macOS/Linux) Source: https://geminicli.com/docs/get-started/authentication Sets the GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION environment variables for Vertex AI on macOS or Linux. Replace placeholders with your actual project ID and desired location. ```bash # Replace with your project ID and desired location (e.g., us-central1) export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID" export GOOGLE_CLOUD_LOCATION="YOUR_PROJECT_LOCATION" ``` -------------------------------- ### Restricting Powerful Tools in `gemini-extension.json` Source: https://geminicli.com/docs/extensions/best-practices Example of `gemini-extension.json` configuration to exclude dangerous tools like `run_shell_command` with specific arguments, enhancing security. ```json { "name": "my-safe-extension", "excludeTools": ["run_shell_command(rm -rf *)"] } ``` -------------------------------- ### SKILL.md YAML frontmatter and Markdown for Gemini CLI skills Source: https://geminicli.com/docs/cli/creating-skills Illustrates the 'SKILL.md' file format, which uses YAML frontmatter for metadata like 'name' and 'description', followed by Markdown content to guide the agent's behavior. ```markdown --- name: code-reviewer description: Use this skill to review code. It supports both local changes and remote Pull Requests. --- # Code Reviewer This skill guides the agent in conducting thorough code reviews. ## Workflow ### 1. Determine Review Target - **Remote PR**: If the user gives a PR number or URL, target that remote PR. - **Local Changes**: If changes are local... ... ``` -------------------------------- ### Create Skill Directory Structure Source: https://geminicli.com/docs/extensions/writing-extensions Demonstrates how to create a directory structure for a new agent skill. This involves creating a 'skills' directory and a subdirectory for the specific skill, such as 'security-audit'. ```bash mkdir -p skills/security-audit ``` ```powershell New-Item -ItemType Directory -Force -Path "skills\security-audit" ``` -------------------------------- ### Gemini CLI Merged Configuration Example (JSON) Source: https://geminicli.com/docs/cli/enterprise Illustrates the final merged configuration of Gemini CLI settings, demonstrating how system defaults, user settings, workspace settings, and system overrides are combined based on their precedence and merging rules for single-value and array/object settings. ```json { "ui": { "theme": "system-enforced-theme" }, "mcpServers": { "corp-server": { "command": "/usr/local/bin/corp-server-prod" }, "user-tool": { "command": "npm start --prefix ~/tools/my-tool" }, "project-tool": { "command": "npm start" } }, "context": { "includeDirectories": [ "/etc/gemini-cli/common-context", "~/gemini-context", "./project-context", "/etc/gemini-cli/global-context" ] } } ``` -------------------------------- ### Find Project Root Asynchronously Source: https://geminicli.com/docs/reference/memport Asynchronously finds the project root by searching for a '.git' directory upwards from a given start directory. This non-blocking implementation prevents the Node.js event loop from being stalled during the search. ```typescript async findProjectRoot(startDir) ``` -------------------------------- ### Link Gemini CLI Locally Source: https://geminicli.com/docs/contributing Creates a symbolic link for the Gemini CLI package, allowing you to run it globally as if it were installed. This is useful for testing local changes. Requires npm. ```bash npm link path/to/gemini-cli/packages/cli ``` -------------------------------- ### Example TOML Policy Rule (Allow Git Status) Source: https://geminicli.com/docs/reference/policy-engine.md A sample TOML policy rule that automatically allows the execution of the 'git status' command. This rule specifies the tool name, a command prefix to match, the decision to allow, and a priority. ```toml [[rule]] toolName = "run_shell_command" commandPrefix = "git status" decision = "allow" priority = 100 ``` -------------------------------- ### Gemini Extension Manifest Configuration Source: https://geminicli.com/docs/extensions/writing-extensions Defines the metadata and configuration for a Gemini CLI extension. It specifies the extension's name, version, and MCP server details, including how to start the server process. ```json { "name": "mcp-server-example", "version": "1.0.0", "mcpServers": { "nodeServer": { "command": "node", "args": ["${extensionPath}${/}example.js"], "cwd": "${extensionPath}" } } } ``` -------------------------------- ### Configure Proxied Networking for Gemini CLI Sandbox Source: https://geminicli.com/docs/contributing Restrict outbound network traffic within the Gemini CLI sandbox by specifying a proxy command. Set the `GEMINI_SANDBOX_PROXY_COMMAND` environment variable to a command that starts a proxy server listening on `:::8877`. This proxy will automatically start and stop with the sandbox, managing relevant network requests. ```bash export GEMINI_SANDBOX_PROXY_COMMAND="" # Example proxy script (docs/examples/proxy-script.md): # curl https://example.com ``` -------------------------------- ### Environment Variable Expansion Example in settings.json Source: https://geminicli.com/docs/tools/mcp-server.md Illustrates how environment variables can be expanded within the `env` block of an MCP server configuration. It shows support for POSIX/Bash (`$VAR_NAME`, `${VAR_NAME}`) and Windows (`%VAR_NAME%`) syntax. ```json "env": { "API_KEY": "$MY_EXTERNAL_TOKEN", "LOG_LEVEL": "$LOG_LEVEL", "TEMP_DIR": "%TEMP%" } ``` -------------------------------- ### Set Google Cloud API Key (macOS/Linux) Source: https://geminicli.com/docs/get-started/authentication Sets the GOOGLE_API_KEY environment variable with a Vertex AI API key on macOS or Linux. This method is suitable for certain Vertex AI services but may be restricted by organization policies. ```bash # Replace YOUR_GOOGLE_API_KEY with your Vertex AI API key export GOOGLE_API_KEY="YOUR_GOOGLE_API_KEY" ``` -------------------------------- ### Run React DevTools with npx (Bash) Source: https://geminicli.com/docs/contributing Executes React DevTools version 6 directly using npx without a global installation. This is a convenient way to run the debugging tool for the CLI's React UI. ```bash npx react-devtools@6 ``` -------------------------------- ### Set Service Account Credentials (macOS/Linux) Source: https://geminicli.com/docs/get-started/authentication Sets the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a service account JSON key file on macOS or Linux. This enables authentication using a service account for Vertex AI. ```bash # Replace /path/to/your/keyfile.json with the actual path export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/keyfile.json" ``` -------------------------------- ### Set Vertex AI Environment Variables (Windows PowerShell) Source: https://geminicli.com/docs/get-started/authentication Sets the GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION environment variables for Vertex AI on Windows using PowerShell. Replace placeholders with your actual project ID and desired location. ```powershell # Replace with your project ID and desired location (e.g., us-central1) $env:GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID" $env:GOOGLE_CLOUD_LOCATION="YOUR_PROJECT_LOCATION" ``` -------------------------------- ### Invoking MCP Prompts via Bash Source: https://geminicli.com/docs/tools/mcp-server.md Examples of how to invoke a registered MCP prompt ('poem-writer') using slash commands in the Gemini CLI. Demonstrates both named and positional argument syntax. ```bash # Using named arguments /poem-writer --title="Gemini CLI" --mood="reverent" # Using positional arguments /poem-writer "Gemini CLI" reverent ``` -------------------------------- ### Example Custom Theme JSON Structure Source: https://geminicli.com/docs/cli/themes Defines the structure for a custom theme JSON file. This file specifies colors for various UI elements like background, text, borders, and status indicators. ```json { "name": "Gruvbox Dark", "type": "custom", "background": { "primary": "#282828", "diff": { "added": "#2b3312", "removed": "#341212" } }, "text": { "primary": "#ebdbb2", "secondary": "#a89984", "link": "#83a598", "accent": "#d3869b" }, "border": { "default": "#3c3836", "focused": "#458588" }, "status": { "success": "#b8bb26", "warning": "#fabd2f", "error": "#fb4934" }, "ui": { "comment": "#928374", "symbol": "#8ec07c", "gradient": ["#cc241d", "#d65d0e", "#d79921"] } } ``` -------------------------------- ### Circular Import Detection Example in Markdown Source: https://geminicli.com/docs/reference/memport Illustrates a scenario where circular imports are attempted between two GEMINI.md files. The processor is designed to detect and prevent such circular dependencies. ```markdown # file-a.md @./file-b.md ``` ```markdown # file-b.md @./file-a.md ``` -------------------------------- ### Build and Release Extension with GitHub Actions (YAML) Source: https://geminicli.com/docs/extensions/releasing This workflow automates the process of building and releasing an extension for multiple platforms (macOS, Linux, Windows). It checks out the code, sets up Node.js, installs dependencies, builds the extension, packages it for different architectures, and creates a GitHub release with the generated assets. It requires a GitHub repository with a Node.js project and a defined build script. ```yaml name: Release Extension on: push: tags: - 'v*' jobs: release: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Node.js uses: actions/setup-node@v3 with: node-version: '20' - name: Install dependencies run: npm ci - name: Build extension run: npm run build - name: Create release assets run: | npm run package -- --platform=darwin --arch=arm64 npm run package -- --platform=linux --arch=x64 npm run package -- --platform=win32 --arch=x64 - name: Create GitHub Release uses: softprops/action-gh-release@v1 with: files: | release/darwin.arm64.my-tool.tar.gz release/linux.arm64.my-tool.tar.gz release/win32.arm64.my-tool.zip ``` -------------------------------- ### Allow Specific Command Prefixes - JSON Configuration Source: https://geminicli.com/docs/tools/shell This JSON configuration restricts the `run_shell_command` tool to only execute commands starting with 'git' or 'npm'. Any other command will be blocked. This is useful for ensuring only intended operations are performed. ```json { "tools": { "core": ["run_shell_command(git)", "run_shell_command(npm)"] } } ``` -------------------------------- ### Allowlisting Tools with coreTools (JSON) Source: https://geminicli.com/docs/cli/enterprise An example JSON configuration for the Gemini CLI's tools.core setting, demonstrating an allowlist approach to restrict tool access to specific operations like reading files and listing directories. ```json { "tools": { "core": ["ReadFileTool", "GlobTool", "ShellTool(ls)"] } } ``` -------------------------------- ### Set Service Account Credentials (Windows PowerShell) Source: https://geminicli.com/docs/get-started/authentication Sets the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a service account JSON key file on Windows using PowerShell. This enables authentication using a service account for Vertex AI. ```powershell # Replace C:\path\to\your\keyfile.json with the actual path $env:GOOGLE_APPLICATION_CREDENTIALS="C:\path\to\your\keyfile.json" ``` -------------------------------- ### Set Google Cloud API Key (Windows PowerShell) Source: https://geminicli.com/docs/get-started/authentication Sets the GOOGLE_API_KEY environment variable with a Vertex AI API key on Windows using PowerShell. This method is suitable for certain Vertex AI services but may be restricted by organization policies. ```powershell # Replace YOUR_GOOGLE_API_KEY with your Vertex AI API key $env:GOOGLE_API_KEY="YOUR_GOOGLE_API_KEY" ``` -------------------------------- ### Gemini CLI Context File Loading Order Source: https://geminicli.com/docs/reference/configuration.md Illustrates the hierarchical loading order of context files in the Gemini CLI. Content from lower (more specific) files overrides or supplements content from higher (more general) files. The exact order can be inspected using the `/memory show` command. ```text 1. Global context file: ~/.gemini/ 2. Project root and ancestors context files: Searches from current directory up to project root. 3. Sub-directory context files: Scans subdirectories below the current working directory (limited by context.discoveryMaxDirs). ``` -------------------------------- ### Persist Google Cloud Project Variable in Shell Config (Windows PowerShell) Source: https://geminicli.com/docs/get-started/authentication Appends the environment variable setting for GOOGLE_CLOUD_PROJECT to the user's PowerShell profile and sources it. This persists the environment variable across PowerShell sessions on Windows. ```powershell Add-Content -Path $PROFILE -Value '$env:GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"' . $PROFILE ``` -------------------------------- ### Custom System Prompt with Variable Substitution (Markdown) Source: https://geminicli.com/docs/cli/system-prompt Example of a custom system prompt in Markdown format that utilizes built-in variables like ${AgentSkills}, ${SubAgents}, and ${AvailableTools} for dynamic content injection. ```markdown # Custom System Prompt You are a helpful assistant. ${AgentSkills} ${SubAgents} ## Tooling The following tools are available to you: ${AvailableTools} You can use ${write_file_ToolName} to save logs. ``` -------------------------------- ### Registering MCP Prompts with TypeScript SDK Source: https://geminicli.com/docs/tools/mcp-server.md Example of a stdio MCP server written in TypeScript that registers a prompt named 'poem-writer'. This prompt takes 'title' and optional 'mood' arguments and constructs a user message for a haiku. ```typescript 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); ``` -------------------------------- ### Gemini CLI Custom Command Definition (TOML) Source: https://geminicli.com/docs/extensions/writing-extensions Defines a custom command for Gemini CLI using TOML format. This example creates a `/fs:grep-code` command that takes a pattern argument, runs `grep` on the current directory, and summarizes the results. ```toml prompt = """ Please summarize the findings for the pattern `{{args}}`. Search Results: !{grep -r {{args}} .} """ ``` -------------------------------- ### Custom Gemini CLI Sandbox Dockerfile Source: https://geminicli.com/docs/reference/configuration.md Demonstrates how to create a custom Dockerfile for the Gemini CLI's sandboxed environment. This allows for project-specific dependencies and configurations by extending the base sandbox image. ```dockerfile 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 ``` -------------------------------- ### Run Gemini CLI from Source (Development Mode) Source: https://geminicli.com/docs/get-started/installation Runs the Gemini CLI directly from the source code in development mode, enabling hot-reloading. This is recommended for project contributors actively developing the CLI. Requires Node.js and npm. ```bash # From the root of the repository npm run start ``` -------------------------------- ### SessionStart Hook Source: https://geminicli.com/docs/hooks/reference Fires on application startup, resuming a session, or after a /clear command. Used for loading initial context. ```APIDOC ## SessionStart Hook ### Description Fires on application startup, resuming a session, or after a `/clear` command. Used for loading initial context. ### Method (Implicitly called by the Gemini CLI) ### Endpoint N/A (Internal Hook) ### Parameters #### Input fields - **source** (string) - Required - Can be `"startup"`, `"resume"`, or `"clear"`. #### Relevant output fields - **hookSpecificOutput.additionalContext** (string) - Optional - Injected as the first turn in history (interactive) or prepended to the user's prompt (non-interactive). - **systemMessage** (string) - Optional - Shown at the start of the session. ### Advisory only `continue` and `decision` fields are ignored. Startup is never blocked. ### Request Example ```json { "source": "startup" } ``` ### Response #### Success Response (Implicit) - **hookSpecificOutput.additionalContext** (string) - Additional context to load. - **systemMessage** (string) - A system message to display. #### Response Example ```json { "hookSpecificOutput": { "additionalContext": "Welcome! Let's start a new session." }, "systemMessage": "Session started." } ``` ``` -------------------------------- ### List Installed Gemini CLI Extensions Source: https://geminicli.com/docs/extensions View a list of installed Gemini CLI extensions and their status. This command can be run interactively or directly from the terminal. ```bash /extensions list ``` ```bash gemini extensions list ``` -------------------------------- ### Set Google Cloud Project Environment Variable (Windows PowerShell) Source: https://geminicli.com/docs/get-started/authentication Sets the GOOGLE_CLOUD_PROJECT environment variable for the current PowerShell session on Windows. Replace YOUR_PROJECT_ID with your actual Google Cloud project ID. This variable is used by Gemini CLI for authentication. ```powershell # Replace YOUR_PROJECT_ID with your actual Google Cloud project ID $env:GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID" ``` -------------------------------- ### Building Custom Gemini CLI Sandbox Image Source: https://geminicli.com/docs/reference/configuration.md Shows how to automatically build a custom sandbox image for the Gemini CLI when a project-specific Dockerfile is present. This is achieved by setting the BUILD_SANDBOX environment variable. ```bash BUILD_SANDBOX=1 gemini -s ``` -------------------------------- ### Persist Google Cloud Project Variable in Shell Config (macOS/Linux) Source: https://geminicli.com/docs/get-started/authentication Appends the export command for GOOGLE_CLOUD_PROJECT to the user's bashrc file and sources it to make the change effective immediately. This persists the environment variable across terminal sessions on macOS/Linux. ```bash echo 'export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"' >> ~/.bashrc source ~/.bashrc ``` -------------------------------- ### Uninstall Gemini CLI (MacPorts) Source: https://geminicli.com/docs/resources/uninstall Removes the Gemini CLI when it was installed globally using MacPorts. This command uses MacPorts' 'port uninstall' command for removal. Ensure MacPorts is installed and configured correctly. ```bash sudo port uninstall gemini-cli ``` -------------------------------- ### MCP Server Tool Registration (JavaScript) Source: https://geminicli.com/docs/extensions/writing-extensions Implements an MCP server using the Model Context Protocol SDK in JavaScript. It registers a 'fetch_posts' tool that fetches data from a public API and returns the first 5 posts. ```javascript /** * @license * Copyright 2025 Google LLC * SPDX-License-Identifier: Apache-2.0 */ 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', }); // Registers a new tool named 'fetch_posts' server.registerTool( 'fetch_posts', { description: 'Fetches a list of posts from a public API.', inputSchema: z.object({}).shape, }, async () => { const apiResponse = await fetch( 'https://jsonplaceholder.typicode.com/posts', ); const posts = await apiResponse.json(); const response = { posts: posts.slice(0, 5) }; return { content: [ { type: 'text', text: JSON.stringify(response), }, ], }; }, ); const transport = new StdioServerTransport(); await server.connect(transport); ``` -------------------------------- ### Set Google Cloud Project Environment Variable (macOS/Linux) Source: https://geminicli.com/docs/get-started/authentication Sets the GOOGLE_CLOUD_PROJECT environment variable for the current terminal session on macOS or Linux. Replace YOUR_PROJECT_ID with your actual Google Cloud project ID. This variable is used by Gemini CLI for authentication. ```bash # Replace YOUR_PROJECT_ID with your actual Google Cloud project ID export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID" ``` -------------------------------- ### Run Gemini CLI Sandbox from Docker Registry Source: https://geminicli.com/docs/get-started/installation Runs the Gemini CLI within a Docker container directly from the registry for security and isolation. This command requires Docker to be installed and running. ```bash # Run the published sandbox image docker run --rm -it us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.1.1 ``` -------------------------------- ### Build Gemini CLI and Sandbox Container Source: https://geminicli.com/docs/contributing Builds both the 'gemini' CLI utility and its associated sandbox container. This command is used when sandboxing is enabled and requires a sandboxing provider. Requires Node.js and npm. ```bash npm run build:all ``` -------------------------------- ### Uninstall Gemini CLI (Homebrew) Source: https://geminicli.com/docs/resources/uninstall Removes the Gemini CLI when it was installed globally using Homebrew. This command utilizes Homebrew's uninstall command to remove the package. Ensure Homebrew is installed and configured correctly. ```bash brew uninstall gemini-cli ``` -------------------------------- ### Define Agent Skill Metadata and Instructions Source: https://geminicli.com/docs/extensions/writing-extensions Creates a SKILL.md file to define the agent skill's name, description, and instructions. This file is used by Gemini CLI to understand and activate the skill when relevant tasks are requested. ```markdown --- name: security-audit description: Expertise in auditing code for security vulnerabilities. Use when the user asks to "check for security issues" or "audit" their changes. --- # Security Auditor You are an expert security researcher. When auditing code: 1. Look for common vulnerabilities (OWASP Top 10). 2. Check for hardcoded secrets or API keys. 3. Suggest remediation steps for any findings. ```