Skip to main content
Glama
qhdrl12

Gemini Image Generator MCP Server

by qhdrl12

значок кузнеца

Генератор изображений Gemini MCP-сервер

Создавайте высококачественные изображения из текстовых подсказок, используя модель Gemini от Google через протокол MCP.

Обзор

Этот сервер MCP позволяет любому помощнику ИИ генерировать изображения с помощью модели ИИ Gemini от Google. Сервер обрабатывает оперативную разработку, преобразование текста в изображение, генерацию имен файлов и локальное хранение изображений, что упрощает создание и управление изображениями, сгенерированными ИИ, через любой клиент MCP.

Related MCP server: Gemini Image Gen MCP Server

Функции

  • Генерация текста в изображение с помощью Gemini 2.0 Flash

  • Преобразование изображения в изображение на основе текстовых подсказок

  • Поддержка как файловых, так и закодированных в base64 изображений

  • Автоматическая интеллектуальная генерация имени файла на основе подсказок

  • Автоматический перевод неанглоязычных подсказок

  • Локальное хранилище изображений с настраиваемым путем вывода

  • Строгое исключение текста из сгенерированных изображений

  • Вывод изображения высокого разрешения

  • Прямой доступ к данным изображения и пути к файлу

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

Сервер предоставляет следующие инструменты MCP для помощников ИИ:

1. generate_image_from_text

Создает новое изображение из текстового описания.

generate_image_from_text(prompt: str) -> Tuple[bytes, str]

Параметры:

  • prompt : Текстовое описание изображения, которое вы хотите создать

Возврат:

  • Кортеж, содержащий:

    • Необработанные данные изображения (байты)

    • Путь к сохраненному файлу изображения (str)

Этот формат двойного возврата позволяет помощникам на базе искусственного интеллекта работать с данными изображения напрямую или ссылаться на сохраненный путь к файлу.

Примеры:

  • «Создайте изображение заката над горами»

  • «Создайте фотореалистичную летающую свинью в научно-фантастическом городе»

Пример вывода

Это изображение было создано с помощью подсказки:

"Hi, can you create a 3d rendered image of a pig with wings and a top hat flying over a happy futuristic scifi city with lots of greenery?"

Летающая свинья над научно-фантастическим городом

3D-визуализация свиньи с крыльями и цилиндром, летящей над футуристическим научно-фантастическим городом, полным зелени.

Известные проблемы

При использовании этого сервера MCP с Claude Desktop Host:

  1. Проблемы с производительностью : использование transform_image_from_encoded может занять значительно больше времени для обработки по сравнению с другими методами. Это связано с накладными расходами на передачу больших данных изображения в кодировке base64 через протокол MCP.

  2. Проблемы с разрешением путей : могут возникнуть проблемы с правильным разрешением путей изображений при использовании Claude Desktop Host. Приложение-хост может неправильно интерпретировать возвращенные пути файлов, что затрудняет доступ к сгенерированным изображениям.

Для достижения наилучшего результата рассмотрите возможность использования альтернативных клиентов MCP или метода transform_image_from_file , когда это возможно.

2. transform_image_from_encoded

Преобразует существующее изображение на основе текстовой подсказки, используя данные изображения в кодировке base64.

transform_image_from_encoded(encoded_image: str, prompt: str) -> Tuple[bytes, str]

Параметры:

  • encoded_image : данные изображения, закодированные в Base64, с заголовком формата (должны быть в формате: "data:image/[format];base64,[data]")

  • prompt : Текстовое описание того, как вы хотите преобразовать изображение.

Возврат:

  • Кортеж, содержащий:

    • Необработанные преобразованные данные изображения (байты)

    • Путь к сохраненному преобразованному файлу изображения (str)

Пример:

  • «Добавьте снега к этому пейзажу»

  • «Изменить фон на пляж»

3. transform_image_from_file

Преобразует существующий файл изображения на основе текстовой подсказки.

transform_image_from_file(image_file_path: str, prompt: str) -> Tuple[bytes, str]

Параметры:

  • image_file_path : Путь к файлу изображения, который необходимо преобразовать.

  • prompt : Текстовое описание того, как вы хотите преобразовать изображение.

Возврат:

  • Кортеж, содержащий:

    • Необработанные преобразованные данные изображения (байты)

    • Путь к сохраненному преобразованному файлу изображения (str)

Примеры:

  • «Добавьте ламу рядом с человеком на этом изображении»

  • «Сделайте эту дневную сцену похожей на ночную»

Пример преобразования

Используя изображение летающей свиньи, созданное выше, мы применили преобразование с помощью следующего запроса:

"Add a cute baby whale flying alongside the pig"

До: Летающая свинья над научно-фантастическим городом

После: Летающая свинья с детенышем кита

Оригинальное изображение летающей свиньи с добавленным милым детенышем кита, летящим рядом с ней

Настраивать

Предпосылки

  • Питон 3.11+

  • Ключ API Google AI (Gemini)

  • Хост-приложение MCP (Claude Desktop App, Cursor или другие MCP-совместимые клиенты)

