Skip to main content
Glama
ivanantigravity-lgtm

Nano Banana 2 Polza MCP Server

Nano Banana 2 Polza MCP Server

mcp-name: io.github.ivanantigravity-lgtm/nanobanana-2-polzaia-mcp-server

MCP-сервер для генерации и редактирования изображений через Polza с моделями семейства Google Nano Banana:

  • google/gemini-3.1-flash-image-preview — Nano Banana 2, модель по умолчанию

  • google/gemini-3-pro-image-preview — для сложных композиций и максимального качества

  • google/gemini-2.5-flash-image — для быстрых черновиков

Сервер отдаёт изображения настоящими MCP image content-блоками и параллельно — структурированный JSON с метаданными и подсказками по воспроизводимости.

Инструменты MCP

  • generate_image — генерация и редактирование. Поддерживает до трёх референсов для conditioning, выбор модели, aspect ratio, разрешение и прочие параметры.

  • fetch_generation — докачка уже запущенной генерации по gen_... id. Нужен, когда MCP-клиент отвалился по таймауту, а генерация на стороне Polza успешно завершилась. Позволяет не перегенерировать (и не оплачивать повторно).

  • upload_file — загрузка файлов в Polza Storage.

  • show_output_stats — статистика локальной выходной директории.

  • maintenance — обслуживание кэша, квот и БД.

Related MCP server: Nano Banana MCP

Что нужно пользователю

  • Claude Code или любой другой MCP-клиент

  • uv

  • Python 3.11+

  • POLZA_AI_API_KEY (токен аккаунта Polza)

Быстрая установка за 2 минуты

Для Claude Code / VS Code:

  1. Установите uv (brew install uv на macOS).

  2. В корне проекта создайте файл .mcp.json.

  3. Вставьте конфиг и подставьте свой Polza-ключ.

{
  "mcpServers": {
    "nanobanana-polza": {
      "command": "uvx",
      "args": ["nanobanana-2-polzaia-mcp-server@latest"],
      "env": {
        "POLZA_AI_API_KEY": "your-polza-api-key-here",
        "POLZA_BASE_URL": "https://polza.ai/api",
        "IMAGE_OUTPUT_DIR": "/Users/yourname/Documents/nanobanana"
      }
    }
  }
}

Перезапустите Claude Code / VS Code.

Восстановление после таймаута

MCP-клиенты (в том числе Claude Code) обычно имеют собственный таймаут на один tool call порядка 60 секунд. Nano Banana 2 укладывается в это окно не всегда, и клиент может вернуть The read operation timed out ещё до того, как Polza успела отдать результат. Сервер Polza в этот момент доводит генерацию до конца и сохраняет её под gen_... id.

Если такое случилось:

  1. Посмотрите gen_... id в веб-интерфейсе Polza (раздел генераций).

  2. Вызовите fetch_generation с этим id — сервер опросит статус и сохранит файл локально.

fetch_generation(media_id="gen_2158267363095220225",
                 output_path="/abs/path/to/slide_3.png")

Параметр output_path принимает как конкретный файл, так и директорию. При отсутствии параметра файл сохраняется в IMAGE_OUTPUT_DIR.

Локальная разработка

git clone https://github.com/ivanantigravity-lgtm/nanobanana-2-polzaia-mcp-server.git
cd nanobanana-2-polzaia-mcp-server
uv sync
cp .env.example .env

Минимум в .env:

POLZA_AI_API_KEY=your_polza_api_key
POLZA_BASE_URL=https://polza.ai/api
IMAGE_OUTPUT_DIR=/absolute/path/to/output

Запуск:

uv run python -m nanobanana_2_polzaia_mcp_server.server

Claude Code / VS Code (варианты конфига)

Установленный через PyPI пакет — рекомендуемый вариант:

{
  "mcpServers": {
    "nanobanana-polza": {
      "command": "uvx",
      "args": ["nanobanana-2-polzaia-mcp-server@latest"],
      "env": {
        "POLZA_AI_API_KEY": "your-polza-api-key-here",
        "POLZA_BASE_URL": "https://polza.ai/api",
        "IMAGE_OUTPUT_DIR": "/Users/demo/Documents/nanobanana"
      }
    }
  }
}

Запуск из исходников:

{
  "mcpServers": {
    "nanobanana-polza-local": {
      "command": "uv",
      "args": ["run", "python", "-m", "nanobanana_2_polzaia_mcp_server.server"],
      "cwd": "/absolute/path/to/nanobanana-2-polzaia-mcp-server",
      "env": {
        "POLZA_AI_API_KEY": "your-polza-api-key-here",
        "POLZA_BASE_URL": "https://polza.ai/api",
        "IMAGE_OUTPUT_DIR": "/absolute/path/to/output"
      }
    }
  }
}

