Skip to main content
Glama
eLyiN
by eLyiN

Gemini Bridge

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

Легковесный MCP-сервер (Model Context Protocol), позволяющий ИИ-ассистентам для программирования взаимодействовать с Google Gemini AI через официальный CLI. Работает с Claude Code, Cursor, VS Code и другими MCP-совместимыми клиентами. Разработан для простоты, надежности и бесшовной интеграции.

✨ Возможности

  • Прямая интеграция с Gemini CLI: Нулевые затраты на API при использовании официального Gemini CLI

  • Три MCP-инструмента: Базовые запросы, анализ файлов и возможности веб-поиска

  • Работа без сохранения состояния: Нет сессий, кэширования или сложного управления состоянием

  • Готовность к продакшену: Надежная обработка ошибок с настраиваемыми 60-секундными таймаутами

  • Минимальные зависимости: Требуются только mcp>=1.0.0 и Gemini CLI

  • Простое развертывание: Поддержка как uvx, так и традиционной установки через pip

  • Универсальная MCP-совместимость: Работает с любым MCP-совместимым ИИ-ассистентом для программирования

  • Современный Python: Использует pathlib и современные подсказки типов (Python 3.10+)

Related MCP server: Globalping

🚀 Быстрый старт

Предварительные требования

  1. Установите Gemini CLI:

    npm install -g @google/gemini-cli
  2. Авторизуйтесь в Gemini:

    gemini auth login
  3. Проверьте установку:

    gemini --version

Установка

🎯 Рекомендуется: Установка через 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

Альтернатива: Из исходного кода

# 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

Установка для разработки

# 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

🌐 Поддержка нескольких клиентов

Gemini Bridge работает с любым MCP-совместимым ИИ-ассистентом для программирования — один и тот же сервер поддерживает несколько клиентов через различные методы конфигурации.

Поддерживаемые MCP-клиенты

  • Claude Code ✅ (По умолчанию)

  • Cursor ✅

  • VS Code ✅

  • Windsurf ✅

  • Cline ✅

  • Void ✅

  • Cherry Studio ✅

  • Augment ✅

  • Roo Code ✅

  • Zencoder ✅

  • Любой MCP-совместимый клиент ✅

Примеры конфигурации

# 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

Глобальная конфигурация (~/.cursor/mcp.json):

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

Специфичная для проекта (.cursor/mcp.json в вашем проекте):

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

Перейдите в: Settings → Cursor Settings → MCP → Add new global MCP server

Конфигурация (.vscode/mcp.json в вашей рабочей области):

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

Альтернатива: Через расширения

  1. Откройте представление расширений (Ctrl+Shift+X)

  2. Найдите MCP-расширения

  3. Добавьте пользовательский сервер с командой: uvx gemini-bridge

Добавьте в конфигурацию MCP Windsurf:

{
  "mcpServers": {
    "gemini-bridge": {
      "command": "uvx",
      "args": ["gemini-bridge"],
      "env": {}
    }
  }
}
  1. Откройте Cline и нажмите MCP Servers в верхней навигации

  2. Выберите вкладку Installed → Advanced MCP Settings

  3. Добавьте в cline_mcp_settings.json:

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

Перейдите в: Settings → MCP → Add MCP Server

{
  "mcpServers": {
    "gemini-bridge": {
      "command": "uvx",
      "args": ["gemini-bridge"],
      "env": {}
    }
  }
}
  1. Перейдите в Settings → MCP Servers → Add Server

  2. Заполните данные сервера:

    • Name: gemini-bridge

    • Type: STDIO

    • Command: uvx

    • Arguments: ["gemini-bridge"]

  3. Сохраните конфигурацию

Использование интерфейса:

  1. Нажмите на меню-гамбургер → Settings → Tools

  2. Нажмите кнопку + Add MCP

  3. Введите команду: uvx gemini-bridge

  4. Имя: Gemini Bridge

Ручная конфигурация:

"augment.advanced": { 
  "mcpServers": [ 
    { 
      "name": "gemini-bridge", 
      "command": "uvx", 
      "args": ["gemini-bridge"],
      "env": {}
    }
  ]
}
  1. Перейдите в Settings → MCP Servers → Edit Global Config

  2. Добавьте в mcp_settings.json:

{
  "mcpServers": {
    "gemini-bridge": {
      "command": "uvx",
      "args": ["gemini-bridge"],
      "env": {}
    }
  }
}
  1. Перейдите в меню Zencoder (...) → Tools → Add Custom MCP

  2. Добавьте конфигурацию:

{
  "command": "uvx",
  "args": ["gemini-bridge"],
  "env": {}
}
  1. Нажмите кнопку Install

Для установок на базе pip:

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

Для разработки/локального тестирования:

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

Для установки в стиле npm (если необходимо):

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

Универсальное использование

После настройки с любым клиентом используйте те же два инструмента:

  1. Задавайте общие вопросы: "Какие шаблоны аутентификации используются в этой кодовой базе?"

  2. Анализируйте конкретные файлы: "Проверь эти файлы аутентификации на наличие проблем с безопасностью"

Реализация сервера идентична — отличается только конфигурация клиента!

⚙️ Конфигурация

Настройка таймаута

По умолчанию Gemini Bridge использует 60-секундный таймаут для всех операций CLI. Для более длительных запросов (большие файлы, сложный анализ) вы можете настроить собственный таймаут с помощью переменной окружения GEMINI_BRIDGE_TIMEOUT.

Примеры конфигурации:

# 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"
      }
    }
  }
}