Получение API-ключа Gemini

  1. Посетите страницу ключей API Google AI Studio

  2. Войдите в систему, используя свой аккаунт Google.

  3. Нажмите «Создать ключ API».

  4. Скопируйте новый ключ API для использования в конфигурации.

  5. Примечание: API-ключ предоставляет определенную квоту бесплатного использования в месяц. Вы можете проверить свое использование в Google AI Studio

Установка

Установка через Smithery

Чтобы автоматически установить Gemini Image Generator MCP для Claude Desktop через Smithery :

npx -y @smithery/cli install @qhdrl12/mcp-server-gemini-image-gen --client claude

Ручная установка

  1. Клонируйте репозиторий:

git clone https://github.com/your-username/gemini-image-generator.git
cd gemini-image-generator
  1. Создайте виртуальную среду и установите зависимости:

# Using regular venv
python -m venv .venv
source .venv/bin/activate
pip install -e .

# Or using uv
uv venv
source .venv/bin/activate
uv pip install -e .
  1. Скопируйте пример файла среды и добавьте свой ключ API:

cp .env.example .env
  1. Отредактируйте файл .env , включив в него ключ API Google Gemini и предпочитаемый выходной путь:

GEMINI_API_KEY="your-gemini-api-key-here"
OUTPUT_IMAGE_PATH="/path/to/save/images"

Настроить рабочий стол Клода

Добавьте следующее в ваш claude_desktop_config.json :

  • macOS : ~/Library/Application Support/Claude/claude_desktop_config.json

{
    "mcpServers": {
        "gemini-image-generator": {
            "command": "uv",
            "args": [
                "--directory",
                "/absolute/path/to/gemini-image-generator",
                "run",
                "server.py"
            ],
            "env": {
                "GEMINI_API_KEY": "GEMINI_API_KEY",
                "OUTPUT_IMAGE_PATH": "OUTPUT_IMAGE_PATH"
            }
        }
    }
}

Использование

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

Создание новых изображений

  • «Создайте изображение заката над горами»

  • «Создайте иллюстрацию футуристического городского пейзажа»

  • «Нарисуй кошку в солнцезащитных очках»

Преобразование существующих изображений

  • «Преобразите это изображение, добавив в него снег»

  • «Отредактируйте это фото так, чтобы оно выглядело так, будто оно было сделано ночью»

  • «Добавьте летящего дракона на задний план этой картинки»

Сгенерированные/преобразованные изображения будут сохранены в настроенном вами выходном пути и отображены в Claude. Благодаря обновленным типам возврата помощники ИИ также могут работать напрямую с данными изображений без необходимости доступа к сохраненным файлам.

Тестирование

Вы можете протестировать приложение, запустив сервер разработки FastMCP:

fastmcp dev server.py

Эта команда запускает локальный сервер разработки и делает MCP Inspector доступным по адресу http://localhost:5173/ . MCP Inspector предоставляет удобный веб-интерфейс, где вы можете напрямую протестировать инструмент генерации изображений без необходимости использования Claude или другого клиента MCP. Вы можете вводить текстовые подсказки, запускать инструмент и немедленно видеть результаты, что полезно для разработки и отладки.

Лицензия

Лицензия Массачусетского технологического института

Available Tools

3 tools
generate_image_from_textA

Generate an image based on the given text prompt using Google's Gemini model.

Args:
    prompt: User's text prompt describing the desired image to generate
    
Returns:
    Path to the generated image file using Gemini's image generation capabilities
ParametersJSON Schema
NameRequiredDescriptionDefault
promptYes

TDQS

A3.5/5.0
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions the model and return type (path to image file) but lacks critical details such as rate limits, authentication requirements, image format, size, quality, or error handling. This is insufficient for a generative AI tool with potential costs and constraints.

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 appropriately sized and front-loaded, starting with the core functionality. The structured sections (Args, Returns) enhance readability, though the second sentence could be more integrated to avoid slight redundancy.

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

Completeness2/5

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

Given the complexity of image generation, no annotations, and no output schema, the description is incomplete. It lacks details on behavioral traits (e.g., costs, latency), output specifics (e.g., file format, resolution), and error cases, leaving significant gaps for an AI agent to use the tool effectively.

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 schema description coverage is 0%, but the description compensates by explaining the single parameter ('prompt') as 'User's text prompt describing the desired image to generate.' This adds meaningful context beyond the schema's basic type information, clarifying the parameter's role in the generation process.

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 the specific action ('Generate an image') and resource ('based on the given text prompt'), using Google's Gemini model. It distinguishes from sibling tools like 'transform_image_from_encoded' and 'transform_image_from_file' by specifying text-based generation rather than transformation from existing images.

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 implies usage for text-to-image generation but does not explicitly state when to use this tool versus alternatives. It mentions the model (Gemini) but provides no guidance on prerequisites, limitations, or scenarios where other tools might be more appropriate.

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

transform_image_from_encodedA

Transform an existing image based on the given text prompt using Google's Gemini model.

Args:
    encoded_image: Base64 encoded image data with header. Must be in format:
                "data:image/[format];base64,[data]"
                Where [format] can be: png, jpeg, jpg, gif, webp, etc.
    prompt: Text prompt describing the desired transformation or modifications
    