Claude Desktop

На macOS добавьте сервер в файл:

~/Library/Application Support/Claude/claude_desktop_config.json

Пример:

{
  "mcpServers": {
    "nanobanana-polza": {
      "command": "uvx",
      "args": ["nanobanana-2-polzaia-mcp-server@latest"],
      "env": {
        "POLZA_AI_API_KEY": "your-polza-api-key-here",
        "POLZA_BASE_URL": "https://polza.ai/api",
        "IMAGE_OUTPUT_DIR": "/Users/demo/Documents/nanobanana"
      }
    }
  }
}

Переменные окружения

Переменная

Обязательно

Описание

POLZA_AI_API_KEY

да

Токен доступа к Polza API

POLZA_BASE_URL

нет

База API, по умолчанию https://polza.ai/api

IMAGE_OUTPUT_DIR

нет

Директория для сохранённых файлов, по умолчанию ~/nanobanana-images

POLZA_POLL_INTERVAL_SECONDS

нет

Интервал поллинга статуса, по умолчанию 2

POLZA_POLL_TIMEOUT_SECONDS

нет

Таймаут ожидания генерации, по умолчанию 120

POLZA_EXTERNAL_USER_ID

нет

Передаётся в Polza как user для антифрода

RETURN_FULL_IMAGE

нет

Возвращать полное изображение в MCP-ответе вместо thumbnail

NANOBANANA_MODEL

нет

Дефолтный tier: auto, nb2, pro, flash

Публикация новой версии

# 1. bump версии в pyproject.toml и nanobanana_2_polzaia_mcp_server/__init__.py
# 2. обновить CHANGELOG.md
# 3. прогнать быстрый smoke-test
PYTHONPYCACHEPREFIX=/tmp/pycache python3 -m compileall nanobanana_2_polzaia_mcp_server
uv build

# 4. публикация на PyPI
uv publish --token "$UV_PUBLISH_TOKEN"

# 5. публикация метаданных в MCP Registry
brew install mcp-publisher   # один раз
mcp-publisher login
mcp-publisher publish

MCP Registry хранит только метаданные, сам пакет должен лежать на PyPI.

Используемые эндпоинты Polza

  • POST /v1/media — запуск генерации

  • GET /v1/media/{id} — статус и результат (используется для fetch_generation и поллинга)

  • POST /v1/storage/upload — загрузка референса

  • GET /v1/storage/files/{id} — метаданные файла

  • DELETE /v1/storage/files/{id} — удаление файла

Лицензия

MIT. См. файл LICENSE.

Available Tools

5 tools
fetch_generationFetch a Polza media generation by idD
Read-only
ParametersJSON Schema
NameRequiredDescriptionDefault
media_idYesPolza generation id (e.g. 'gen_2158264963618050049'). Returned by the Polza API when an `images/generations` or `/v1/media` call switches to async mode or when the MCP client times out waiting for a synchronous response.
output_pathNoWhere to save the downloaded asset(s). If a file path with an extension is provided, saves the first asset there. If a directory is provided, saves using '<media_id>_<index>.<ext>'. If omitted, saves into IMAGE_OUTPUT_DIR.
waitNoIf true (default), polls until the generation reports 'completed' or 'failed', respecting POLZA_POLL_TIMEOUT_SECONDS. If false, returns the raw status without downloading.

TDQS

D1/5.0
Behavior1/5

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

Tool has no description.

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

Conciseness1/5

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

Tool has no description.

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

Completeness1/5

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

Tool has no description.

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

Parameters1/5

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

Tool has no description.

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

Purpose1/5

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

Tool has no description.

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

Usage Guidelines1/5

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

Tool has no description.

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

generate_imageGenerate or edit images (Multi-Model: Flash & Pro)A
Read-only

Generate new images or edit existing images using natural language instructions.

Supports multiple input modes:

  1. Pure generation: Just provide a prompt to create new images

  2. Multi-image conditioning: Provide up to 3 input images using input_image_path_1/2/3 parameters

  3. File ID editing: Edit previously uploaded images using Files API ID

  4. File path editing: Edit local images by providing single input image path

Automatically detects mode based on parameters or can be explicitly controlled. Input images are read from the local filesystem to avoid massive token usage. Returns both MCP image content blocks and structured JSON with metadata.

