Model Context Protocol (MCP) is the key to unlocking Gemini CLI's full potential. By configuring MCP integrations, you can connect Gemini to databases, APIs, custom tools, and external services, transforming it from a standalone AI assistant into a powerful automation hub.
This guide covers everything from basic MCP configuration to advanced integrations with databases and custom Python tools.
What is MCP?
MCP (Model Context Protocol) is an open standard that provides a unified way for AI agents to interact with external systems. An MCP server exposes:
- Tools: Functions that Gemini can call to perform actions
- Resources: Data sources that Gemini can read from
- Prompts: Predefined templates accessible as slash commands
MCP servers act as a bridge between the Gemini model and your local environment, databases, or cloud services.
Prerequisites
Before configuring MCP integrations:
- Gemini CLI installed (see How to Install Google Gemini CLI)
- Node.js 20+ for running Node.js-based MCP servers
- Python 3.9+ for running Python-based MCP servers (optional)
- Basic familiarity with JSON for configuration files
Configuration File Locations
MCP servers are configured in settings.json files. Gemini CLI checks multiple locations in this order of precedence:
| Type | macOS/Linux | Windows |
|---|---|---|
| User Settings | ~/.gemini/settings.json | %USERPROFILE%\.gemini\settings.json |
| Project Settings | .gemini/settings.json | .gemini\settings.json |
| System Settings | /etc/gemini-cli/settings.json | C:\ProgramData\gemini-cli\settings.json |
Project settings override user settings, which override system settings.
Basic MCP Configuration
Create or edit your ~/.gemini/settings.json file:
{
"mcpServers": {
"myServer": {
"command": "node",
"args": ["path/to/mcp-server.js"]
}
}
}
Configuration Options
Each MCP server requires at least one transport mechanism:
| Option | Description |
|---|---|
command | Executable path for stdio transport (local servers) |
url | SSE endpoint URL for Server-Sent Events transport |
httpUrl | HTTP streaming endpoint for remote servers |
Additional optional settings:
| Option | Description |
|---|---|
args | Array of command-line arguments |
env | Environment variables (supports $VAR_NAME expansion) |
cwd | Working directory for the server |
timeout | Request timeout in milliseconds (default: 600,000) |
trust | Skip confirmation dialogs when true (use cautiously) |
includeTools | Allowlist specific tools by name |
excludeTools | Blocklist specific tools (takes precedence over includeTools) |
Creating Custom Tools with Python (FastMCP)
FastMCP is the easiest way to create custom MCP tools for Gemini CLI.
Step 1: Install FastMCP
pip install fastmcp>=2.12.3
Step 2: Create Your Server
Create a file called my_tools.py:
from fastmcp import FastMCP
# Create the MCP server
mcp = FastMCP("MyCustomTools")
@mcp.tool
def calculate_discount(price: float, percentage: float) -> float:
"""Calculate the discounted price given an original price and discount percentage."""
discount = price * (percentage / 100)
return round(price - discount, 2)
@mcp.tool
def format_currency(amount: float, currency: str = "USD") -> str:
"""Format a number as currency with the appropriate symbol."""
symbols = {"USD": "$", "EUR": "EUR ", "GBP": "GBP "}
symbol = symbols.get(currency, currency + " ")
return f"{symbol}{amount:,.2f}"
@mcp.tool
def word_count(text: str) -> dict:
"""Count words, characters, and lines in a text string."""
return {
"words": len(text.split()),
"characters": len(text),
"lines": text.count('\n') + 1
}
if __name__ == "__main__":
mcp.run()
Step 3: Install with Gemini CLI
FastMCP provides a convenient installation command:
fastmcp install gemini-cli my_tools.py
This automatically:
- Configures the MCP server in your settings.json
- Sets up proper dependency management
- Registers all tools with Gemini CLI
Step 4: Verify Installation
gemini
Then type /mcp to see your custom tools listed.
Manual Configuration (Alternative)
If you prefer manual configuration, add this to ~/.gemini/settings.json:
{
"mcpServers": {
"myTools": {
"command": "python",
"args": ["-m", "my_tools"],
"cwd": "/path/to/your/project"
}
}
}
Connecting to Databases
MCP servers can connect Gemini CLI to various databases for natural language queries.
SQLite Integration
Install the MCP SQLite server:
npm install -g mcp-sqlite
Configure in settings.json:
{
"mcpServers": {
"sqlite": {
"command": "npx",
"args": ["-y", "mcp-sqlite", "/path/to/your/database.db"]
}
}
}
Now you can ask Gemini questions like:
- "Show me all users who signed up last month"
- "What are the top 10 products by revenue?"
- "Find orders with status pending"
PostgreSQL Integration
For PostgreSQL, use the MCP Toolbox:
{
"mcpServers": {
"postgres": {
"command": "./toolbox",
"args": ["--prebuilt", "postgres", "--stdio"],
"env": {
"POSTGRES_HOST": "localhost",
"POSTGRES_PORT": "5432",
"POSTGRES_DATABASE": "myapp",
"POSTGRES_USER": "$DB_USER",
"POSTGRES_PASSWORD": "$DB_PASSWORD"
}
}
}
}
Security note: Use environment variable expansion ($VAR_NAME) for sensitive values like passwords rather than hardcoding them.
DBHub (Multi-Database)
DBHub provides a single MCP server for multiple database types:
npm install -g dbhub
{
"mcpServers": {
"dbhub": {
"command": "dbhub",
"args": ["--connection-string", "$DATABASE_URL"]
}
}
}
Supported databases: PostgreSQL, MySQL, MariaDB, SQL Server, SQLite.
Connecting to External APIs
GitHub Integration
Connect Gemini CLI to GitHub for repository management:
{
"mcpServers": {
"github": {
"httpUrl": "https://api.githubcopilot.com/mcp/",
"headers": {
"Authorization": "Bearer $GITHUB_TOKEN"
},
"timeout": 30000
}
}
}
Custom API Server Example
Create an API wrapper as an MCP server:
from fastmcp import FastMCP
import httpx
mcp = FastMCP("APIWrapper")
@mcp.tool
async def get_weather(city: str) -> dict:
"""Get current weather for a city using the weather API."""
async with httpx.AsyncClient() as client:
response = await client.get(
f"https://api.weatherapi.com/v1/current.json",
params={"key": os.environ["WEATHER_API_KEY"], "q": city}
)
data = response.json()
return {
"city": data["location"]["name"],
"temp_f": data["current"]["temp_f"],
"condition": data["current"]["condition"]["text"]
}
if __name__ == "__main__":
mcp.run()
Managing MCP Servers via CLI
Gemini CLI provides commands for managing MCP servers:
# Add a new server
gemini mcp add myserver python my_server.py
# List all configured servers
gemini mcp list
# Remove a server
gemini mcp remove myserver
# Enable a disabled server
gemini mcp enable myserver
# Disable a server temporarily
gemini mcp disable myserver
MCP Prompts as Slash Commands
MCP servers can expose predefined prompts accessible as slash commands:
from fastmcp import FastMCP
mcp = FastMCP("PromptServer")
@mcp.prompt
def code_review():
"""Perform a thorough code review of the current file."""
return """Review this code for:
1. Security vulnerabilities
2. Performance issues
3. Code style and readability
4. Potential bugs
Provide specific line numbers and suggestions."""
@mcp.prompt
def explain_error(error_message: str):
"""Explain an error message and suggest fixes."""
return f"""Explain this error and provide solutions:
Error: {error_message}
Include:
- What caused this error
- How to fix it
- How to prevent it in the future"""
if __name__ == "__main__":
mcp.run()
After configuration, use these as /code_review or /explain_error "message" in Gemini CLI.
Working with MCP Resources
MCP servers can expose resources that Gemini can read:
from fastmcp import FastMCP
mcp = FastMCP("ResourceServer")
@mcp.resource("config://app")
def get_app_config() -> str:
"""Application configuration settings."""
with open("config.json") as f:
return f.read()
@mcp.resource("report://{report_type}")
def get_report(report_type: str) -> str:
"""Get a specific report by type."""
reports = {
"daily": "Daily sales: $10,000",
"weekly": "Weekly sales: $70,000",
"monthly": "Monthly sales: $300,000"
}
return reports.get(report_type, "Report not found")
if __name__ == "__main__":
mcp.run()
Reference resources in Gemini CLI using @server://resource/path syntax.
Platform-Specific Notes
macOS
- Configuration files use Unix paths:
~/.gemini/settings.json - For Homebrew-installed dependencies, ensure they are in your PATH
- Apple Silicon users may need to use
arch -arm64prefix for some npm packages
Windows
- Use backslashes in paths within JSON:
"cwd": "C:\\Projects\\mcp-server" - Or use forward slashes (also valid):
"cwd": "C:/Projects/mcp-server" - PowerShell environment variables:
$env:MY_VAR = "value" - For WSL-based servers, use WSL paths in the command
Linux
- System-wide configuration:
/etc/gemini-cli/settings.json - User configuration:
~/.gemini/settings.json - Ensure Python/Node.js are accessible from PATH
- For Docker-based servers, ensure Docker daemon is running
Security Considerations
Trust Settings
The trust: true option bypasses confirmation dialogs. Only use for:
- Servers you completely control
- Local development environments
- Thoroughly tested production servers
{
"mcpServers": {
"trustedServer": {
"command": "python",
"args": ["trusted_server.py"],
"trust": true
}
}
}
Environment Variables
Never hardcode sensitive values. Use environment variable expansion:
{
"mcpServers": {
"secure": {
"command": "node",
"args": ["server.js"],
"env": {
"API_KEY": "$MY_API_KEY",
"DB_PASSWORD": "$DB_PASSWORD"
}
}
}
}
Tool Filtering
Restrict available tools for security:
{
"mcpServers": {
"restricted": {
"command": "python",
"args": ["server.py"],
"includeTools": ["safe_read", "safe_query"],
"excludeTools": ["dangerous_delete", "admin_reset"]
}
}
}
Troubleshooting
Server Not Connecting
- Check the command exists:
which python # or node, npx, etc.
- Verify paths are correct:
ls -la /path/to/your/server.py
- Enable debug mode:
gemini --debug
- Test the server independently:
python my_server.py
No Tools Discovered
- Ensure your server implements the MCP protocol correctly
- Check for schema validation errors in debug output
- Verify
includeTools/excludeToolsare not filtering all tools
Timeout Errors
Increase the timeout for slow-starting servers:
{
"mcpServers": {
"slowServer": {
"command": "python",
"args": ["heavy_server.py"],
"timeout": 120000
}
}
}
Environment Variables Not Expanding
- Use
$VAR_NAMEor${VAR_NAME}syntax - Ensure variables are set in your shell before running Gemini CLI
- Create a
.envfile in your project directory for automatic loading
Next Steps
- Explore the Gemini CLI GitHub repository for more examples
- Read the FastMCP documentation for advanced Python MCP development
- Check out MCP Servers directory for pre-built community servers
- Learn about Google's managed MCP servers for enterprise integrations