Gemini
Предоставляет модели Google Gemini в качестве стандартных инструментов MCP с помощью этого сервера. Обеспечивает генерацию текста, вызов функций, работу с файлами и многое другое для бесшовной интеграции ИИ.
Этот инструмент предоставляет выделенный сервер, оборачивающий SDK @google/genai и предоставляющий возможности модели Gemini от Google в виде стандартных инструментов Model Context Protocol (MCP). Он позволяет другим LLM или системам, совместимым с MCP, использовать возможности Gemini в качестве внутреннего вычислителя, предлагая единый интерфейс на основе инструментов, управляемый через стандарт MCP.
Ключевые возможности
Варианты использования
This project provides a dedicated MCP (Model Context Protocol) server that wraps the @google/genai SDK. It exposes Google's Gemini model capabilities as standard MCP tools, allowing other LLMs (like Cline) or MCP-compatible systems to leverage Gemini's features as a backend workhorse.
This server aims to simplify integration with Gemini models by providing a consistent, tool-based interface managed via the MCP standard.
- Core Generation: Standard (
gemini_generateContent) and streaming (gemini_generateContentStream) text generation. - Function Calling: Enables Gemini models to request the execution of client-defined functions (
gemini_functionCall). - Stateful Chat: Manages conversational context across multiple turns (
gemini_startChat,gemini_sendMessage,gemini_sendFunctionResult). - File Handling: Upload, list, retrieve, and delete files using the Gemini API.
- Caching: Create, list, retrieve, update, and delete cached content to optimize prompts.
- Node.js (v18 or later)
- An API Key from Google AI Studio (https://aistudio.google.com/app/apikey).
- Important: The File Handling and Caching APIs are only compatible with Google AI Studio API keys and are not supported when using Vertex AI credentials. This server does not currently support Vertex AI authentication.
-
Clone/Place Project: Ensure the
mcp-gemini-serverproject directory is accessible on your system. -
Install Dependencies: Navigate to the project directory in your terminal and run:
npm install
-
Build Project: Compile the TypeScript source code:
npm run build
This command uses the TypeScript compiler (
tsc) and outputs the JavaScript files to the./distdirectory (as specified byoutDirintsconfig.json). The main server entry point will bedist/server.js. -
Configure MCP Client: Add the server configuration to your MCP client's settings file (e.g.,
cline_mcp_settings.jsonfor Cline/VSCode, orclaude_desktop_config.jsonfor Claude Desktop App). Replace/path/to/mcp-gemini-serverwith the actual path on your system andYOUR_API_KEYwith your Google AI Studio key.{ "mcpServers": { "gemini-server": { // Or your preferred name "command": "node", "args": ["/path/to/mcp-gemini-server/dist/server.js"], // Path to the compiled server entry point "env": { "GOOGLE_GEMINI_API_KEY": "YOUR_API_KEY", "GOOGLE_GEMINI_MODEL": "gemini-1.5-flash" // Optional: Set a default model }, "disabled": false, "autoApprove": [] } // ... other servers } } -
Restart MCP Client: Restart your MCP client application (e.g., VS Code with Cline extension, Claude Desktop App) to load the new server configuration. The MCP client will manage starting and stopping the server process.
The server uses environment variables for configuration, passed via the env object in the MCP settings:
GOOGLE_GEMINI_API_KEY(Required): Your API key obtained from Google AI Studio.GOOGLE_GEMINI_MODEL(Optional): Specifies a default Gemini model name (e.g.,gemini-1.5-flash,gemini-1.0-pro). If set, tools that require a model name (likegemini_generateContent,gemini_startChat, etc.) will use this default when themodelNameparameter is omitted in the tool call. This simplifies client calls when primarily using one model. If this environment variable is not set, themodelNameparameter becomes required for those tools. See the Google AI documentation for available model names.
This server provides the following MCP tools. Parameter schemas are defined using Zod for validation and description.
Note on Optional Parameters: Many tools accept complex optional parameters (e.g., generationConfig, safetySettings, toolConfig, history, functionDeclarations, contents). These parameters are typically objects or arrays whose structure mirrors the types defined in the underlying @google/genai SDK. For the exact structure and available fields within these complex parameters, please refer to:
1. The corresponding src/tools/*Params.ts file in this project.
2. The official Google AI JS SDK Documentation.
gemini_generateContent- Description: Generates non-streaming text content from a prompt.
- Required Params:
prompt(string) - Optional Params:
modelName(string),generationConfig(object),safetySettings(array)
gemini_generateContentStream- Description: Generates text content via streaming. (Note: Current implementation uses a workaround and collects all chunks before returning the full text).
- Required Params:
prompt(string) - Optional Params:
modelName(string),generationConfig(object),safetySettings(array)
gemini_functionCall- Description: Sends a prompt and function declarations to the model, returning either a text response or a requested function call object (as a JSON string).
- Required Params:
prompt(string),functionDeclarations(array) - Optional Params:
modelName(string),generationConfig(object),safetySettings(array),toolConfig(object)
gemini_startChat- Description: Initiates a new stateful chat session and returns a unique
sessionId.\n * Required Params: None - Optional Params:
modelName(string),history(array),tools(array),generationConfig(object),safetySettings(array)
- Description: Initiates a new stateful chat session and returns a unique
gemini_sendMessage- Description: Sends a message within an existing chat session.\n * Required Params:
sessionId(string),message(string) - Optional Params:
generationConfig(object),safetySettings(array),tools(array),toolConfig(object)
- Description: Sends a message within an existing chat session.\n * Required Params:
gemini_sendFunctionResult- Description: Sends the result of a function execution back to a chat session.\n * Required Params:
sessionId(string),functionResponses(array) - Optional Params:
generationConfig(object),safetySettings(array)
- Description: Sends the result of a function execution back to a chat session.\n * Required Params:
gemini_uploadFile- Description: Uploads a file from a local path.\n Required Params:
filePath(string - must be an absolute path)\n Optional Params:displayName(string),mimeType(string)
- Description: Uploads a file from a local path.\n Required Params:
gemini_listFiles- Description: Lists previously uploaded files.\n * Required Params: None
- Optional Params:
pageSize(number),pageToken(string - Note:pageTokenmay not be reliably returned currently).
gemini_getFile- Description: Retrieves metadata for a specific uploaded file.\n * Required Params:
fileName(string - e.g.,files/abc123xyz)
- Description: Retrieves metadata for a specific uploaded file.\n * Required Params:
gemini_deleteFile- Description: Deletes an uploaded file.\n * Required Params:
fileName(string - e.g.,files/abc123xyz)
- Description: Deletes an uploaded file.\n * Required Params:
gemini_createCache- Description: Creates cached content for compatible models (e.g.,
gemini-1.5-flash).\n * Required Params:contents(array) - Optional Params:
modelName(string),displayName(string),systemInstruction(object),ttl(string - e.g., '3600s')
- Description: Creates cached content for compatible models (e.g.,
gemini_listCaches- Description: Lists existing cached content.\n * Required Params: None
- Optional Params:
pageSize(number),pageToken(string - Note:pageTokenmay not be reliably returned currently).
gemini_getCache- Description: Retrieves metadata for specific cached content.\n * Required Params:
cacheName(string - e.g.,cachedContents/abc123xyz)
- Description: Retrieves metadata for specific cached content.\n * Required Params:
gemini_updateCache- Description: Updates metadata (TTL, displayName) for cached content.\n * Required Params:
cacheName(string) - Optional Params:
ttl(string),displayName(string)
- Description: Updates metadata (TTL, displayName) for cached content.\n * Required Params:
gemini_deleteCache- Description: Deletes cached content.\n * Required Params:
cacheName(string - e.g.,cachedContents/abc123xyz)
- Description: Deletes cached content.\n * Required Params:
Here are examples of how an MCP client (like Cline) might call these tools using the use_mcp_tool format:
Example 1: Simple Content Generation (Using Default Model)
<use_mcp_tool>
<server_name>gemini-server</server_name>
<tool_name>gemini_generateContent</tool_name>
<arguments>
{
"prompt": "Write a short poem about a rubber duck."
}
</arguments>
</use_mcp_tool>Example 2: Content Generation (Specifying Model & Config)
<use_mcp_tool>
<server_name>gemini-server</server_name>
<tool_name>gemini_generateContent</tool_name>
<arguments>
{
"modelName": "gemini-1.0-pro",
"prompt": "Explain the concept of recursion in programming.",
"generationConfig": {
"temperature": 0.7,
"maxOutputTokens": 500
}
}
</arguments>
</use_mcp_tool>Example 3: Starting and Continuing a Chat
Start Chat:
<use_mcp_tool>
<server_name>gemini-server</server_name>
<tool_name>gemini_startChat</tool_name>
<arguments>
{}
</arguments>
</use_mcp_tool>(Assume response contains sessionId: "some-uuid-123")
Send Message:
<use_mcp_tool>
<server_name>gemini-server</server_name>
<tool_name>gemini_sendMessage</tool_name>
<arguments>
{
"sessionId": "some-uuid-123",
"message": "Hello! Can you tell me about the Gemini API?"
}
</arguments>
</use_mcp_tool>Example 4: Uploading a File
<use_mcp_tool>
<server_name>gemini-server</server_name>
<tool_name>gemini_uploadFile</tool_name>
<arguments>
{
"filePath": "C:\\Users\\YourUser\\Documents\\my_document.txt", // IMPORTANT: Use absolute path with escaped backslashes if needed
"displayName": "My Document"
}
</arguments>
</use_mcp_tool>The server aims to return structured errors using the MCP standard McpError type when tool execution fails. This object typically contains:
code: AnErrorCodeenum value indicating the type of error (e.g.,InvalidParams,InternalError,PermissionDenied,NotFound).message: A human-readable description of the error.details: (Optional) An object potentially containing more specific information from the underlying Gemini SDK error (like safety block reasons or API error messages) for troubleshooting.
Common Error Scenarios:
- Invalid API Key: Often results in an
InternalErrorwith details indicating an authentication failure. - Invalid Parameters: Results in
InvalidParams(e.g., missing required field, wrong data type). - Safety Blocks: May result in
InternalErrorwith details indicatingSAFETYas the block reason or finish reason. - File/Cache Not Found: May result in
NotFoundorInternalErrordepending on how the SDK surfaces the error. - Rate Limits: May result in
ResourceExhaustedorInternalError.
Check the message and details fields of the returned McpError for specific clues when troubleshooting.
This server follows the standard MCP server structure outlined in the project's .clinerules and internal documentation. Key patterns include:
- Service Layer (
src/services): Encapsulates interactions with the@google/genaiSDK, keeping it decoupled from MCP specifics. - Tool Layer (
src/tools): Adapts service layer functionality to MCP tools, handling parameter mapping and error translation. - Zod Schemas (
src/tools/*Params.ts): Used extensively for defining tool parameters, providing validation, and generating detailed descriptions crucial for LLM interaction. - Configuration (
src/config): Centralized management viaConfigurationManager. - Types (
src/types): Clear TypeScript definitions.
gemini_generateContentStreamuses a workaround, collecting all chunks before returning the full text. True streaming to the MCP client is not yet implemented.gemini_listFilesandgemini_listCachesmay not reliably returnnextPageTokendue to limitations in iterating the SDK's Pager object.gemini_uploadFilerequires absolute file paths when run from the server environment.- File Handling & Caching APIs are not supported on Vertex AI, only Google AI Studio API keys.
MCP Gemini Server
Сервер, реализующий протокол MCP (Model Context Protocol) для интеграции моделей Google Gemini с любыми MCP-совместимыми клиентами (например, Cline, Claude Desktop). Он оборачивает @google/genai SDK в набор стандартных инструментов, позволяя другим LLM использовать Gemini в качестве бэкенда.
Возможности
- Генерация текста: обычная (
gemini_generateContent) и потоковая (gemini_generateContentStream). - Function Calling: модель может запрашивать выполнение функций, определённых клиентом (
gemini_functionCall). - Диалоговый режим: управление контекстом беседы через
gemini_startChat,gemini_sendMessage,gemini_sendFunctionResult. - Работа с файлами: загрузка, список, получение метаданных и удаление файлов через Gemini API.
- Кэширование: создание, обновление, удаление кэшированного контента для оптимизации промптов.
Требования
- Node.js v18 или новее.
- API-ключ из Google AI Studio.
Важно: работа с файлами и кэширование поддерживаются только с ключами Google AI Studio. Vertex AI не поддерживается.
Установка и настройка
- Склонируйте или скопируйте проект
mcp-gemini-server. - В терминале перейдите в директорию проекта и выполните:
Командаnpm install npm run buildbuildкомпилирует TypeScript в JavaScript (выходная директория./dist). - Настройте MCP-клиент. Добавьте в его конфигурационный файл (например,
cline_mcp_settings.jsonилиclaude_desktop_config.json) следующий блок, заменив пути и ключ на свои:{ "mcpServers": { "gemini-server": { "command": "node", "args": ["/путь/к/mcp-gemini-server/dist/server.js"], "env": { "GOOGLE_GEMINI_API_KEY": "ВАШ_КЛЮЧ", "GOOGLE_GEMINI_MODEL": "gemini-1.5-flash" }, "disabled": false, "autoApprove": [] } } } - Перезапустите MCP-клиент (VS Code с Cline, Claude Desktop и т.д.).
Конфигурация
Настройки передаются через переменные окружения в объекте env:
GOOGLE_GEMINI_API_KEY(обязательно) — API-ключ из Google AI Studio.GOOGLE_GEMINI_MODEL(опционально) — модель по умолчанию (например,gemini-1.5-flash,gemini-1.0-pro). Если переменная не задана, параметрmodelNameстановится обязательным для инструментов, которые его используют.
Доступные инструменты
Параметры описаны с помощью Zod. Для сложных опциональных параметров (например, generationConfig, safetySettings, history) смотрите файлы src/tools/*Params.ts или официальную документацию Google AI JS SDK.
Генерация текста
gemini_generateContent— генерация без потоковой передачи.- Обязательно:
prompt(string). - Опционально:
modelName,generationConfig,safetySettings.
- Обязательно:
gemini_generateContentStream— потоковая генерация (текущая реализация собирает все чанки и возвращает полный текст).- Параметры те же.
Function Calling
gemini_functionCall— отправляет промпт и объявления функций, возвращает текст или JSON с запросом вызова функции.- Обязательно:
prompt,functionDeclarations(array). - Опционально:
modelName,generationConfig,safetySettings,toolConfig.
- Обязательно:
Диалоговый режим
gemini_startChat— создаёт новую сессию чата, возвращаетsessionId.- Опционально:
modelName,history,tools,generationConfig,safetySettings.
- Опционально:
gemini_sendMessage— отправляет сообщение в существующую сессию.- Обязательно:
sessionId,message. - Опционально:
generationConfig,safetySettings,tools,toolConfig.
- Обязательно:
gemini_sendFunctionResult— отправляет результат выполнения функции обратно в чат.- Обязательно:
sessionId,functionResponses(array). - Опционально:
generationConfig,safetySettings.
- Обязательно:
Работа с файлами (только Google AI Studio)
gemini_uploadFile— загружает файл по абсолютному пути.- Обязательно:
filePath(string, абсолютный путь). - Опционально:
displayName,mimeType.
- Обязательно:
gemini_listFiles— список загруженных файлов.- Опционально:
pageSize,pageToken(может не возвращаться).
- Опционально:
gemini_getFile— метаданные файла.- Обязательно:
fileName(например,files/abc123xyz).
- Обязательно:
gemini_deleteFile— удаление файла.- Обязательно:
fileName.
- Обязательно:
Кэширование (только Google AI Studio)
gemini_createCache— создаёт кэш для совместимых моделей (например,gemini-1.5-flash).- Обязательно:
contents(array). - Опционально:
modelName,displayName,systemInstruction,ttl(например,'3600s').
- Обязательно:
gemini_listCaches— список кэшей.- Опционально:
pageSize,pageToken.
- Опционально:
gemini_getCache— метаданные кэша.- Обязательно:
cacheName(например,cachedContents/abc123xyz).
- Обязательно:
gemini_updateCache— обновление TTL или имени кэша.- Обязательно:
cacheName. - Опционально:
ttl,displayName.
- Обязательно:
gemini_deleteCache— удаление кэша.- Обязательно:
cacheName.
- Обязательно:
Примеры использования
Простая генерация (модель по умолчанию)
<use_mcp_tool>
<server_name>gemini-server</server_name>
<tool_name>gemini_generateContent</tool_name>
<arguments>
{
"prompt": "Напиши короткое стихотворение о резиновой утке."
}
</arguments>
</use_mcp_tool>
Генерация с указанием модели и параметров
<use_mcp_tool>
<server_name>gemini-server</server_name>
<tool_name>gemini_generateContent</tool_name>
<arguments>
{
"modelName": "gemini-1.0-pro",
"prompt": "Объясни рекурсию в программировании.",
"generationConfig": {
"temperature": 0.7,
"maxOutputTokens": 500
}
}
</arguments>
</use_mcp_tool>
Диалог
- Начать чат:
<use_mcp_tool>
<server_name>gemini-server</server_name>
<tool_name>gemini_startChat</tool_name>
<arguments>{}</arguments>
</use_mcp_tool>
(В ответ придёт sessionId, например some-uuid-123).
2. Отправить сообщение:
<use_mcp_tool>
<server_name>gemini-server</server_name>
<tool_name>gemini_sendMessage</tool_name>
<arguments>
{
"sessionId": "some-uuid-123",
"message": "Привет! Расскажи о Gemini API."
}
</arguments>
</use_mcp_tool>
Загрузка файла
<use_mcp_tool>
<server_name>gemini-server</server_name>
<tool_name>gemini_uploadFile</tool_name>
<arguments>
{
"filePath": "C:\\Users\\User\\Documents\\file.txt",
"displayName": "Мой документ"
}
</arguments>
</use_mcp_tool>
Обработка ошибок
Сервер возвращает структурированные ошибки в формате McpError:
code— тип ошибки (InvalidParams,InternalError,PermissionDenied,NotFound).message— описание.details— (опционально) дополнительная информация от SDK (например, причина блокировки safety).
Типичные сценарии:
- Неверный API-ключ →
InternalError. - Неверные параметры →
InvalidParams. - Блокировка safety →
InternalErrorсdetails.SAFETY. - Файл/кэш не найден →
NotFoundилиInternalError. - Превышение лимитов →
ResourceExhaustedилиInternalError.
Разработка
Архитектура сервера:
- Service Layer (
src/services) — взаимодействие с@google/genaiSDK. - Tool Layer (
src/tools) — адаптация сервисов к MCP-инструментам. - Zod Schemas (
src/tools/*Params.ts) — валидация параметров. - Config (
src/config) — централизованное управление черезConfigurationManager. - Types (
src/types) — TypeScript-определения.
Известные проблемы
gemini_generateContentStreamсобирает все чанки перед возвратом — настоящий стриминг пока не реализован.gemini_listFilesиgemini_listCachesмогут не возвращатьnextPageTokenиз-за ограничений SDK.gemini_uploadFileтребует абсолютный путь к файлу.- Работа с файлами и кэширование недоступны при использовании Vertex AI.
Какие функции предлагает Gemini MCP Server?
Он предоставляет основные возможности генерации текста, потоковой передачи, вызова функций, управления состоянием сеанса чата и обработки файлов с использованием Gemini API.
Какие модели Gemini доступны через этот сервер?
Вы можете получить доступ к моделям Gemini, таким как `gemini-1.5-flash` и `gemini-1.0-pro`. Список доступных моделей см. в документации Google AI.
Что такое Gemini MCP Server?
Это сервер, который предоставляет модели Google Gemini в качестве стандартных инструментов Model Context Protocol (MCP), что позволяет другим LLM или системам, совместимым с MCP, легко использовать возможности Gemini.
Нужен ли мне ключ API Google AI Studio для использования всех функций?
Да, требуется ключ API Google AI Studio. Обработка файлов и кэширование API совместимы только с ключами API Google AI Studio, а не с учетными данными Vertex AI.
Что такое Model Context Protocol (MCP)?
MCP — это стандартный протокол, который позволяет различным языковым моделям (LLM) и системам взаимодействовать друг с другом через единый интерфейс «инструментов».
Источник: https://mcpmarket.com/server/gemini-5
Комментарии
Комментариев пока нет. Будьте первым.