Логотип Gemini MCP 服务器

Gemini MCP 服务器

Сообщество
kousen

Wraps Gemini 2.5 flash in an MCP server

Издательkousen
РепозиторийGeminiMcpServer
ЯзыкJava
Форки
5
Звёзды
15
Доступные инструменты
0
Тип транспортаstdio
Категории
ЛицензияMIT
Ссылки
  • Подключайте инструменты к рабочим процессам с ИИ

    Gemini MCP 服务器 предоставляет возможности MCP, доступные совместимым ИИ-клиентам и агентам.

  • Доступные инструменты: 0

    Ниже представлены доступные для вызова действия с названиями и описаниями, если сервер их предоставляет.

  • Готовая конфигурация для копирования

    Используйте примеры конфигурации, чтобы настроить этот сервер в предпочитаемом MCP-клиенте.

  • Показатели интереса к открытому проекту

    Звёзды: 15, форки: 5 — в связанном репозитории.

Gemini MCP Server

A Spring Boot-based Model Context Protocol (MCP) server that enables MCP clients to leverage Google Gemini's large context window for codebase analysis. This server acts as a bridge between MCP clients (like Claude Desktop, Cursor, or Claude Code) and Google Gemini, allowing you to offload large codebase analysis tasks to Gemini while preserving your primary assistant's context window.

Overview

This MCP server provides two main tools:

  • gemini_scanAndPlan: Scans a codebase and creates an analysis plan, with support for file filtering, size limits, and automatic sharding for large projects
  • gemini_analyzeCodebase: Executes codebase analysis using the Gemini CLI with the scanned files

