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.2/5.0
Behavior1/5

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

Annotations declare readOnlyHint=true, but the description explicitly describes destructive actions like 'Remove expired Files API entries from database' and 'Clean old local files'. This is a direct annotation contradiction, which the rubric requires scoring as 1, and the description also fails to disclose irreversibility or safety implications beyond the dry_run parameter in the schema.

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 compact and front-loaded with a clear purpose, followed by a well-structured bullet list of operations. The phrase 'following workflows.md patterns' is somewhat ambiguous and could be clearer, but overall every line adds useful information without unnecessary verbosity.

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 the tool has four parameters, multiple operation modes, and no output schema, the description covers the operation choices reasonably well. However, it relies on a vague external reference, does not describe return values or success/failure behavior, and the readOnlyHint contradiction makes the safety profile incomplete for an agent deciding whether to invoke it.

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 the input schema already fully documents operation, dry_run, keep_count, and max_age_hours. The description adds a helpful mapping of operation names to behaviors, but does not provide extra parameter semantics beyond what the schema already gives, so it stays at the baseline.

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 names a specific resource ('maintenance operations') and enumerates each concrete sub-operation with a verb and object, such as 'Remove expired Files API entries from database' and 'Check Files API storage usage'. It is clearly distinguishable from sibling tools like generate_image and upload_file, so an agent can tell what this tool does without opening the schema.

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 this tool is for maintenance and cleanup tasks, but it does not explicitly state when to use it versus sibling tools or when to prefer one operation over another. The reference to 'following workflows.md patterns' gives some context but is vague and does not provide concrete selection criteria or exclusions.

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.7/5.0
Behavior3/5

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

The annotations already declare readOnlyHint=true, and the description's use of 'Show' is consistent with that. It adds useful scoping around output directory and recently generated images, but it does not disclose output format, potential cost, or hidden scanning behavior. Given the read-only annotation, a mid-range score is appropriate.

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 a single, front-loaded sentence with no filler, repetition, or unnecessary detail. It communicates the verb, resource, and scope efficiently.

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 zero-parameter, read-only stats tool, the description adequately states what the tool operates on and what it returns at a high level. No output schema exists, so 'statistics' is somewhat vague, but the tool is simple enough that an agent can select and invoke it correctly without more detail.

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 tool has zero parameters, so there is no parameter behavior to explain. The baseline of 4 applies here because the description does not need to compensate for missing parameter documentation.

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?

The description uses a specific verb ('Show') and clearly identifies the resource ('statistics about the output directory and recently generated images'). It is clearly distinct from generate_image and upload_file, but it does not explicitly differentiate itself from fetch_generation or maintenance.

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 a monitoring use case for checking output directory stats, but it provides no explicit when-to-use guidance or exclusions. Sibling tools like fetch_generation are not referenced as alternatives, so an agent must infer when this tool is appropriate.

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.1/5.0
Behavior3/5

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

Annotations already indicate readOnlyHint=false, so the write behavior is known. The description adds return value details ('URI & metadata') and a practical constraint (20MB/reuse context), but does not disclose side effects like persistence, overwriting, or authentication requirements. Adds moderate value beyond annotations without contradicting them.

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?

Two sentences with no wasted words: the first states the action and outcome, the second gives practical usage guidance. Front-loaded and highly scannable.

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

Completeness5/5

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

For a simple two-parameter upload tool with full schema coverage and no nested objects, the description is complete. It explains what the tool does, what it returns, and when to use it. No output schema exists, but the return format is explicitly mentioned.

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%, and both parameters already have clear descriptions. The tool description adds minimal parameter-level context beyond the schema, so it stays at the baseline.

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 states a specific verb ('Upload'), a clear resource ('a local file through the Polza Storage API'), and the expected outcome ('return its URI & metadata'). This clearly distinguishes it from siblings like generate_image and fetch_generation, which do different things.

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?

Provides explicit use conditions: 'Useful when the image is larger than 20MB or reused across prompts.' This gives clear context for when to invoke the tool, though it does not name alternative tools or explicitly state when not to use it.

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. 5 tool updatesv0.5.1
    • First observedfetch_generation
    • First observedgenerate_image
    • First observedmaintenance
    • First observedshow_output_stats
    • First observedupload_file

TDQS

C2.4/5.0

Scored across 5 tools

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

Related MCP Connectors

Related MCP Servers