Nano Banana 2 Polza MCP Server
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Nano Banana 2 Polza MCP ServerGenerate a realistic image of a white wolf in a snowy forest"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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-клиентuvPython 3.11+POLZA_AI_API_KEY(токен аккаунта Polza)
Быстрая установка за 2 минуты
Для Claude Code / VS Code:
Установите
uv(brew install uvна macOS).В корне проекта создайте файл
.mcp.json.Вставьте конфиг и подставьте свой 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.
Если такое случилось:
Посмотрите
gen_...id в веб-интерфейсе Polza (раздел генераций).Вызовите
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.serverClaude 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 API |
| нет | База API, по умолчанию |
| нет | Директория для сохранённых файлов, по умолчанию |
| нет | Интервал поллинга статуса, по умолчанию |
| нет | Таймаут ожидания генерации, по умолчанию |
| нет | Передаётся в Polza как |
| нет | Возвращать полное изображение в MCP-ответе вместо thumbnail |
| нет | Дефолтный tier: |
Публикация новой версии
# 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 publishMCP 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 toolsfetch_generationFetch a Polza media generation by idDRead-only
| Name | Required | Description | Default |
|---|---|---|---|
| media_id | Yes | Polza 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_path | No | Where 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. | |
| wait | No | If true (default), polls until the generation reports 'completed' or 'failed', respecting POLZA_POLL_TIMEOUT_SECONDS. If false, returns the raw status without downloading. |
TDQS
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.
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.
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.
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.
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.
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)ARead-only
Generate new images or edit existing images using natural language instructions.
Supports multiple input modes:
Pure generation: Just provide a prompt to create new images
Multi-image conditioning: Provide up to 3 input images using input_image_path_1/2/3 parameters
File ID editing: Edit previously uploaded images using Files API ID
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.
| Name | Required | Description | Default |
|---|---|---|---|
| prompt | Yes | Clear, 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. | |
| n | No | Requested image count (model may return fewer). | |
| negative_prompt | No | Things to avoid (style, objects, text). | |
| system_instruction | No | Optional system tone/style guidance. | |
| input_image_path_1 | No | Path to first input image for composition/conditioning | |
| input_image_path_2 | No | Path to second input image for composition/conditioning | |
| input_image_path_3 | No | Path to third input image for composition/conditioning | |
| file_id | No | Files 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. | |
| mode | No | Operation mode: 'generate' for new image creation, 'edit' for modifying existing images. Auto-detected based on input parameters if not specified. | auto |
| model_tier | No | Model 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 |
| resolution | No | Output resolution: 'high', '4k', '2k', '1k'. 4K and 2K available with 'nb2' and 'pro' models. Default: '1k'. | 1k |
| thinking_level | No | Reasoning depth hint: 'low' (faster), 'high' (better quality). Applied to the 'nb2' model; 'high' also biases auto-selection toward Pro. Default: None (auto). | |
| enable_grounding | No | Enable Google Search grounding for factual accuracy (NB2 and Pro models). Useful for real-world subjects. Default: true. | |
| aspect_ratio | No | Optional 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_path | No | Output 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_image | No | Return 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_generation | No | Start 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
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.
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.
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.
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.
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.
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 operationsBRead-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
| Name | Required | Description | Default |
|---|---|---|---|
| operation | Yes | Maintenance operation to perform: 'cleanup_expired', 'cleanup_local', 'check_quota', 'database_hygiene', 'full_cleanup' | |
| dry_run | No | If true, only report what would be done without making changes | |
| max_age_hours | No | For local cleanup: maximum age in hours (default: 168 = 1 week) | |
| keep_count | No | For local cleanup: minimum number of recent files to keep |
TDQS
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.
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.
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.
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.
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.
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 statsARead-only
Show statistics about the output directory and recently generated images.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
TDQS
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.
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.
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.
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.
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.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | Server-accessible file path to upload to Polza Storage API. | |
| display_name | No | Optional display name for the uploaded file. |
TDQS
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.
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.
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.
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.
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.
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.
5 tool updates
v0.5.1- First observed
fetch_generation - First observed
generate_image - First observed
maintenance - First observed
show_output_stats - First observed
upload_file
TDQS
Scored across 5 tools
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.
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.
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.
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
Related MCP Connectors
MCP server for NanoBanana AI image generation and editing
MCP server for Qwen Image 3 AI image generation
MCP server for Wan AI video generation
MCP server for Google Veo AI video generation
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceAn MCP server that provides image generation using Google's Nano Banana Gemini models, with additional tools for background removal, upscaling, and format conversion via deterministic post-processing.1MIT
- AlicenseAqualityDmaintenanceMCP server for Google Gemini image generation with configurable model support, enabling text-to-image generation, image editing, and iterative refinement.640MIT
- AlicenseNot gradedqualityDmaintenanceMCP server for Google's Nano Banana image generation models (Gemini). Generate and edit images via natural language.8 npm1MIT
- AlicenseAqualityDmaintenanceMCP server for generating and editing images using Google Gemini API, with support for multi-turn iterative refinement.325 npmMIT