Skip to main content
Glama
eLyiN
by eLyiN

Gemini Bridge

CI Status PyPI Version MIT License Python 3.10+ MCP Compatible Gemini CLI

Un servidor MCP (Model Context Protocol) ligero que permite a los asistentes de codificación de IA interactuar con la IA Gemini de Google a través de la CLI oficial. Funciona con Claude Code, Cursor, VS Code y otros clientes compatibles con MCP. Diseñado para la simplicidad, la fiabilidad y una integración fluida.

✨ Características

  • Integración directa con Gemini CLI: Costes de API cero utilizando la CLI oficial de Gemini

  • Tres herramientas MCP: Consultas básicas, análisis de archivos y capacidades de búsqueda web

  • Operación sin estado: Sin sesiones, almacenamiento en caché ni gestión compleja de estados

  • Listo para producción: Manejo robusto de errores con tiempos de espera configurables de 60 segundos

  • Dependencias mínimas: Solo requiere mcp>=1.0.0 y Gemini CLI

  • Despliegue sencillo: Soporte tanto para uvx como para la instalación tradicional con pip

  • Compatibilidad universal con MCP: Funciona con cualquier asistente de codificación de IA compatible con MCP

  • Python moderno: Utiliza pathlib y sugerencias de tipo modernas (Python 3.10+)

Related MCP server: Globalping

🚀 Inicio rápido

Requisitos previos

  1. Instalar Gemini CLI:

    npm install -g @google/gemini-cli
  2. Autenticarse con Gemini:

    gemini auth login
  3. Verificar la instalación:

    gemini --version

Instalación

🎯 Recomendado: Instalación mediante PyPI

# Install from PyPI
pip install gemini-bridge

# Add to Claude Code with uvx (recommended)
claude mcp add gemini-bridge -s user -- uvx gemini-bridge

Alternativa: Desde el código fuente

# Clone the repository
git clone https://github.com/shelakh/gemini-bridge.git
cd gemini-bridge