ParametersJSON Schema
NameRequiredDescriptionDefault
promptYesClear, detailed image prompt. Include subject, composition, action, location, style, and any text to render. Use the aspect_ratio parameter to pin a specific canvas shape when needed.
nNoRequested image count (model may return fewer).
negative_promptNoThings to avoid (style, objects, text).
system_instructionNoOptional system tone/style guidance.
input_image_path_1NoPath to first input image for composition/conditioning
input_image_path_2NoPath to second input image for composition/conditioning
input_image_path_3NoPath to third input image for composition/conditioning
file_idNoFiles API file ID to use as input/edit source (e.g., 'files/abc123'). If provided, this takes precedence over input_image_path_* parameters for the primary input.
modeNoOperation mode: 'generate' for new image creation, 'edit' for modifying existing images. Auto-detected based on input parameters if not specified.auto
model_tierNoModel tier: 'flash' (legacy, 1024px), 'nb2' (4K at Flash speed, default), 'pro' (max quality, 4K), or 'auto' (smart selection). Default: 'auto' - automatically selects nb2 or pro based on prompt.auto
resolutionNoOutput resolution: 'high', '4k', '2k', '1k'. 4K and 2K available with 'nb2' and 'pro' models. Default: '1k'.1k
thinking_levelNoReasoning depth hint: 'low' (faster), 'high' (better quality). Applied to the 'nb2' model; 'high' also biases auto-selection toward Pro. Default: None (auto).
enable_groundingNoEnable Google Search grounding for factual accuracy (NB2 and Pro models). Useful for real-world subjects. Default: true.
aspect_ratioNoOptional output aspect ratio (e.g., '16:9'). Polza-supported values: auto, 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9.
output_pathNoOutput path for generated image(s). If a file path with extension (e.g., '/path/image.png'), saves directly to that path. If a directory path (e.g., '/path/to/dir/'), uses default filename in that directory. If None, uses IMAGE_OUTPUT_DIR environment variable or ~/nanobanana-images.
return_full_imageNoReturn full-resolution images in MCP response instead of thumbnails. Warning: full images can be large (3-7MB each for 4K). Default: uses RETURN_FULL_IMAGE env var, or false if not set.
force_new_generationNoStart a brand-new upstream generation even if the same request is already pending or recently completed. Use only after the user explicitly confirmed they want a rerun.

TDQS

A3.8/5.0
Behavior2/5

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

Annotations declare readOnlyHint=true, but description indicates mutation ('generate new images or edit existing images'), creating a contradiction. Beyond that, description discloses input file handling and return format. The contradiction significantly undermines transparency.

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

Conciseness3/5

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

Description is structured with bullet list of modes but somewhat verbose. Key information is front-loaded (first sentence captures core), but some redundancy exists (e.g., 'Supports multiple input modes:' followed by list). Adequate but not terse.

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 complex tool with 17 parameters and no output schema, the description covers input modes, auto-detection, return type (MCP image blocks + metadata), and parameter interactions. Lacks details about metadata structure but adequate for selection and invocation.

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?

All 17 parameters have schema descriptions, so baseline is 3. Description adds value by explaining inter-parameter relationships (e.g., file_id takes precedence over input_image_path_*) and operational context (mode auto-detection).

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?

Description clearly states verb+resource: 'Generate new images or edit existing images using natural language instructions.' It lists four specific modes and distinguishes from sibling tools (fetch_generation, maintenance, show_output_stats, upload_file) by focusing on creation/editing.

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?

Explicitly describes when to use each mode (pure generation, multi-image conditioning, file ID editing, file path editing), including auto-detection logic. No explicit when-not or alternatives, but the context is clear enough for an agent to decide.

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

maintenanceMaintenance and cleanup operationsB
Read-only

Perform maintenance operations following workflows.md patterns.

Available operations:

  • cleanup_expired: Remove expired Files API entries from database

  • cleanup_local: Clean old local files based on age/LRU

  • check_quota: Check Files API storage usage vs. ~20GB budget

  • database_hygiene: Clean up database inconsistencies

  • full_cleanup: Run all cleanup operations in sequence

ParametersJSON Schema
NameRequiredDescriptionDefault
operationYesMaintenance operation to perform: 'cleanup_expired', 'cleanup_local', 'check_quota', 'database_hygiene', 'full_cleanup'
dry_runNoIf true, only report what would be done without making changes
max_age_hoursNoFor local cleanup: maximum age in hours (default: 168 = 1 week)
keep_countNoFor local cleanup: minimum number of recent files to keep

TDQS

B3.1/5.0
Behavior1/5

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

The annotations declare readOnlyHint=true (suggesting no side effects), but the description lists destructive operations like 'cleanup_expired: Remove expired Files API entries' and 'cleanup_local: Clean old local files', implying data deletion. This is a clear contradiction. Additionally, no disclosure of auth requirements or rate 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?

The description is short and uses a bullet list for operations, aiding readability. It is front-loaded with 'Perform maintenance operations'. The reference to 'workflows.md patterns' is vague but does not significantly detract. Every sentence contributes, though the external reference could be clarified.

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?

