| theme | seriph | ||||||
|---|---|---|---|---|---|---|---|
| background | https://images.unsplash.com/photo-1451187580459-43490279c0fa?ixlib=rb-4.0.3&auto=format&fit=crop&w=1920&q=80 | ||||||
| addons |
|
||||||
| class | text-center | ||||||
| highlighter | shiki | ||||||
| lineNumbers | true | ||||||
| info | ## Agentic Coding with Gemini CLI By Kenneth Kousen Learn more at [KouseniT](https://kousenit.com) | ||||||
| drawings |
|
||||||
| transition | slide-left | ||||||
| title | Agentic Coding with Gemini CLI | ||||||
| mdc | true | ||||||
| slidev |
|
||||||
| css | unocss |
Press Space for next page
Ken Kousen Kousen IT, Inc.
- ken.kousen@kousenit.com
- http://www.kousenit.com
- http://kousenit.org (blog)
- Social Media:
- @kenkousen (twitter)
- @kenkousen@foojay.social (mastodon)
- @kousenit.com (bluesky)
- Tales from the jar side (free newsletter)
- Duration: 5 hours of hands-on learning
- Format: Instructor-led with multiple labs
- Hands-on Labs: Real codebases in Python, JavaScript, Java
- Prerequisites: Command-line experience, development background
- Foundation: Installation, CLI basics, authentication
- Core Skills: File operations, shell integration, context management
- Customization: GEMINI.md, custom commands, settings.json
- Safety: Sandbox mode, approval policies, checkpointing
- Advanced: MCP integration, skills/extensions, session management
- Agent Skills stable and default-on · SDK +
SessionContext(0.30) - Policy Engine replaces
--allowed-tools/tools.exclude(0.30) - Gemini 3.1 Pro Preview available via
/model(0.31) - Workspace model steering + parallel extension loading (0.32)
- A2A remote agents over authenticated HTTP (0.33)
- Plan Mode (opt-in via
--approval-mode plan); gVisor/LXC sandboxing on Linux (0.34) - Multi-registry MCP/extensions, macOS Seatbelt, Windows sandboxing, Git worktrees (0.36)
- Ctrl+G replaces
Ctrl+Xfor external editor; persistent policy approvals (0.37) - Latest stable track: Gemini CLI
0.37.x
- Open-source AI agent from Google
- Gemini 3.1 Pro Preview (newest) · Gemini 3 Pro · Gemini 2.5 Pro/Flash
- Built-in tools: Google Search, file ops, shell, web fetch
- Model Context Protocol (MCP) support
- Designed for developers who live in the terminal
- Massive Context: 1 million token context window
- Google Search Grounding: Real-time web access
- Free Tier Available: Generous API limits
- Open Source: Fully open, community-driven
- MCP Native: Built-in Model Context Protocol support
- Gemini 3.1 Pro Preview: Newest, added in Gemini CLI 0.31
- Gemini 3 Pro: Most intelligent stable model, best for complex coding
- Gemini 2.5 Pro: Strong performance, 1M token context
- Gemini 2.5 Flash: Faster, lower cost option
- Auto routing: CLI picks the best model for each task
- Workspace model steering (0.32+): pin a model per workspace
- Free Tier: Generous daily limits
- Google AI Ultra: Full Gemini 3 Pro access
- Paid API Key: Pay-as-you-go pricing
- Enable via
/settings→ "Preview features"
📖 Get API Key: Google AI Studio
- npm (recommended):
npm install -g @google/gemini-cli - npx (no install):
npx @google/gemini-cli - Verify:
gemini --version - Current version: 0.37.x (latest stable as of April 2026)
# Install globally
npm install -g @google/gemini-cli
# Verify installation
gemini --version- Environment Variable:
export GEMINI_API_KEY="your-key" - Global .env file:
~/.gemini/.env - Project .env file:
./.gemini/.env - Google Cloud:
GOOGLE_CLOUD_PROJECTfor Vertex AI
# Option 1: Environment variable
export GEMINI_API_KEY="your-api-key"
# Option 2: Global .env file
echo 'GEMINI_API_KEY=your-api-key' >> ~/.gemini/.env
# Option 3: Project .env file
mkdir -p .gemini && echo 'GEMINI_API_KEY=your-api-key' >> .gemini/.env- Interactive REPL:
gemini- Start a conversation - One-shot:
gemini "prompt"- Single response - Piped input:
echo "task" | gemini - Interactive with context:
gemini -i "initial context"
# Interactive mode
gemini
# One-shot mode
gemini "Explain what this codebase does"
# With initial context
gemini -i "You are a Python expert"layout: image-right image: https://images.unsplash.com/photo-1555949963-ff9fe0c870eb?ixlib=rb-4.0.3&auto=format&fit=crop&w=1920&q=80 backgroundSize: cover
- Reference files directly:
@./src/main.js - Reference directories:
@./src/(recursive) - Reference images:
@./screenshot.png - Multiple references in one prompt
# Reference a specific file
gemini "Explain @./src/app.py"
# Reference multiple files
gemini "Compare @./old.js and @./new.js"
# Reference a directory
gemini "Analyze the architecture in @./src/"- Execute shell commands:
!git status - Toggle persistent shell mode:
! - Gemini can observe and analyze output
- Combine with AI analysis
# In interactive mode:
> !npm test
# Gemini sees the test output
> !git diff
# Ask Gemini to analyze the changes
# Toggle persistent shell mode
> !/help- Show available commands/clear- Clear conversation history/memory show- View loaded context/memory refresh- Reload GEMINI.md files
/init- Generate project GEMINI.md/prompt-suggest- Generate stronger prompts/stats- Session and quota metrics
/resume- Open session browser/rewind- Navigate and optionally revert history/restore- Recover from checkpoint
# Show what context is loaded
/memory show
# Reload all GEMINI.md files
/memory refresh
# Generate a GEMINI.md for current project
/init
# Suggest stronger prompt wording
/prompt-suggest# Open session browser
/resume
# Rewind through recent interactions
/rewind
# Restore from checkpoint list
/restoreCtrl+L- Clear screenCtrl+V- Paste text/imagesCtrl+G- Open external editor (wasCtrl+Xbefore 0.37)
Ctrl+Y- Toggle auto-approval (YOLO mode)Shift+Tab- Cycle approval mode (default/auto_edit/plan)Ctrl+C- Cancel current operationCtrl+D- Exit Gemini CLI
- File System:
read_file(),write_file(),replace(),glob() - Shell: Execute terminal commands
- Web:
google_web_search(),web_fetch() - Memory:
save_memory()for cross-session recall
# Gemini automatically uses appropriate tools
"Search the web for React 19 new features"
# Uses google_web_search()
"Read all Python files in src/"
# Uses glob() and read_file()
"Update the README with the changes we made"
# Uses write_file()layout: image-right image: https://images.unsplash.com/photo-1488590528505-98d2b5aba04b?ixlib=rb-4.0.3&auto=format&fit=crop&w=1920&q=80 backgroundSize: cover
- default (the default): Prompt for approval on each tool call
- plan: Read-only — draft a plan, no execution until you approve
- auto_edit: Auto-approve file edit tools only
- yolo: Auto-approve ALL tool calls
# Default - interactive, prompts per tool call
gemini
# Draft a plan first (read-only until approved)
gemini --approval-mode plan
# Auto-approve edits only
gemini --approval-mode auto_edit
# Auto-approve everything (YOLO mode)
gemini --approval-mode yolo
# Or use Ctrl+Y in interactive mode- Opt-in with
--approval-mode plan— read-only until you approve - Drafts a structured plan before touching any file or tool
- Open the plan in your external editor with
Ctrl+G - Use
Shift+Tabto cycle intodefault/auto_editonce you're ready - 0.33+ adds research subagents, annotations, and a
copysubcommand - Great first step when exploring an unfamiliar codebase
# Launch in plan mode
gemini --approval-mode plan- Isolate file operations away from your host
- Multiple backends depending on your OS
- Prevents accidental system changes
- Perfect for exploring unfamiliar code
# Run in sandbox mode (picks the best backend for your OS)
gemini --sandbox
# Short form
gemini -s "Refactor this entire codebase"- Docker / Podman: original cross-platform option
- gVisor (runsc): Linux, added in 0.34 — strong kernel-level isolation
- LXC: Linux, experimental in 0.34
- macOS Seatbelt: native in 0.36, no Docker required
- Windows sandboxing: native subagent sandboxing in 0.36
// ~/.gemini/settings.json
{
"tools": {
"sandbox": "docker" // or "gvisor", "seatbelt", etc.
}
}📖 geminicli.com/docs/cli/settings/
- Automatic: Snapshots created before each file modification
- Shadow Git: Stored in
~/.gemini/history/(not your repo) - Includes: Files + conversation + tool call
- Disabled by default: Must enable in settings
// ~/.gemini/settings.json
{ "general": { "checkpointing": { "enabled": true } } }# List and select a checkpoint to restore
/restore
# Shows timestamps + filename + tool name
# e.g., 2025-06-22T10-00-00_000Z-app.py-write_fileRestores files AND resets conversation to that point
layout: image-left image: https://images.unsplash.com/photo-1454165804606-c3d57bc86b40?ixlib=rb-4.0.3&auto=format&fit=crop&w=1920&q=80 backgroundSize: cover
- Project memory loaded automatically
- Coding standards and conventions
- Architecture context for the AI
- Persistent instructions across sessions
- Similar to CLAUDE.md or AGENTS.md
graph TD
A[~/.gemini/GEMINI.md<br/>Global Rules] --> B[project/GEMINI.md<br/>Project Standards]
B --> C[project/frontend/GEMINI.md<br/>Frontend Conventions]
B --> D[project/backend/GEMINI.md<br/>Backend Patterns]
style A fill:#FFE5CC,stroke:#333,stroke-width:2px,color:#000
style B fill:#CCE5FF,stroke:#333,stroke-width:2px,color:#000
style C fill:#E5CCFF,stroke:#333,stroke-width:2px,color:#000
style D fill:#CCFFE5,stroke:#333,stroke-width:2px,color:#000
More specific files override general ones
# Project: Weather API
## Tech Stack
- Backend: Python Flask
- Database: PostgreSQL
- Testing: pytest
## Coding Standards
- Use type hints for all functions
- Follow PEP 8 style guide
- Write docstrings for public APIs
## Current Focus
Implementing caching layer for API responses/memory show- View combined context/memory refresh- Reload all GEMINI.md files/memory add <text>- Append to global GEMINI.md/init- Generate starter GEMINI.md
# See what context is loaded
/memory show
# Add a quick note to global memory
/memory add "Always use async/await for database calls"
# Generate a project-specific GEMINI.md
/init- Import other files with
@file.mdsyntax - Break large context into components
- Supports relative and absolute paths
# GEMINI.md
## Project Overview
@./docs/architecture.md
## Coding Standards
@./docs/style-guide.md
## API Documentation
@./docs/api-reference.mdlayout: image-right image: https://images.unsplash.com/photo-1558494949-ef010cbdcc31?ixlib=rb-4.0.3&auto=format&fit=crop&w=1920&q=80 backgroundSize: cover
- Default values - Built-in defaults
- User settings -
~/.gemini/settings.json - Project settings -
.gemini/settings.json - Environment variables - Including
.envfiles - Command-line arguments - Highest priority
{
"general": {
"preferredEditor": "vscode",
"vimMode": false,
"checkpointing": { "enabled": true }
}
}{
"ui": {
"hideTips": false,
"hideBanner": false
},
"tools": {
"sandbox": false
}
}- tools.allowed: Whitelist available tools
- Policy Engine (preferred):
denyrules for blocking tools tools.excludestill works but is deprecated since 0.30
{
"tools": {
"allowed": ["read_file", "write_file", "glob"]
}
}Pass a policy file to block tools:
gemini --policy ./policy.tomlPolicy files use TOML with decision + priority fields per rule.
See the current schema at the docs link below.
📖 geminicli.com/docs/reference/policy-engine
- respectGitIgnore: Honor .gitignore patterns
- enableRecursiveFileSearch: Recursive completion
- .geminiignore: Custom ignore patterns
{
"context": {
"fileFiltering": {
"respectGitIgnore": true,
"respectGeminiIgnore": true,
"enableRecursiveFileSearch": true
}
}
}| Variable | Purpose |
|---|---|
GEMINI_API_KEY |
Google AI Studio authentication |
GOOGLE_API_KEY |
Vertex API key authentication |
GEMINI_MODEL |
Override default model |
GOOGLE_CLOUD_PROJECT |
GCP project for Vertex AI |
GOOGLE_CLOUD_LOCATION |
GCP region |
GEMINI_CLI_HOME |
Override Gemini CLI home directory |
HTTP_PROXY |
Network proxy |
- Change from
GEMINI.mdto a custom name AGENTS.mdis officially supported — friendly to multi-agent repos- Support multiple filenames in priority order
- Include additional directories
{
"context": {
"fileName": ["AGENTS.md", "GEMINI.md", "CONTEXT.md"],
"includeDirectories": ["~/shared-context"],
"loadMemoryFromIncludeDirectories": true
}
}layout: image-right image: https://images.unsplash.com/photo-1516321318423-f06f85e504b3?ixlib=rb-4.0.3&auto=format&fit=crop&w=1920&q=80 backgroundSize: cover
- Standard protocol for AI-to-system connections
- Connect to external tools and services
- Supports local commands, HTTP, and SSE
- OAuth 2.0 for remote authentication
{
"mcpServers": {
"firecrawl": {
"command": "npx",
"args": ["@modelcontextprotocol/server-firecrawl"],
"env": {
"FIRECRAWL_API_KEY": "${FIRECRAWL_API_KEY}"
}
}
}
}{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["@modelcontextprotocol/server-postgres"],
"env": {
"CONNECTION_STRING": "${DATABASE_URL}"
}
}
}
}# List configured MCP servers
gemini mcp list
# Add a new MCP server
gemini mcp add github npx -y @modelcontextprotocol/server-github
# Remove an MCP server
gemini mcp remove github# List MCP tools/resources from inside session
/mcp list
# Authenticate with OAuth-enabled MCP server
/mcp auth github
# Refresh MCP tools/resources
/mcp refresh- command: Shell command to start server
- args: Command arguments
- env: Environment variables
- cwd: Working directory
- timeout: Startup timeout in ms
- includeTools/excludeTools: Filter available tools
- trust: Bypass tool confirmation for this server
- Firecrawl - Web scraping, search, content extraction
- PostgreSQL - Database queries and schema
- Filesystem - Extended file operations
- Slack - Team communication
- Playwright - Browser automation
📖 Registry: modelcontextprotocol.io/registry
- Gemini CLI now supports multiple extension/MCP registries side by side
- Mix the public MCP registry with internal/private registries
- Useful for teams that host vetted MCP servers internally
- Extensions load in parallel (added in 0.32)
# List registries and what each provides
gemini extensions list
gemini mcp list📖 geminicli.com/docs/changelogs/latest/
- Gemini CLI can call remote agents over HTTP via the A2A protocol
- Authenticated agent-card discovery for private catalogs
- Same permissioning story as MCP: allow/deny per server
- Good fit for internal "shared agents" a team maintains centrally
- Extend Gemini CLI capabilities
- Place in
~/.gemini/extensions/ - Configure with
gemini-extension.json - List with
gemini --list-extensions
# List available extensions
gemini --list-extensions
# Use specific extensions only
gemini -e extension1 -e extension2
# Manage extensions
gemini extensions list
gemini extensions enable my-extension- Create reusable prompt templates
- Place TOML files in
~/.gemini/commands/ - Access via slash command syntax
# ~/.gemini/commands/review.toml
description = "Review code for issues"
prompt = """
Review the following code for:
- Security vulnerabilities
- Performance issues
- Best practices violations
{{args}}
"""- Resume sessions: Continue previous conversations
- List sessions: View available sessions
- Delete sessions: Clean up old conversations
# Resume the latest session
gemini --resume
# Resume by index
gemini --resume 3
# List available sessions
gemini --list-sessions
# Delete a session
gemini --delete-session 5- text: Default human-readable output
- json: Structured JSON for scripting
- stream-json: Streaming JSON for real-time
# JSON output for automation
gemini -o json "List all TODO comments"
# Stream JSON for real-time processing
gemini -o stream-json "Analyze this codebase"- VS Code Integration: Connect to workspace
- Native diff viewing: Review changes in editor
- Context sharing: IDE context available to Gemini
{
"preferredEditor": "vscode"
}layout: image-left image: https://images.unsplash.com/photo-1498050108023-c5249f4df085?ixlib=rb-4.0.3&auto=format&fit=crop&w=1920&q=80 backgroundSize: cover
- Understand unfamiliar codebases
- Trace dependencies and data flow
- Find patterns and conventions
- Generate architecture documentation
gemini "Analyze the architecture of @./src/ and explain
how the components interact"
gemini "Trace the flow from the API endpoint to the database
in @./src/controllers/ and @./src/services/"- Generate unit tests for existing code
- Identify edge cases automatically
- Create integration test scaffolding
- Mock setup and fixtures
gemini "Create comprehensive unit tests for @./src/utils.py
with pytest, including edge cases"
gemini "Generate integration tests for @./src/api/users.py
with proper mocking"- README files for projects
- API documentation
- Architecture diagrams (Mermaid)
- Code comments and docstrings
gemini "Generate a comprehensive README.md for this project"
gemini "Add detailed docstrings to all public functions
in @./src/services/"
gemini "Create a Mermaid diagram showing the system architecture"- Upgrade legacy code patterns
- Apply modern language features
- Improve code organization
- Fix anti-patterns
gemini "Refactor @./src/legacy.py to use modern Python 3.12
features like type hints and match statements"
gemini "Convert this callback-based code to async/await
@./src/api.js"- Analyze error messages and stack traces
- Identify root causes
- Suggest fixes with context
- Test and verify solutions
gemini "This test is failing with @./tests/output.log.
Analyze the error and fix the issue in @./src/app.py"
gemini "Debug why the API returns 500 errors.
Check @./src/routes.py and @./src/middleware.py"- Generate commit messages
- Create pull request descriptions
- Analyze diffs and changes
- Resolve merge conflicts
# Analyze staged changes
!git diff --staged
"Generate a conventional commit message for these changes"
# Create PR description
"Create a pull request description summarizing the changes
from the last 5 commits"- Non-interactive mode for pipelines
- JSON output for parsing
- Exit codes for success/failure
- Automated code reviews
# In CI/CD pipeline
gemini "Review @./src/ for security issues" -o json > review.json
# Check exit code
if gemini "Verify all tests pass" -o json; then
echo "All checks passed"
filayout: image-right image: https://images.unsplash.com/photo-1522071820081-009f0129c71c?ixlib=rb-4.0.3&auto=format&fit=crop&w=1920&q=80 backgroundSize: cover
- Designed for teams moving from personal usage to production workflows
- Can be taught live or assigned as follow-up practice
- Focus areas: auth strategy, governance, skills/MCP, CI automation
- Login with Google: Best default for local interactive usage
GEMINI_API_KEY: Simple personal/team scripts via AI Studio- Vertex + ADC: Enterprise cloud projects and IAM-managed access
- Service account credentials: CI/CD and headless automation
# API key route
export GEMINI_API_KEY="..."
gemini
# Vertex route (ADC)
unset GEMINI_API_KEY GOOGLE_API_KEY
gcloud auth application-default login
export GOOGLE_CLOUD_PROJECT="my-project"
export GOOGLE_CLOUD_LOCATION="us-central1"
gemini- Approval mode controls are per-session safety rails
- Policies provide durable guardrails across users/projects
- Keep high-risk tools constrained in team settings
- Prefer explicit allow/deny patterns over ad-hoc approvals
/hooks listshows active lifecycle hooks- Use hooks for auditing, validation, and policy enforcement
- Folder trust impacts settings, skills, and context loading
- Treat untrusted repos with stricter modes and sandboxing
- Skills package repeatable expert workflows for teams
- MCP connects external systems (docs, data, browsers, APIs)
- Resource URIs can be injected via
@server://resource/path - Use
includeTools/excludeToolsto narrow risky MCP exposure
# Skills lifecycle
/skills list
/skills disable skill-name
/skills enable skill-name
# MCP visibility and maintenance
/mcp list
/mcp auth server-name
/mcp refresh- Prefer
-o jsonfor machine-readable parsing - Use exit codes for pipeline gates
- Keep prompts deterministic and repo-scoped
- Store logs/artifacts for auditability
gemini -o json "Review @./src/ for security issues" > review.json
if gemini -o json "Run checks and report pass/fail"; then
echo "Gate passed"
else
echo "Gate failed" && exit 1
filayout: image-right image: https://images.unsplash.com/photo-1522071820081-009f0129c71c?ixlib=rb-4.0.3&auto=format&fit=crop&w=1920&q=80 backgroundSize: cover
- Be specific about what you want to achieve
- Provide context about goals and constraints
- Use file references to ground the conversation
- Iterate for complex tasks
- Include examples when possible
- Start in default mode - Get comfortable first
- Enable checkpointing - Safety net for mistakes
- Review generated code - Don't blindly accept
- Use sandbox for exploratory work
- Commit often - Git is your safety net
- Create comprehensive GEMINI.md
- Set up project-specific settings.json
- Configure relevant MCP servers
- Create custom commands for common tasks
- Establish team conventions
- Keep it focused - Relevant project info only
- Update regularly - Reflect current state
- Use imports - Modularize large contexts
- Include examples - Show expected patterns
- Document conventions - Style guides, patterns
- Share GEMINI.md in version control
- Standardize settings.json across team
- Create shared custom commands
- Document AI-assisted workflows
- Review AI-generated code together
- Overly broad prompts → Be specific
- Missing context → Use GEMINI.md
- Skipping review → Always verify output
- YOLO mode too early → Build trust first
- Ignoring checkpoints → Enable early
- Authentication issues: Check
GEMINI_API_KEY - Rate limits: Use appropriate tier
- Tool failures: Check MCP server status
- Context not loading: Run
/memory refresh - Debug mode: Use
gemini -dfor details
# Debug mode for troubleshooting
gemini -d
# Check memory/context
/memory show
# Refresh context files
/memory refreshhttps://github.com/google-gemini/gemini-cli
https://aistudio.google.com/apikey
https://modelcontextprotocol.io/registry
https://github.com/kousen/gemini-training
# Interactive mode
gemini
# One-shot mode
gemini "prompt"
# Interactive with initial context
gemini -i "context"# Run in sandbox mode
gemini --sandbox
# Auto-approve all tool calls
gemini --approval-mode yolo
# Auto-approve file edits only
gemini --approval-mode auto_edit# Resume last session
gemini --resume
# List available sessions
gemini --list-sessions
# Delete a session
gemini --delete-session 2# JSON output for scripting
gemini -o json "prompt"
# Streaming JSON events
gemini -o stream-json "prompt"
# Debug mode
gemini -d