Опции таймаута:

  • По умолчанию: 60 секунд (если не настроено)

  • Диапазон: Любое положительное целое число (секунды)

  • Переопределение для вызова: Укажите timeout_seconds для любого инструмента для разового расширения

  • Рекомендуется: 120-300 секунд для анализа больших файлов

  • Некорректные значения: Возврат к 60 секундам с предупреждением

🛠️ Доступные инструменты

consult_gemini

Прямой CLI-мост для простых запросов.

Параметры:

  • query (строка): Вопрос или промпт для отправки в Gemini

  • directory (строка): Рабочая директория для запроса

  • model (строка, опционально): Модель для использования - "flash", "pro", "flash-lite", "2.5-lite", "3-pro", "3-flash", "3.1-pro", "3.1-flash-lite" или "auto" (по умолчанию: "flash")

  • timeout_seconds (целое число, опционально): Переопределение таймаута выполнения для этого запроса

Пример:

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

consult_gemini_with_files

CLI-мост с вложениями файлов для детального анализа.

Параметры:

  • query (строка): Вопрос или промпт для отправки в Gemini

  • directory (строка): Рабочая директория для запроса

  • files (список): Список путей к файлам относительно директории

  • model (строка, опционально): Модель для использования - "flash", "pro", "flash-lite", "2.5-lite", "3-pro", "3-flash", "3.1-pro", "3.1-flash-lite" или "auto" (по умолчанию: "flash")

  • timeout_seconds (целое число, опционально): Переопределение таймаута выполнения для этого запроса

  • mode (строка, опционально): Либо "inline" (по умолчанию) для потоковой передачи содержимого файлов, либо "at_command", чтобы позволить Gemini CLI самостоятельно разрешать ссылки @path

Пример:

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
)

Совет: При сканировании больших деревьев переключитесь на mode="at_command", чтобы Gemini CLI самостоятельно обрабатывал раскрытие путей (globbing) и усечение файлов.

Задавайте Gemini вопросы с контекстом веб-поиска. Использует автоматический веб-поиск Gemini CLI, когда модель определяет, что это необходимо. Функциональность "как есть" — не гарантируется для каждого запроса.

Параметры:

  • query (строка): Поисковый запрос или вопрос для поиска в сети

  • directory (строка): Рабочая директория для выполнения команды

  • model (строка, опционально): Модель для использования - "flash", "pro", "flash-lite", "2.5-lite", "3-pro", "3-flash", "3.1-pro", "3.1-flash-lite" или "auto" (по умолчанию: "flash")

  • timeout_seconds (целое число, опционально): Переопределение таймаута выполнения для этого запроса

Пример:

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

📋 Примеры использования

Базовый анализ кода

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

Детальный обзор файла

# 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"
)

Анализ нескольких файлов

# 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"
)

Веб-поиск

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

Меры предосторожности для больших файлов

  • Встроенные передачи ограничены ~256 КБ на файл и ~512 КБ на запрос, чтобы избежать зависаний.

  • Файлы слишком большого размера усекаются до фрагментов начала/конца с предупреждением в ответе MCP.

  • Настраивайте ограничения с помощью переменных окружения (GEMINI_BRIDGE_MAX_INLINE_TOTAL_BYTES и т.д.) или отдавайте предпочтение mode="at_command" для больших полезных нагрузок.

🏗️ Архитектура

Основной дизайн

  • CLI-First: Прямые вызовы подпроцессов к команде gemini

  • Без сохранения состояния: Каждый вызов инструмента независим, без состояния сессии

  • Адаптивный таймаут: По умолчанию 60 секунд, но переопределяется для каждого запроса или через переменную окружения

  • Ограничения вложений: Режим inline обеспечивает легкие ограничения; режим @ делегирует работу инструментам Gemini CLI

  • Простая обработка ошибок: Понятные сообщения об ошибках с подходом быстрого отказа

Структура проекта

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

🔧 Разработка

Локальное тестирование

# Install in development mode
pip install -e .

# Run directly
python -m src

# Test CLI availability
gemini --version

Интеграция с Claude Code

Сервер автоматически интегрируется с Claude Code при правильной настройке через протокол MCP.

🔍 Устранение неполадок

CLI недоступен

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

# Authenticate
gemini auth login

# Test
gemini --version

Проблемы с подключением

  • Проверьте, правильно ли авторизован Gemini CLI

  • Проверьте сетевое подключение

  • Убедитесь, что конфигурация MCP Claude Code верна

  • Проверьте, находится ли команда gemini в вашем PATH

Распространенные сообщения об ошибках

  • "CLI not available": Gemini CLI не установлен или отсутствует в PATH

  • "Authentication required": Выполните gemini auth login

  • "Timeout after 60 seconds": Запрос выполнялся слишком долго, попробуйте разбить его на части

🤝 Участие в разработке

Мы приветствуем вклад сообщества! Пожалуйста, ознакомьтесь с нашими Руководством по участию для получения подробной информации о том, как начать.

Краткое руководство по участию

  1. Сделайте форк репозитория

  2. Создайте ветку для функции

  3. Внесите изменения

  4. Добавьте тесты, если применимо

  5. Отправьте pull request

📄 Лицензия

Этот проект лицензирован по лицензии MIT — подробности см. в файле LICENSE.

🔄 История версий

Подробную историю версий см. в CHANGELOG.md.

🆘 Поддержка

  • Проблемы: Сообщайте об ошибках или запрашивайте функции через GitHub Issues

  • Обсуждения: Присоединяйтесь к обсуждению в сообществе

  • Документация: Дополнительная документация может быть создана в директории docs/


Фокус: Простой, надежный мост между Claude Code и Gemini AI через официальный CLI.

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