No output schema is present, and the description does not explain what the tool returns (e.g., a report, status, or nothing). For destructive operations, knowing the output type is important. The dry_run parameter hints at reporting, but the default behavior is unspecified. The tool's impact on data is described, but consequences (e.g., irreversible deletion) are not highlighted.

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

Parameters3/5

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

Schema description coverage is 100%, so parameters are already well-documented. The description adds marginal value by listing operation names with one-line summaries (e.g., 'check_quota: Check Files API storage usage'), which slightly enriches understanding beyond the schema's plain enumeration. However, for dry_run, max_age_hours, and keep_count, no additional semantics are provided.

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 'Perform maintenance operations' and enumerates five specific operations with brief explanations (e.g., 'Remove expired Files API entries'). This distinguishes it from sibling tools (fetch_generation, generate_image, etc.) which are unrelated. The title 'Maintenance and cleanup operations' reinforces the resource.

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 references 'following workflows.md patterns', implying a prescribed usage context, but does not explicitly state when to use this tool versus alternatives (e.g., when to choose cleanup_expired vs. cleanup_local). No when-not-to-use guidance is provided, though sibling tools are unrelated, so confusion is minimal.

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

show_output_statsShow output directory statsA
Read-only

Show statistics about the output directory and recently generated images.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A3.8/5.0
Behavior3/5

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

Annotations already provide readOnlyHint=true. Description adds context about showing stats for output directory and recent images, which aligns with read-only behavior but does not disclose potential performance impact or data freshness limits.

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?

Single, front-loaded sentence with no unnecessary words. Every part earns its place.

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 no parameters, annotations (readOnlyHint), and no output schema, the description is mostly complete. It explains the tool's purpose but could mention what specific statistics are returned (e.g., file count, disk usage) for fuller context.

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?

No parameters exist; the input schema is empty. With 0 parameters, the baseline is 4. The description adds no parameter information, but none is needed.

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 'Show statistics about the output directory and recently generated images', specifying the verb (show) and resource (statistics, output directory, images). It distinguishes from siblings like generate_image (creation) and fetch_generation (specific retrieval).

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

Usage Guidelines2/5

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

No guidance on when to use this tool versus alternatives. Sibling tools are listed but the description does not explain when to prefer show_output_stats over fetch_generation or maintenance.

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

upload_fileUpload file to Polza Storage APIA

Upload a local file through the Polza Storage API and return its URI & metadata. Useful when the image is larger than 20MB or reused across prompts.

ParametersJSON Schema
NameRequiredDescriptionDefault
pathYesServer-accessible file path to upload to Polza Storage API.
display_nameNoOptional display name for the uploaded file.

TDQS

A4/5.0
Behavior3/5

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

Annotations show readOnlyHint=false, confirming it is a write operation. The description adds that it 'returns URI & metadata' but does not disclose potential side effects, authentication requirements, or failure behaviors. With annotations already indicating a write operation, the description provides marginal additional context.

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 two sentences, tightly worded, and front-loads the primary action and result. Every sentence serves a purpose—stating what the tool does and when to use it.

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 low complexity (2 params, no output schema, no nested objects), the description covers the main goal and usage context. It mentions file size threshold and reusability, but lacks details on metadata format or file type constraints. Still, it is sufficient for an agent to select and invoke the tool correctly.

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

Parameters3/5

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

Schema coverage is 100% with descriptions for both parameters. The description does not add significant meaning beyond the schema; it reaffirms the path is 'Server-accessible' and display_name is optional. Baseline 3 is appropriate as the schema already documents the parameters thoroughly.

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 action ('Upload a local file'), the resource ('to Polza Storage API'), and the return value ('URI & metadata'). It also provides a specific use case, distinguishing it from sibling tools that focus on generation, maintenance, or statistics.

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 includes explicit guidance on when to use the tool: 'when the image is larger than 20MB or reused across prompts.' It does not mention alternatives or when not to use, but the context is clear given sibling tools have distinct purposes.

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

TDQS

C2.4/5.0
Disambiguation2/5

Most tools have clear descriptions, but 'fetch_generation' lacks any description, creating ambiguity about its purpose and potential overlap with 'generate_image'. This makes it hard for an agent to distinguish between them.

Naming Consistency3/5

Tool names consistently use snake_case, but they mix verb and noun forms (e.g., 'maintenance' is a noun while others are verb+noun). The pattern is partially predictable but not fully uniform.

Tool Count4/5

With 5 tools, the server covers core image generation and file management tasks reasonably well. The count is appropriate for a focused service, though not overly extensive.

Completeness2/5

The tool set lacks a way to list or delete previously generated images, and 'fetch_generation' is undefined. This leaves significant gaps in the lifecycle, likely causing agent failures during cleanup or retrieval tasks.

Maintenance

ActivityInactive
ResponsivenessNo issues

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/ivanantigravity-lgtm/nanobanana-2-polzaia-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server