Returns:
    Path to the transformed image file saved on the server
ParametersJSON Schema
NameRequiredDescriptionDefault
encoded_imageYes
promptYes

TDQS

A4.3/5.0
Behavior3/5

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

With no annotations provided, the description carries full burden. It discloses the tool uses Google's Gemini model and that it saves the transformed image on the server, which are useful behavioral traits. However, it doesn't mention rate limits, authentication requirements, file size limits, or potential side effects of the transformation process.

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

Conciseness5/5

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

The description is efficiently structured with a clear opening sentence stating the purpose, followed by well-organized sections for Args and Returns. Every sentence earns its place by providing essential information without redundancy.

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 2-parameter tool with no annotations and no output schema, the description provides good coverage of purpose, parameters, and basic behavior. It explains what the tool does, how to format inputs, and what to expect as output. The main gap is lack of information about error conditions, performance characteristics, or more detailed behavioral constraints.

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?

With 0% schema description coverage, the description fully compensates by providing detailed semantics for both parameters. It specifies the exact format required for encoded_image (including header format and supported image types) and explains what the prompt parameter should contain. This adds significant value beyond the bare schema.

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 the tool's purpose with specific verb ('Transform') and resource ('an existing image'), and distinguishes it from siblings by specifying it uses encoded image data rather than text or file inputs. The mention of Google's Gemini model adds technical specificity.

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

Usage Guidelines4/5

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

The description provides clear context about when to use this tool (transforming existing images with encoded data) and implicitly distinguishes it from siblings (generate_image_from_text for text-to-image, transform_image_from_file for file-based transformation). However, it doesn't explicitly state when NOT to use this tool or mention specific prerequisites.

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

transform_image_from_fileA

Transform an existing image file based on the given text prompt using Google's Gemini model.

Args:
    image_file_path: Path to the image file to be transformed
    prompt: Text prompt describing the desired transformation or modifications
    
Returns:
    Path to the transformed image file saved on the server
ParametersJSON Schema
NameRequiredDescriptionDefault
image_file_pathYes
promptYes

TDQS

A3.9/5.0
Behavior2/5

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

No annotations are provided, so the description carries full burden. It mentions the tool saves the transformed file on the server, which is useful behavioral context. However, it lacks critical details like required permissions, file format limitations, transformation scope, error handling, or whether the operation is reversible/destructive.

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

Conciseness5/5

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

The description is efficiently structured with a clear purpose statement followed by labeled sections for Args and Returns. Every sentence adds value without redundancy, and information is front-loaded appropriately.

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

Completeness3/5

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

Given no annotations, no output schema, and 2 parameters, the description covers purpose and parameters adequately. However, for a transformation tool with potential complexity (image processing via Gemini), it lacks details about output format, file location specifics, or error cases, leaving gaps in completeness.

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?

With 0% schema description coverage, the description fully compensates by explaining both parameters: 'image_file_path' as 'Path to the image file to be transformed' and 'prompt' as 'Text prompt describing the desired transformation or modifications'. This adds essential meaning beyond the bare schema.

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 the tool's purpose with specific verb ('Transform') and resource ('existing image file'), and distinguishes it from siblings by specifying it works from a file path rather than text or encoded input. The mention of using Google's Gemini model adds technical specificity.

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

Usage Guidelines4/5

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

The description implies usage context by specifying it transforms 'an existing image file' and uses a 'text prompt', which differentiates it from 'generate_image_from_text' (creates new images) and 'transform_image_from_encoded' (uses encoded input). However, it doesn't explicitly state when to choose this tool over alternatives or any prerequisites.

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. 3 tool updates
    • First observedgenerate_image_from_text
    • First observedtransform_image_from_encoded
    • First observedtransform_image_from_file

TDQS

A3.9/5.0

Scored across 3 tools

Disambiguation5/5

The three tools have clearly distinct purposes: generate_image_from_text creates new images from text prompts, while transform_image_from_encoded and transform_image_from_file both transform existing images but differ in input format (base64 encoded vs. file path). The descriptions make these distinctions explicit, eliminating any potential confusion between generation and transformation operations.

Naming Consistency5/5

All tools follow a consistent verb_noun_from_source naming pattern: generate_image_from_text, transform_image_from_encoded, and transform_image_from_file. This pattern clearly indicates the action (generate/transform), the target (image), and the input source (text/encoded/file), creating a predictable and readable naming convention throughout the toolset.

Tool Count4/5

Three tools is a reasonable count for an image generation server, covering the core operations of generating new images and transforming existing ones. However, the scope feels slightly thin as there are no complementary tools for managing generated images (like listing, deleting, or retrieving metadata), which might limit agent workflows in production scenarios.

Completeness3/5

The server covers basic image generation and transformation operations well, but has notable gaps in image management. There are no tools for listing generated images, deleting files, retrieving image metadata, or batch operations. While the core generative AI functionality is present, the lack of lifecycle management tools creates potential dead ends for agents working with multiple images over time.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers