feat: add support for Gemini CLI integration (#1709)

This commit is contained in:
Jack Wotherspoon 2025-09-06 10:08:56 -06:00 committed by GitHub
commit e5e426279e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 487 additions and 0 deletions

View file

@ -0,0 +1,173 @@
---
title: Gemini CLI 🤝 FastMCP
sidebarTitle: Gemini CLI
description: Install and use FastMCP servers in Gemini CLI
icon: message-smile
---
import { VersionBadge } from "/snippets/version-badge.mdx"
import { LocalFocusTip } from "/snippets/local-focus.mdx"
<LocalFocusTip />
Gemini CLI supports MCP servers through multiple transport methods including STDIO, SSE, and HTTP, allowing you to extend Gemini's capabilities with custom tools, resources, and prompts from your FastMCP servers.
## Requirements
This integration uses STDIO transport to run your FastMCP server locally. For remote deployments, you can run your FastMCP server with HTTP or SSE transport and configure it directly using Gemini CLI's built-in MCP management commands.
## Create a Server
The examples in this guide will use the following simple dice-rolling server, saved as `server.py`.
```python server.py
import random
from fastmcp import FastMCP
mcp = FastMCP(name="Dice Roller")
@mcp.tool
def roll_dice(n_dice: int) -> list[int]:
"""Roll `n_dice` 6-sided dice and return the results."""
return [random.randint(1, 6) for _ in range(n_dice)]
if __name__ == "__main__":
mcp.run()
```
## Install the Server
### FastMCP CLI
<VersionBadge version="2.13.0" />
The easiest way to install a FastMCP server in Gemini CLI is using the `fastmcp install gemini-cli` command. This automatically handles the configuration, dependency management, and calls Gemini CLI's built-in MCP management system.
```bash
fastmcp install gemini-cli server.py
```
The install command supports the same `file.py:object` notation as the `run` command. If no object is specified, it will automatically look for a FastMCP server object named `mcp`, `server`, or `app` in your file:
```bash
# These are equivalent if your server object is named 'mcp'
fastmcp install gemini-cli server.py
fastmcp install gemini-cli server.py:mcp
# Use explicit object name if your server has a different name
fastmcp install gemini-cli server.py:my_custom_server
```
The command will automatically configure the server with Gemini CLI's `gemini mcp add` command.
#### Dependencies
FastMCP provides flexible dependency management options for your Gemini CLI servers:
**Individual packages**: Use the `--with` flag to specify packages your server needs. You can use this flag multiple times:
```bash
fastmcp install gemini-cli server.py --with pandas --with requests
```
**Requirements file**: If you maintain a `requirements.txt` file with all your dependencies, use `--with-requirements` to install them:
```bash
fastmcp install gemini-cli server.py --with-requirements requirements.txt
```
**Editable packages**: For local packages under development, use `--with-editable` to install them in editable mode:
```bash
fastmcp install gemini-cli server.py --with-editable ./my-local-package
```
Alternatively, you can use a `fastmcp.json` configuration file (recommended):
```json fastmcp.json
{
"$schema": "https://gofastmcp.com/public/schemas/fastmcp.json/v1.json",
"source": {
"path": "server.py",
"entrypoint": "mcp"
},
"environment": {
"dependencies": ["pandas", "requests"]
}
}
```
#### Python Version and Project Configuration
Control the Python environment for your server with these options:
**Python version**: Use `--python` to specify which Python version your server requires. This ensures compatibility when your server needs specific Python features:
```bash
fastmcp install gemini-cli server.py --python 3.11
```
**Project directory**: Use `--project` to run your server within a specific project context. This tells `uv` to use the project's configuration files and virtual environment:
```bash
fastmcp install gemini-cli server.py --project /path/to/my-project
```
#### Environment Variables
If your server needs environment variables (like API keys), you must include them:
```bash
fastmcp install gemini-cli server.py --server-name "Weather Server" \
--env API_KEY=your-api-key \
--env DEBUG=true
```
Or load them from a `.env` file:
```bash
fastmcp install gemini-cli server.py --server-name "Weather Server" --env-file .env
```
<Warning>
**Gemini CLI must be installed**. The integration looks for the Gemini CLI and uses the `gemini mcp add` command to register servers.
</Warning>
### Manual Configuration
For more control over the configuration, you can manually use Gemini CLI's built-in MCP management commands. This gives you direct control over how your server is launched:
```bash
# Add a server with custom configuration
gemini mcp add dice-roller uv -- run --with fastmcp fastmcp run server.py
# Add with environment variables
gemini mcp add weather-server -e API_KEY=secret -e DEBUG=true uv -- run --with fastmcp fastmcp run server.py
# Add with specific scope (user, or project)
gemini mcp add my-server --scope user uv -- run --with fastmcp fastmcp run server.py
```
You can also manually specify Python versions and project directories in your Gemini CLI commands:
```bash
# With specific Python version
gemini mcp add ml-server uv -- run --python 3.11 --with fastmcp fastmcp run server.py
# Within a project directory
gemini mcp add project-server uv -- run --project /path/to/project --with fastmcp fastmcp run server.py
```
## Using the Server
Once your server is installed, you can start using your FastMCP server with Gemini CLI.
Try asking Gemini something like:
> "Roll some dice for me"
Gemini will automatically detect your `roll_dice` tool and use it to fulfill your request.
Gemini CLI can now access all the tools and prompts you've defined in your FastMCP server.
If your server provides prompts, you can use them as slash commands with `/prompt_name`.

View file

@ -5,6 +5,7 @@ import cyclopts
from .claude_code import claude_code_command
from .claude_desktop import claude_desktop_command
from .cursor import cursor_command
from .gemini_cli import gemini_cli_command
from .mcp_json import mcp_json_command
# Create a cyclopts app for install subcommands
@ -17,4 +18,5 @@ install_app = cyclopts.App(
install_app.command(claude_code_command, name="claude-code")
install_app.command(claude_desktop_command, name="claude-desktop")
install_app.command(cursor_command, name="cursor")
install_app.command(gemini_cli_command, name="gemini-cli")
install_app.command(mcp_json_command, name="mcp-json")

View file

@ -0,0 +1,250 @@
"""Gemini CLI integration for FastMCP install using Cyclopts."""
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Annotated
import cyclopts
from rich import print
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.mcp_server_config.v1.environments.uv import UVEnvironment
from .shared import process_common_args
logger = get_logger(__name__)
def find_gemini_command() -> str | None:
"""Find the Gemini CLI command."""
# First try shutil.which() in case it's a real executable in PATH
gemini_in_path = shutil.which("gemini")
if gemini_in_path:
try:
# If 'gemini --version' fails, it's not the correct path
subprocess.run(
[gemini_in_path, "--version"],
check=True,
capture_output=True,
)
return gemini_in_path
except (subprocess.CalledProcessError, FileNotFoundError):
pass
# Check common installation locations (aliases don't work with subprocess)
potential_paths = [
# Default Gemini CLI installation location (after migration)
Path.home() / ".gemini" / "local" / "gemini",
# npm global installation on macOS/Linux (default)
Path("/usr/local/bin/gemini"),
# npm global installation with custom prefix
Path.home() / ".npm-global" / "bin" / "gemini",
# Homebrew installation on macOS
Path("/opt/homebrew/bin/gemini"),
]
for path in potential_paths:
if path.exists():
# If 'gemini --version' fails, it's not the correct path
try:
subprocess.run(
[str(path), "--version"],
check=True,
capture_output=True,
)
return str(path)
except (subprocess.CalledProcessError, FileNotFoundError):
continue
return None
def check_gemini_cli_available() -> bool:
"""Check if Gemini CLI is available."""
return find_gemini_command() is not None
def install_gemini_cli(
file: Path,
server_object: str | None,
name: str,
*,
with_editable: list[Path] | None = None,
with_packages: list[str] | None = None,
env_vars: dict[str, str] | None = None,
python_version: str | None = None,
with_requirements: Path | None = None,
project: Path | None = None,
) -> bool:
"""Install FastMCP server in Gemini CLI.
Args:
file: Path to the server file
server_object: Optional server object name (for :object suffix)
name: Name for the server in Gemini CLI
with_editable: Optional list of directories to install in editable mode
with_packages: Optional list of additional packages to install
env_vars: Optional dictionary of environment variables
python_version: Optional Python version to use
with_requirements: Optional requirements file to install from
project: Optional project directory to run within
Returns:
True if installation was successful, False otherwise
"""
# Check if Gemini CLI is available
gemini_cmd = find_gemini_command()
if not gemini_cmd:
print(
"[red]Gemini CLI not found.[/red]\n"
"[blue]Please ensure Gemini CLI is installed. Try running 'gemini --version' to verify.[/blue]\n"
"[blue]You can install it using 'npm install -g @google/gemini-cli'.[/blue]\n"
)
return False
# Deduplicate packages and exclude 'fastmcp' since Environment adds it automatically
deduplicated_packages = None
if with_packages:
deduplicated = list(dict.fromkeys(with_packages))
deduplicated_packages = [pkg for pkg in deduplicated if pkg != "fastmcp"]
if not deduplicated_packages:
deduplicated_packages = None
# Build uv run command using Environment.build_uv_run_command()
env_config = UVEnvironment(
python=python_version,
dependencies=deduplicated_packages,
requirements=str(with_requirements) if with_requirements else None,
project=str(project) if project else None,
editable=[str(p) for p in with_editable] if with_editable else None,
)
# Build server spec from parsed components
if server_object:
server_spec = f"{file.resolve()}:{server_object}"
else:
server_spec = str(file.resolve())
# Build the full command
full_command = env_config.build_command(["fastmcp", "run", server_spec])
# Build gemini mcp add command
cmd_parts = [gemini_cmd, "mcp", "add"]
# Add environment variables if specified (before the name and command)
if env_vars:
for key, value in env_vars.items():
cmd_parts.extend(["-e", f"{key}={value}"])
# Add server name and command
cmd_parts.extend([name, full_command[0], "--"])
cmd_parts.extend(full_command[1:])
try:
# Run the gemini mcp add command
subprocess.run(cmd_parts, check=True, capture_output=True, text=True)
return True
except subprocess.CalledProcessError as e:
print(
f"[red]Failed to install '[bold]{name}[/bold]' in Gemini CLI: {e.stderr.strip() if e.stderr else str(e)}[/red]"
)
return False
except Exception as e:
print(f"[red]Failed to install '[bold]{name}[/bold]' in Gemini CLI: {e}[/red]")
return False
async def gemini_cli_command(
server_spec: str,
*,
server_name: Annotated[
str | None,
cyclopts.Parameter(
name=["--name", "-n"],
help="Custom name for the server in Gemini CLI",
),
] = None,
with_editable: Annotated[
list[Path] | None,
cyclopts.Parameter(
"--with-editable",
help="Directory with pyproject.toml to install in editable mode (can be used multiple times)",
negative="",
),
] = None,
with_packages: Annotated[
list[str] | None,
cyclopts.Parameter(
"--with",
help="Additional packages to install (can be used multiple times)",
negative="",
),
] = None,
env_vars: Annotated[
list[str] | None,
cyclopts.Parameter(
"--env",
help="Environment variables in KEY=VALUE format (can be used multiple times)",
negative="",
),
] = None,
env_file: Annotated[
Path | None,
cyclopts.Parameter(
"--env-file",
help="Load environment variables from .env file",
),
] = None,
python: Annotated[
str | None,
cyclopts.Parameter(
"--python",
help="Python version to use (e.g., 3.10, 3.11)",
),
] = None,
with_requirements: Annotated[
Path | None,
cyclopts.Parameter(
"--with-requirements",
help="Requirements file to install dependencies from",
),
] = None,
project: Annotated[
Path | None,
cyclopts.Parameter(
"--project",
help="Run the command within the given project directory",
),
] = None,
) -> None:
"""Install an MCP server in Gemini CLI.
Args:
server_spec: Python file to install, optionally with :object suffix
"""
# Convert None to empty lists for list parameters
with_editable = with_editable or []
with_packages = with_packages or []
env_vars = env_vars or []
file, server_object, name, packages, env_dict = await process_common_args(
server_spec, server_name, with_packages, env_vars, env_file
)
success = install_gemini_cli(
file=file,
server_object=server_object,
name=name,
with_editable=with_editable,
with_packages=packages,
env_vars=env_dict,
python_version=python,
with_requirements=with_requirements,
project=project,
)
if success:
print(f"[green]Successfully installed '{name}' in Gemini CLI")
else:
sys.exit(1)

View file

@ -24,6 +24,7 @@ class TestInstallApp:
install_app.parse_args(["claude-code", "--help"])
install_app.parse_args(["claude-desktop", "--help"])
install_app.parse_args(["cursor", "--help"])
install_app.parse_args(["gemini-cli", "--help"])
install_app.parse_args(["mcp-json", "--help"])
except SystemExit:
# Help commands exit with 0, that's expected
@ -184,6 +185,63 @@ class TestMcpJsonInstall:
assert bound.arguments["copy"] is True
class TestGeminiCliInstall:
"""Test gemini-cli install command."""
def test_gemini_cli_basic(self):
"""Test basic gemini-cli install command parsing."""
# Parse command with correct parameter names
command, bound, _ = install_app.parse_args(
["gemini-cli", "server.py", "--name", "test-server"]
)
# Verify parsing was successful
assert command is not None
assert bound.arguments["server_spec"] == "server.py"
assert bound.arguments["server_name"] == "test-server"
def test_gemini_cli_with_options(self):
"""Test gemini-cli install with various options."""
command, bound, _ = install_app.parse_args(
[
"gemini-cli",
"server.py",
"--name",
"test-server",
"--with",
"package1",
"--with",
"package2",
"--env",
"VAR1=value1",
]
)
assert bound.arguments["with_packages"] == ["package1", "package2"]
assert bound.arguments["env_vars"] == ["VAR1=value1"]
def test_gemini_cli_with_new_options(self):
"""Test gemini-cli install with new uv options."""
from pathlib import Path
command, bound, _ = install_app.parse_args(
[
"gemini-cli",
"server.py",
"--python",
"3.11",
"--project",
"/workspace",
"--with-requirements",
"requirements.txt",
]
)
assert bound.arguments["python"] == "3.11"
assert bound.arguments["project"] == Path("/workspace")
assert bound.arguments["with_requirements"] == Path("requirements.txt")
class TestInstallCommandParsing:
"""Test command parsing and error handling."""
@ -194,6 +252,7 @@ class TestInstallCommandParsing:
["claude-code", "server.py"],
["claude-desktop", "server.py"],
["cursor", "server.py"],
["gemini-cli", "server.py"],
]
for cmd_args in commands_to_test:
@ -214,6 +273,7 @@ class TestInstallCommandParsing:
["claude-code", "server.py", "--python", "3.11"],
["claude-desktop", "server.py", "--python", "3.11"],
["cursor", "server.py", "--python", "3.11"],
["gemini-cli", "server.py", "--python", "3.11"],
["mcp-json", "server.py", "--python", "3.11"],
]
@ -228,6 +288,7 @@ class TestInstallCommandParsing:
["claude-code", "server.py", "--with-requirements", "requirements.txt"],
["claude-desktop", "server.py", "--with-requirements", "requirements.txt"],
["cursor", "server.py", "--with-requirements", "requirements.txt"],
["gemini-cli", "server.py", "--with-requirements", "requirements.txt"],
["mcp-json", "server.py", "--with-requirements", "requirements.txt"],
]
@ -242,6 +303,7 @@ class TestInstallCommandParsing:
["claude-code", "server.py", "--project", "/path/to/project"],
["claude-desktop", "server.py", "--project", "/path/to/project"],
["cursor", "server.py", "--project", "/path/to/project"],
["gemini-cli", "server.py", "--project", "/path/to/project"],
["mcp-json", "server.py", "--project", "/path/to/project"],
]