# Build and install locally
uvx --from build pyproject-build
pip install dist/*.whl

# Add to Claude Code
claude mcp add gemini-bridge -s user -- uvx gemini-bridge

Instalación para desarrollo

# Clone and install in development mode
git clone https://github.com/shelakh/gemini-bridge.git
cd gemini-bridge
pip install -e .

# Add to Claude Code (development)
claude mcp add gemini-bridge-dev -s user -- python -m src

🌐 Soporte multi-cliente

Gemini Bridge funciona con cualquier asistente de codificación de IA compatible con MCP: el mismo servidor admite múltiples clientes a través de diferentes métodos de configuración.

Clientes MCP compatibles

  • Claude Code ✅ (Predeterminado)

  • Cursor ✅

  • VS Code ✅

  • Windsurf ✅

  • Cline ✅

  • Void ✅

  • Cherry Studio ✅

  • Augment ✅

  • Roo Code ✅

  • Zencoder ✅

  • Cualquier cliente compatible con MCP ✅

Ejemplos de configuración

# Recommended installation
claude mcp add gemini-bridge -s user -- uvx gemini-bridge

# Development installation
claude mcp add gemini-bridge-dev -s user -- python -m src

Configuración global (~/.cursor/mcp.json):

{
  "mcpServers": {
    "gemini-bridge": {
      "command": "uvx",
      "args": ["gemini-bridge"],
      "env": {}
    }
  }
}

Específica del proyecto (.cursor/mcp.json en su proyecto):

{
  "mcpServers": {
    "gemini-bridge": {
      "command": "uvx",
      "args": ["gemini-bridge"],
      "env": {}
    }
  }
}

Vaya a: Settings → Cursor Settings → MCP → Add new global MCP server

Configuración (.vscode/mcp.json en su espacio de trabajo):

{
  "servers": {
    "gemini-bridge": {
      "type": "stdio",
      "command": "uvx",
      "args": ["gemini-bridge"]
    }
  }
}

Alternativa: A través de extensiones

  1. Abra la vista de Extensiones (Ctrl+Shift+X)

  2. Busque extensiones MCP

  3. Añada un servidor personalizado con el comando: uvx gemini-bridge

Añada a su configuración MCP de Windsurf:

{
  "mcpServers": {
    "gemini-bridge": {
      "command": "uvx",
      "args": ["gemini-bridge"],
      "env": {}
    }
  }
}
  1. Abra Cline y haga clic en MCP Servers en la navegación superior

  2. Seleccione la pestaña Installed → Advanced MCP Settings

  3. Añada a cline_mcp_settings.json:

{
  "mcpServers": {
    "gemini-bridge": {
      "command": "uvx",
      "args": ["gemini-bridge"],
      "env": {}
    }
  }
}

Vaya a: Settings → MCP → Add MCP Server

{
  "mcpServers": {
    "gemini-bridge": {
      "command": "uvx",
      "args": ["gemini-bridge"],
      "env": {}
    }
  }
}
  1. Navegue a Settings → MCP Servers → Add Server

  2. Rellene los detalles del servidor:

    • Name: gemini-bridge

    • Type: STDIO

    • Command: uvx

    • Arguments: ["gemini-bridge"]

  3. Guarde la configuración

Usando la interfaz de usuario:

  1. Haga clic en el menú hamburguesa → Settings → Tools

  2. Haga clic en el botón + Add MCP

  3. Introduzca el comando: uvx gemini-bridge

  4. Nombre: Gemini Bridge

Configuración manual:

"augment.advanced": { 
  "mcpServers": [ 
    { 
      "name": "gemini-bridge", 
      "command": "uvx", 
      "args": ["gemini-bridge"],
      "env": {}
    }
  ]
}
  1. Vaya a Settings → MCP Servers → Edit Global Config

  2. Añada a mcp_settings.json:

{
  "mcpServers": {
    "gemini-bridge": {
      "command": "uvx",
      "args": ["gemini-bridge"],
      "env": {}
    }
  }
}
  1. Vaya al menú de Zencoder (...) → Tools → Add Custom MCP

  2. Añada la configuración:

{
  "command": "uvx",
  "args": ["gemini-bridge"],
  "env": {}
}
  1. Pulse el botón Install

Para instalaciones basadas en pip:

{
  "command": "gemini-bridge",
  "args": [],
  "env": {}
}

Para desarrollo/pruebas locales:

{
  "command": "python",
  "args": ["-m", "src"],
  "env": {},
  "cwd": "/path/to/gemini-bridge"
}

Para instalación estilo npm (si es necesario):

{
  "command": "npx",
  "args": ["gemini-bridge"],
  "env": {}
}

Uso universal

Una vez configurado con cualquier cliente, utilice las mismas dos herramientas:

  1. Hacer preguntas generales: "¿Qué patrones de autenticación se utilizan en esta base de código?"

  2. Analizar archivos específicos: "Revisa estos archivos de autenticación en busca de problemas de seguridad"

La implementación del servidor es idéntica: ¡solo difiere la configuración del cliente!

⚙️ Configuración

Configuración del tiempo de espera (Timeout)

Por defecto, Gemini Bridge utiliza un tiempo de espera de 60 segundos para todas las operaciones de la CLI. Para consultas más largas (archivos grandes, análisis complejos), puede configurar un tiempo de espera personalizado utilizando la variable de entorno GEMINI_BRIDGE_TIMEOUT.

Ejemplos de configuración:

# Add with custom timeout (120 seconds)
claude mcp add gemini-bridge -s user --env GEMINI_BRIDGE_TIMEOUT=120 -- uvx gemini-bridge
{
  "mcpServers": {
    "gemini-bridge": {
      "command": "uvx",
      "args": ["gemini-bridge"],
      "env": {
        "GEMINI_BRIDGE_TIMEOUT": "120"
      }
    }
  }
}

Opciones de tiempo de espera:

  • Predeterminado: 60 segundos (si no se configura)

  • Rango: Cualquier número entero positivo (segundos)

  • Anulación por llamada: Proporcione timeout_seconds a cualquiera de las herramientas para extensiones puntuales

  • Recomendado: 120-300 segundos para análisis de archivos grandes

  • Valores no válidos: Se vuelve a los 60 segundos con una advertencia

🛠️ Herramientas disponibles

consult_gemini

Puente directo de CLI para consultas simples.

Parámetros:

  • query (string): La pregunta o prompt para enviar a Gemini

  • directory (string): Directorio de trabajo para la consulta

  • model (string, opcional): Modelo a utilizar - "flash", "pro", "flash-lite", "2.5-lite", "3-pro", "3-flash", "3.1-pro", "3.1-flash-lite", o "auto" (predeterminado: "flash")

  • timeout_seconds (int, opcional): Anular el tiempo de espera de ejecución para esta solicitud

Ejemplo:

consult_gemini(
    query="Find authentication patterns in this codebase",
    directory="/path/to/project",
    model="flash"
)

consult_gemini_with_files

Puente de CLI con archivos adjuntos para un análisis detallado.

Parámetros:

  • query (string): La pregunta o prompt para enviar a Gemini

  • directory (string): Directorio de trabajo para la consulta

  • files (list): Lista de rutas de archivos relativas al directorio

  • model (string, opcional): Modelo a utilizar - "flash", "pro", "flash-lite", "2.5-lite", "3-pro", "3-flash", "3.1-pro", "3.1-flash-lite", o "auto" (predeterminado: "flash")

  • timeout_seconds (int, opcional): Anular el tiempo de espera de ejecución para esta solicitud

  • mode (string, opcional): Ya sea "inline" (predeterminado) para transmitir el contenido del archivo o "at_command" para dejar que la CLI de Gemini resuelva las referencias @path por sí misma

Ejemplo:

consult_gemini_with_files(
    query="Analyze these auth files and suggest improvements",
    directory="/path/to/project",
    files=["src/auth.py", "src/models.py"],
    model="pro",
    timeout_seconds=180
)

Consejo: Al escanear árboles grandes, cambie a mode="at_command" para que la CLI de Gemini maneje el globbing y el truncamiento de archivos de forma nativa.

Realice consultas a Gemini con contexto de búsqueda web. Utiliza la búsqueda web automática de la CLI de Gemini cuando el modelo determina que es necesaria. Funcionalidad de mejor esfuerzo: no garantizada para todas las consultas.

Parámetros:

  • query (string): Consulta de búsqueda o pregunta para buscar en la web

  • directory (string): Directorio de trabajo para la ejecución del comando

  • model (string, opcional): Modelo a utilizar - "flash", "pro", "flash-lite", "2.5-lite", "3-pro", "3-flash", "3.1-pro", "3.1-flash-lite", o "auto" (predeterminado: "flash")

  • timeout_seconds (int, opcional): Anular el tiempo de espera de ejecución para esta solicitud

Ejemplo:

web_search(
    query="latest Python version and new features",
    model="flash"
)

📋 Ejemplos de uso

Análisis de código básico

# Simple research query
consult_gemini(
    query="What authentication patterns are used in this project?",
    directory="/Users/dev/my-project"
)

Revisión detallada de archivos

# Analyze specific files
consult_gemini_with_files(
    query="Review these files and suggest security improvements",
    directory="/Users/dev/my-project",
    files=["src/auth.py", "src/middleware.py"],
    model="pro"
)

Análisis de múltiples archivos

# Compare multiple implementation files
consult_gemini_with_files(
    query="Compare these database implementations and recommend the best approach",
    directory="/Users/dev/my-project",
    files=["src/db/postgres.py", "src/db/sqlite.py", "src/db/redis.py"],
    mode="at_command"
)

Búsqueda web

# Get current information from the web
web_search(
    query="latest Python version and new features in 3.13",
    model="flash"
)

Salvaguardas para archivos grandes

  • Las transferencias en línea tienen un límite de ~256 KB por archivo y ~512 KB por solicitud para evitar bloqueos.

  • Los archivos de gran tamaño se truncan a fragmentos de inicio/fin con una advertencia en la respuesta MCP.

  • Ajuste los límites con variables de entorno (GEMINI_BRIDGE_MAX_INLINE_TOTAL_BYTES, etc.) o prefiera mode="at_command" para cargas útiles más grandes.

🏗️ Arquitectura

Diseño central

  • CLI-First: Llamadas directas de subprocesos al comando gemini

  • Sin estado: Cada llamada a la herramienta es independiente sin estado de sesión

  • Tiempo de espera adaptativo: Predeterminado a 60 segundos pero anulable por solicitud o mediante variable de entorno

  • Barandillas de archivos adjuntos: El modo en línea impone límites ligeros; el modo @ delega en las herramientas de la CLI de Gemini

  • Manejo simple de errores: Mensajes de error claros con un enfoque de fallo rápido

Estructura del proyecto

gemini-bridge/
├── src/
│   ├── __init__.py              # Entry point
│   ├── __main__.py              # Module execution entry point
│   └── mcp_server.py            # Main MCP server implementation
├── .github/                     # GitHub templates and workflows
├── pyproject.toml              # Python package configuration
├── README.md                   # This file
├── CONTRIBUTING.md             # Contribution guidelines
├── CODE_OF_CONDUCT.md          # Community standards
├── SECURITY.md                 # Security policies
├── CHANGELOG.md               # Version history
└── LICENSE                    # MIT license

🔧 Desarrollo

Pruebas locales

# Install in development mode
pip install -e .

# Run directly
python -m src

# Test CLI availability
gemini --version

Integración con Claude Code

El servidor se integra automáticamente con Claude Code cuando se configura correctamente a través del protocolo MCP.

🔍 Solución de problemas

CLI no disponible

# Install Gemini CLI
npm install -g @google/gemini-cli

# Authenticate
gemini auth login

# Test
gemini --version

Problemas de conexión

  • Verifique que la CLI de Gemini esté correctamente autenticada

  • Compruebe la conectividad de red

  • Asegúrese de que la configuración MCP de Claude Code sea correcta

  • Compruebe que el comando gemini esté en su PATH

Mensajes de error comunes

  • "CLI not available": La CLI de Gemini no está instalada o no está en el PATH

  • "Authentication required": Ejecute gemini auth login

  • "Timeout after 60 seconds": La consulta tardó demasiado, intente dividirla en partes más pequeñas

🤝 Contribución

¡Damos la bienvenida a las contribuciones de la comunidad! Por favor, lea nuestras Directrices de contribución para obtener detalles sobre cómo empezar.

Guía rápida de contribución

  1. Haga un fork del repositorio

  2. Cree una rama de características

  3. Realice sus cambios

  4. Añada pruebas si corresponde

  5. Envíe una solicitud de extracción (pull request)

📄 Licencia

Este proyecto está bajo la Licencia MIT: consulte el archivo LICENSE para obtener más detalles.

🔄 Historial de versiones

Consulte CHANGELOG.md para obtener un historial de versiones detallado.

🆘 Soporte

  • Problemas: Informe de errores o solicite funciones a través de GitHub Issues

  • Discusiones: Únase a la discusión de la comunidad

  • Documentación: Se puede crear documentación adicional en el directorio docs/


Enfoque: Un puente simple y fiable entre Claude Code y Gemini AI a través de la CLI oficial.

Available Tools

3 tools
consult_geminiA

Send a query directly to the Gemini CLI.

Args:
    query: Prompt text forwarded verbatim to the CLI.
    directory: Working directory used for command execution.
    model: Optional model alias (``flash``, ``pro``) or full Gemini model id.
    timeout_seconds: Optional per-call timeout override in seconds.

Returns:
    Gemini's response text or an explanatory error string.
ParametersJSON Schema
NameRequiredDescriptionDefault
modelNo
queryYes
directoryYes
timeout_secondsNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.1/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description discloses that the query is 'forwarded verbatim to the CLI', explains optional parameters (model, timeout), and describes the return value as 'Gemini's response text or an explanatory error string'. This provides sufficient behavioral context for a query tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with Args/Returns sections and no extraneous content. It is concise but includes necessary parameter details. Minor tightening could improve it, but overall effective.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (4 params, 2 required) and presence of an output schema (implied by return description), the description covers the key behavioral aspects. It explains inputs, optional overrides, and return value, making it complete enough for effective use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 0% description coverage, so the description carries the burden. It explains all four parameters: query (prompt text), directory (working directory), model (optional alias or ID), timeout_seconds (per-call override). This adds meaning beyond the schema's raw type definitions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states 'Send a query directly to the Gemini CLI', specifying the verb (send) and resource (Gemini CLI). The name 'consult_gemini' and sibling tools 'consult_gemini_with_files' and 'web_search' help distinguish its purpose as a direct query without file context.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description does not explicitly mention when to use this tool vs. 'consult_gemini_with_files' or 'web_search'. It only implies usage for direct queries without files, lacking alternative guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

consult_gemini_with_filesA

Send a query to the Gemini CLI with file context.

Args:
    query: Prompt text forwarded to the CLI.
    directory: Working directory used for resolving relative file paths.
    files: File paths to include alongside the prompt. Paths must resolve
        inside ``directory``; entries pointing outside it are skipped.
    model: Optional model alias (``flash``, ``pro``) or full Gemini model id.
    timeout_seconds: Optional per-call timeout override in seconds.
    mode: ``"inline"`` streams truncated snippets; ``"at_command"`` emits
        ``@path`` directives so Gemini CLI resolves files itself.

Returns:
    Gemini's response or an explanatory error string with any warnings.
ParametersJSON Schema
NameRequiredDescriptionDefault
modeNoinline
filesNo
modelNo
queryYes
directoryYes
timeout_secondsNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden and does well: it discloses that files outside the working directory are silently skipped, that errors are returned as explanatory strings with warnings, and that per-call timeouts are possible. It stops short of stating auth/network prerequisites or what triggers truncation limits.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Front-loaded one-line summary followed by structured Args/Returns sections; each parameter line earns its place. The Returns block partially duplicates the output schema but is short enough not to be wasteful.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a 6-parameter external-CLI tool, all parameters and the path-safety rule are covered, and an output schema exists so return values need little prose. The main gap is the absent routing guidance versus consult_gemini and no discussion of limits when many/large files are passed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0% and the schema even lacks enum metadata, so the description must compensate fully — and it does, defining mode values ('inline' streams truncated snippets vs 'at_command' emits @path directives), model aliases (flash/pro), the path-resolution constraint on files, and the purpose of directory and timeout overrides.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

States a specific verb and resource ('Send a query to the Gemini CLI with file context'), which clearly separates it from the sibling consult_gemini that lacks file context. It is clear, but it never explicitly contrasts itself with that sibling or names when file context is needed.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No explicit when-to-use/when-not guidance or named alternative is given; the agent must infer from the tool name that files-bearing queries belong here rather than in consult_gemini. The mode explanation implies usage patterns but does not state selection criteria.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 1 tool updatev1.3.0
    • Addedweb_search
  2. 2 tool updatesv1.0.0
    • Changedconsult_gemini1 field changed
      • addedInput schema / properties / timeout_seconds
        Added value: +{
        +  "anyOf": [
        +    {
        +      "type": "integer"
        +    },
        +    {
        +      "type": "null"
        +    }
        +  ],
        +  "default": null,
        +  "title": "Timeout Seconds"
        +}
    • Changedconsult_gemini_with_files2 fields changed
      • addedInput schema / properties / mode
        Added value: +{
        +  "default": "inline",
        +  "title": "Mode",
        +  "type": "string"
        +}
      • addedInput schema / properties / timeout_seconds
        Added value: +{
        +  "anyOf": [
        +    {
        +      "type": "integer"
        +    },
        +    {
        +      "type": "null"
        +    }
        +  ],
        +  "default": null,
        +  "title": "Timeout Seconds"
        +}
  3. 2 tool updates
    • First observedconsult_gemini
    • First observedconsult_gemini_with_files

TDQS

A4.1/5.0

Scored across 3 tools

Disambiguation4/5

The three tools are mostly distinguishable: consult_gemini is plain, consult_gemini_with_files adds file context, and web_search adds search context. The overlap between the two consult_* tools is real—they differ only by file arguments—but the file/web/plain split gives an agent a reasonable basis for selection.

Naming Consistency4/5

Two tools follow a clean consult_gemini / consult_gemini_with_files pattern, and web_search is a readable verb_noun name. The only deviation is web_search not carrying the consult_ prefix, but it describes a genuinely different capability so it still reads consistently.

Tool Count4/5

Three tools is well-scoped for a thin bridge to a single CLI. Each tool maps to a distinct query mode rather than padding the surface, though the small count sits at the lower edge of the ideal range.

Completeness4/5

For a Gemini CLI passthrough the surface covers the main workflows: plain queries, file-context queries, and web-grounded queries. Minor gaps exist (no streaming/session continuity or config/inspection tool), but agents can accomplish the core task set without dead ends.

Maintenance

ActivityMaintained
ResponsivenessUnresponsive

Related MCP Connectors

Related MCP Servers