Key Features

  • 🎯 Smart File Selection: Include/exclude patterns for precise file filtering
  • 📦 Automatic Sharding: Splits large codebases into manageable chunks (though rarely needed with Gemini's 1M+ token context)
  • 🚫 Binary File Detection: Automatically skips binary files to avoid token waste
  • 📊 Size Management: Configurable file and byte limits
  • 🔧 Spring Boot Integration: Built on Spring AI's MCP server framework
  • ✅ Comprehensive Testing: Full test coverage with unit and integration tests
  • 🚀 Gemini 2.5 Flash: Always uses gemini-2.5-flash model for maximum context (1M tokens)
  • 📁 Context Inclusion: Uses Gemini CLI's -a flag to include all project files in analysis

Prerequisites

  • Java 21 or higher
  • Google Gemini CLI installed (gemini command available in PATH)
  • Gemini API key configured (set via environment variable or Gemini CLI config)

Installing Gemini CLI

bash
# For macOS with Homebrew:
brew install gemini

# Verify installation:
which gemini  # Should show /opt/homebrew/bin/gemini or similar
gemini --version

# Configure your API key (if not already done):
export GEMINI_API_KEY="your-api-key-here"

Installation

  1. Clone the repository:
bash
git clone <repository-url>
cd GeminiMcpServer
  1. Build the project:
bash
./gradlew build
  1. Run tests to verify everything works:
bash
./gradlew test

Configuration

Building the Server

Important: You don't need to run the server manually! MCP clients will automatically start and manage the server process. You only need to build it:

bash
# Build the executable JAR (this is all you need to do!)
./gradlew bootJar

# The JAR will be created at: build/libs/GeminiMcpServer-0.0.1-SNAPSHOT.jar

The commands below are only for testing/debugging purposes:

bash
# For testing: Run via Gradle
./gradlew bootRun

# For testing: Run the JAR directly
java -jar build/libs/GeminiMcpServer-0.0.1-SNAPSHOT.jar

MCP Client Configuration

Once you've built the JAR, configure your MCP client to use it. The client will handle starting and stopping the server automatically.

Claude Desktop / Cursor

Add the following to your Claude Desktop or Cursor MCP configuration file:

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json Windows: %APPDATA%\Claude\claude_desktop_config.json Linux: ~/.config/Claude/claude_desktop_config.json

json
{
  "mcpServers": {
    "gemini-analyzer": {
      "command": "java",
      "args": [
        "-jar",
        "/path/to/GeminiMcpServer/build/libs/GeminiMcpServer-0.0.1-SNAPSHOT.jar"
      ],
      "env": {
        "GEMINI_API_KEY": "your-api-key-here"  // Optional if configured in Gemini CLI
      }
    }
  }
}

Claude Code

You can add the MCP server to Claude Code in two ways:

Option 1: Via Command Line (Recommended)

bash
# Add to current project only (stored in .claude/)
claude mcp add gemini-analyzer -- java -jar /path/to/GeminiMcpServer/build/libs/GeminiMcpServer-0.0.1-SNAPSHOT.jar

# Or add to project and commit to version control
claude mcp add gemini-analyzer --scope project -- java -jar /path/to/GeminiMcpServer/build/libs/GeminiMcpServer-0.0.1-SNAPSHOT.jar

# Or add globally for all projects
claude mcp add gemini-analyzer --scope user -- java -jar /path/to/GeminiMcpServer/build/libs/GeminiMcpServer-0.0.1-SNAPSHOT.jar

Option 2: Manual Configuration

Create or edit .mcp.json in your project root:

json
{
  "mcpServers": {
    "gemini-analyzer": {
      "command": "java",
      "args": [
        "-jar",
        "/path/to/GeminiMcpServer/build/libs/GeminiMcpServer-0.0.1-SNAPSHOT.jar"
      ],
      "env": {}
    }
  }
}

Note: Make sure the Gemini API key is available in your environment when running Claude Code. Project-scoped servers (in .mcp.json) will require user approval on first use.

Alternative: Using Gradle Wrapper

You can also run the server directly using the Gradle wrapper:

json
{
  "mcpServers": {
    "gemini-analyzer": {
      "command": "/path/to/GeminiMcpServer/gradlew",
      "args": ["bootRun"],
      "cwd": "/path/to/GeminiMcpServer"
    }
  }
}

Usage

Subagent Pattern (Recommended)

This MCP server is designed to work best as part of a Claude Code subagent workflow:

  1. Create a subagent in Claude Code that includes this MCP server
  2. Invoke the subagent with prompts like "Ask Gemini to analyze this codebase"
  3. Results are saved to a file in the project directory: gemini-analysis-<timestamp>.md
  4. Claude Code reads the file after Gemini completes the analysis

Example Subagent Configuration:

yaml
name: gemini-analyzer
description: Analyzes codebases using Google Gemini's large context window
mcp_servers:
  - gemini-analyzer
instructions: |
  When asked to analyze a codebase:
  1. Use gemini_scanAndPlan to scan the files
  2. Use gemini_analyzeCodebase to run the analysis
  3. Report the output file path back to the user
  4. The analysis will be saved to gemini-analysis-<timestamp>.md

Direct Usage

The MCP server provides two tools that can be invoked by your AI assistant:

1. Scan and Plan Analysis

typescript
// The assistant can call this tool to scan a codebase
gemini_scanAndPlan({
  root: "/path/to/project",           // Required: project root directory
  includePatterns: ["**/*.java"],     // Optional: glob patterns to include
  excludePatterns: ["**/test/**"],    // Optional: glob patterns to exclude  
  maxFiles: 1000,                     // Optional: maximum files to include
  maxBytes: 10485760,                 // Optional: maximum total bytes
  targetTokens: 900000                // Optional: target tokens per shard
})

2. Analyze Codebase

typescript
// The assistant can call this tool to analyze the scanned files
// Results are saved to: <root>/gemini-analysis-<timestamp>.md
gemini_analyzeCodebase({
  root: "/path/to/project",
  model: "gemini-2.5-flash",                   // Optional: Gemini model to use (default)
  strategy: "MAP_REDUCE",                      // Optional: analysis strategy
  includePatterns: ["**/*.java"],              // Optional: file patterns
  prompt: "Analyze this codebase for security vulnerabilities"
})

// Returns:
{
  "format": "markdown",
  "report": "...",                             // The full analysis report
  "outputFile": "/path/to/project/gemini-analysis-20250106-143022.md",
  "stats": { ... }
}

Example Use Cases

In Claude Code or Claude Desktop

  1. Large Codebase Review:

    User: "Can you have Gemini analyze this entire Spring Boot application for architectural improvements?"
    Assistant: [Uses gemini_scanAndPlan to scan the codebase, then gemini_analyzeCodebase to get Gemini's analysis]
  2. Security Audit:

    User: "Ask Gemini to review all our Java files for security vulnerabilities"
    Assistant: [Scans for *.java files and sends them to Gemini for security analysis]
  3. Code Quality Assessment:

    User: "Get Gemini's opinion on our test coverage and testing patterns"
    Assistant: [Scans test directories and sends to Gemini for test quality analysis]

Architecture

┌─────────────┐     MCP      ┌──────────────┐     CLI      ┌─────────┐
│   Claude    │◄────────────►│  This MCP    │◄────────────►│ Gemini  │
│   Desktop/  │   Protocol    │   Server     │   Execution  │   CLI   │
│   Code      │               │ (Spring Boot)│              │         │
└─────────────┘               └──────────────┘              └─────────┘

Token Context Windows

  • Gemini 2.5 Flash: 1 million tokens (default model)
  • Gemini 2.5 Pro: 2 million tokens
  • Claude 3.5 Sonnet: 200k tokens
  • GPT-4 Turbo: 128k tokens

This significant difference in context window size makes Gemini ideal for whole-codebase analysis tasks.

Development

Project Structure

GeminiMcpServer/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── edu/trincoll/geminimcpserver/
│   │   │       ├── GeminiMcpServerApplication.java  # Spring Boot main
│   │   │       └── GeminiTools.java                 # MCP tool implementations
│   │   └── resources/
│   │       └── application.properties               # Spring configuration
│   └── test/
│       └── java/
│           └── edu/trincoll/geminimcpserver/
│               ├── GeminiToolsTest.java             # Unit tests
│               ├── GeminiToolsAdvancedTest.java     # Advanced scenarios
│               ├── GeminiMcpServerIntegrationTest.java # Integration tests
│               └── TestFixtures.java                # Test utilities
├── build.gradle.kts                                 # Gradle build configuration
└── README.md                                        # This file

Running Tests

bash
# Run all tests
./gradlew test

# Run specific test class
./gradlew test --tests GeminiToolsTest

# Run with detailed output
./gradlew test --info

Building

bash
# Build the project
./gradlew build

# Build executable JAR
./gradlew bootJar

# Clean and rebuild
./gradlew clean build

Logs and Output

Log Files

The server creates detailed logs to help with debugging:

  • Console output: Shows key operations with timestamps
  • Log file: gemini-mcp-server.log in the working directory
  • Log level: DEBUG for the Gemini tools, INFO for Spring components

Analysis Output Files

Each analysis creates a timestamped markdown file:

  • Location: In the analyzed project's root directory
  • Format: gemini-analysis-YYYYMMDD-HHmmss.md
  • Content: Complete Gemini analysis report in markdown format

Example output files:

/your/project/
├── src/
├── build.gradle.kts
├── gemini-analysis-20250106-143022.md  # First analysis
└── gemini-analysis-20250106-151545.md  # Second analysis

Troubleshooting

Common Issues

  1. Gemini CLI not found: Ensure gemini is in your PATH

    bash
    which gemini  # Should return /opt/homebrew/bin/gemini or similar
    • On M1/M2 Macs, Gemini is typically installed at /opt/homebrew/bin/gemini
    • The MCP server automatically adds this to PATH when running
  2. Empty or minimal analysis results:

    • Check the log file (gemini-mcp-server.log) for "Command succeeded with X chars of output"
    • If X is very small (1-2 chars), Gemini isn't receiving the context properly
    • The server uses the -a flag to include all files - ensure you're running from the project root
  3. "Broken pipe" errors:

    • Usually means the Gemini CLI rejected the input format
    • Check that gemini CLI is up to date: gemini --version
    • The server now uses --prompt flag instead of piping content via stdin
  4. API Key issues: Set the GEMINI_API_KEY environment variable

    bash
    export GEMINI_API_KEY="your-key-here"
  5. Java version: Ensure you're using Java 21+

    bash
    java -version  # Should show version 21 or higher
  6. Wrong Gemini model: The server forces gemini-2.5-flash regardless of what the client requests

    • This ensures maximum context window (1M tokens)
    • Check logs to confirm: should show "gemini --model gemini-2.5-flash"
  7. MCP client can't connect: Check that the path in config is absolute and correct

    bash
    # Test the JAR directly:
    java -jar /path/to/GeminiMcpServer-0.0.1-SNAPSHOT.jar

Contributing

Contributions are welcome! Please feel free to submit issues or pull requests.

License

MIT License - see LICENSE file for details

Acknowledgments

Установка

TypingMind
{
  "mcpServers": {
    "geminimcpserver": {
      "command": "java",
      "args": [
        "-jar",
        "/path/to/GeminiMcpServer/build/libs/GeminiMcpServer-0.0.1-SNAPSHOT.jar"
      ]
    }
  }
}

Используйте MCP Gemini MCP 服务器 с разными ИИ-моделями

TypingMind подключает инструменты MCP на уровне рабочего пространства, поэтому после подключения Gemini MCP 服务器 вы можете использовать их с разными моделями ИИ в TypingMind, не настраивая подключение отдельно для каждой модели. Эта интеграция MCP работает локально на вашем устройстве через коннектор MCP TypingMind.

Руководство по настройке локального коннектора

Выберите этот способ, если серверу MCP нужен доступ к локальным файлам, приложениям или закрытым ресурсам на вашем компьютере.

1

Откройте настройки MCP

В TypingMind откройте «Настройки», затем «Расширенные настройки», перейдите в раздел «Протокол контекста модели» и выберите «Настроить коннектор».

  1. Откройте TypingMind в браузере.
  2. Нажмите значок настроек.
  3. Перейдите в «Расширенные настройки».
  4. Откройте раздел «Протокол контекста модели».
  5. Нажмите «Настроить коннектор» и выберите «Это устройство».
Экран настройки коннектора MCP в TypingMind с выбранным вариантом «Это устройство»
2

Выполните команду коннектора

Выберите «Это устройство», скопируйте команду из TypingMind и выполните её в терминале. Не останавливайте процесс, пока используете MCP.

  1. Скопируйте команду настройки, показанную в TypingMind.
  2. Откройте «Терминал» в macOS или Windows Terminal в Windows.
  3. Вставьте и выполните команду.
  4. Подтвердите установку пакета, если терминал запросит разрешение продолжить.
  5. Не закрывайте окно терминала и не останавливайте процесс, пока используете инструменты MCP.
3

Добавьте Gemini MCP 服务器 как сервер

Когда статус коннектора сменится на «Готов», нажмите «Изменить серверы» и вставьте конфигурацию сервера MCP.

  1. Дождитесь, пока статус коннектора сменится на «Готов».
  2. Нажмите «Изменить серверы».
  3. Вставьте конфигурацию сервера MCP для Gemini MCP 服务器.
  4. Сохраните список серверов.
  5. Обновите статус, если хотите убедиться, что коннектор по-прежнему готов к работе.
Настройки MCP в TypingMind с активным сервером и кнопкой «Изменить серверы»
{
  "mcpServers": {
    "geminimcpserver": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

Используйте подключение с разными моделями

Сохраните список серверов, откройте раздел «Плагины», включите инструменты MCP для Gemini MCP 服务器, затем выберите любую поддерживаемую модель ИИ в TypingMind и используйте инструменты в чате или назначьте их ИИ-агенту.

  1. Откройте страницу «Плагины» в TypingMind.
  2. Включите инструменты MCP для Gemini MCP 服务器.
  3. Начните чат и выберите модель ИИ, которую хотите использовать.
  4. Используйте инструменты MCP в чате или назначьте их ИИ-агенту.
  5. При необходимости переключайтесь на другую модель ИИ без повторного подключения MCP.
Чат TypingMind с включёнными инструментами MCP и выбранной ИИ-моделью
Можете помочь мне с этой задачей с помощью Gemini MCP 服务器?
Gemini MCP 服务器
Конечно. Я всё прочитал.
Вот что я нашёл с помощью Gemini MCP 服务器.

Часто задаваемые вопросы

Для чего используется сервер MCP Gemini MCP 服务器?

Gemini MCP 服务器 — это сервер MCP, который позволяет совместимым ИИ-клиентам подключаться к внешним инструментам и получать контекст. В TypingMind достаточно один раз добавить этот сервер MCP, чтобы его инструменты стали доступны в вашем рабочем пространстве с ИИ.

Можно ли использовать сервер MCP Gemini MCP 服务器 с несколькими ИИ-моделями в TypingMind?

Да. TypingMind подключает инструменты MCP на уровне рабочего пространства, поэтому вы можете использовать Gemini MCP 服务器 с разными ИИ-моделями, например Claude, ChatGPT, Gemini или другими моделями, настроенными в TypingMind, без отдельной настройки сервера MCP для каждой модели.

Зачем использовать MCP Gemini MCP 服务器 с TypingMind?

TypingMind — один из лучших интерфейсов для чата с LLM: он объединяет разные ИИ-модели, промпты, плагины, ИИ-агентов, ключи API и инструменты MCP в одном рабочем пространстве. Подключив Gemini MCP 服务器, вы сможете использовать его инструменты MCP с предпочитаемыми моделями, сохраняя удобную организацию работы с чатами в TypingMind.

Как подключить сервер MCP Gemini MCP 服务器 к TypingMind?

Gemini MCP 服务器 работает через локальный коннектор MCP TypingMind. Этот вариант лучше всего подходит, когда серверу MCP нужен доступ к локальным файлам, настольным приложениям, инструментам командной строки или закрытым ресурсам на вашем компьютере.

Какие инструменты предоставляет сервер MCP Gemini MCP 服务器 в TypingMind?

Gemini MCP 服务器 предоставляет возможности MCP, которые можно включить на странице «Плагины» в TypingMind и использовать в чате или назначить ИИ-агентам.

Нужно ли передавать TypingMind свои ключи API для использования сервера MCP Gemini MCP 服务器?

Нет. TypingMind ориентирован прежде всего на локальную работу и позволяет вам контролировать выбор провайдеров моделей, ключи API, промпты и конфигурацию MCP. Если Gemini MCP 服务器 требует аутентификации, при создании подключения добавьте необходимые заголовки, настройки OAuth или локальную конфигурацию для этого сервера MCP.

Похожие серверы MCP

Все

Создайте свою рабочую ИИ-среду сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