opencode-image-mcp
Provides image generation using Google Gemini's image models via its OpenAI-compatible endpoint, with model auto-discovery and file output.
Provides image generation using OpenAI's image models (e.g., gpt-image, dall-e) via the Images API, with model auto-discovery and file output.
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., "@opencode-image-mcp Make me a corgi astronaut in 16:9."
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.
opencode-image-mcp
A multi-provider image generation MCP server. Point it at any OpenAI-compatible API, let it auto-detect the image models each provider offers, pick the model you ask for, then generate and wait for the result — saving the image to disk and returning its path (optionally inline).
It is a generalized, hardened take on the popular single-provider
openrouter-image-mcp: instead of one hardcoded vendor, it speaks both common
OpenAI-compatible dialects and works with OpenAI, OpenRouter, Google Gemini,
xAI, Together, DeepInfra, SiliconFlow, Fireworks, or any custom endpoint you
configure.
Bring your own endpoint
No preset required. Hand the agent a base URL and it registers the endpoint, discovers its models, and remembers it:
Use
https://api.example.com/v1with keysk-abc123and call itexample.
The agent calls add_provider, which:
probes
https://api.example.com/v1/models,keeps only the models that can produce images,
saves the endpoint (and key) to the gitignored config file,
sets that model as the default.
From then on, in this session and every future run:
Make me a corgi astronaut in 16:9.
...resolves straight to your endpoint. If the endpoint exposes several image
models, the agent inspects the list and calls set_default_model to pick one.
Endpoints without a /models route still work — pass default_model and
discover=false.
Related MCP server: image-gen-mcp
Features
Any OpenAI-compatible provider — built-in presets plus arbitrary custom base URLs.
Two API dialects, auto-selected — the classic Images API (
/images/generations,/images/edits) and the chat-completionsmodalities: ["image","text"]style used by aggregators. Includes automatic chat fallback when a provider rejects the Images endpoint.Model auto-discovery — queries each provider's model endpoint, filters to image-capable models, and caches the result on disk. OpenRouter's dedicated
/images/modelscapability metadata is used when available.Flexible model selection —
provider:model, bare model ids searched across providers, or user-defined aliases.Waits for slow jobs — long timeouts, retry with backoff on
429/5xx(honouringRetry-After), and generic polling for providers that return a job id instead of an image.Robust output handling — base64, data URLs and hosted URLs; MIME/extension detection from magic bytes; multi-image
_2/_3suffixes; never clobbers existing files.Friendly errors — 401/402/404/413/429/5xx and timeouts all become clear, actionable messages naming the provider and model.
Inline previews on demand — return file paths by default, or embed the generated image in the tool result so the model can see it.
Small footprint — Python + the MCP SDK +
httpx. Nothing else.
Supported providers (optional presets)
These presets are just convenient shortcuts — none of them are required, and the custom-endpoint flow above works with any OpenAI-compatible API.
Provider | Dialect | Model list endpoint | Notes |
| images |
|
|
| images + chat |
| capability-aware; Gemini/GPT/Flux/Seedream via one key |
| images |
| Google's OpenAI-compatible endpoint |
| images |
| Grok Imagine; returns hosted URLs |
| images |
| FLUX and friends ( |
| images |
| FLUX ( |
| images |
|
|
| images |
|
|
| any | configurable | LM Studio, vLLM, ComfyUI gateway, proxies… |
A provider becomes active the moment its API key env var is set. Unconfigured
presets are listed as configured: false and skipped.
Install
Requires Python 3.10+ and (recommended) uv.
From a git URL
uv tool install --from git+https://github.com/you/opencode-image-mcp opencode-image-mcpFrom a local checkout
git clone https://github.com/you/opencode-image-mcp
cd opencode-image-mcp
uv tool install --reinstall --from . opencode-image-mcpTwo ways to launch it:
the console script
opencode-image-mcpthe module entry point
python -m opencode_image_mcp(more reliable on Windows, where the generated.exelauncher can miss the venv's site-packages)
Find the tool's venv Python with uv tool dir, then use it in your client
config as shown below.
Run from source without installing
uv venv
uv pip install -e ".[dev]"
python -m opencode_image_mcpConfigure
1. API keys (environment variables)
Set any subset; each one enables that provider:
OPENAI_API_KEY=sk-...
OPENROUTER_API_KEY=sk-or-v1-...
GEMINI_API_KEY=... # GOOGLE_API_KEY also accepted
XAI_API_KEY=xai-...
TOGETHER_API_KEY=...
DEEPINFRA_API_KEY=...
SILICONFLOW_API_KEY=...
FIREWORKS_API_KEY=...2. Server settings (optional)
Variable | Default | Purpose |
| the workspace (current directory) | Default save directory |
|
| Per-request timeout in seconds |
|
| Retry attempts for |
|
| Model-list cache TTL in seconds |
|
| Where the model cache lives |
|
| Extra config file |
| — | Configure the |
| — | Point the |
|
| Logging level (logs go to stderr) |
3. Custom providers, aliases and defaults (providers.json)
Copy providers.example.json and edit. Only the keys you set are changed.
{
"default_model": "openrouter:google/gemini-3.1-flash-image-preview",
"aliases": {
"nb2": "openrouter:google/gemini-3.1-flash-image-preview",
"fast": "gemini:gemini-2.5-flash-image"
},
"settings": { "output_dir": "./generated", "timeout_s": 300 },
"providers": {
"local": {
"base_url": "http://localhost:8000/v1",
"dialect": "images",
"api_key_env": null,
"default_model": "flux-schnell",
"include_models": ["flux", "sdxl"],
"aspect_ratio_mode": "size"
},
"comfy": {
"base_url": "http://localhost:8188/openai/v1",
"dialect": "chat",
"default_model": "comfy-image",
"poll": {
"url_template": "{base_url}/jobs/{id}",
"status_field": "status",
"done_values": ["completed", "done", "succeeded"],
"failed_values": ["failed", "error", "cancelled"],
"result_url_field": "result_url",
"interval_s": 2,
"max_interval_s": 10
}
},
"together": null
}
}Set a provider to null to disable a preset. Setting api_key_env to null
marks a provider as anonymous (no key required) — handy for local servers.
Where runtime additions are stored: add_provider writes to
IMAGE_MCP_CONFIG when set, otherwise ~/.config/opencode-image-mcp/providers.json.
A key passed to add_provider is stored inline in that file. It is gitignored
and blocked by the pre-commit hook, so it never reaches the cloud — but keep the
file out of shared/backup folders if you would rather the key not sit on disk.
Provider keys: base_url, dialect, default_model, label, api_key,
api_key_env, alt_api_key_envs, auth_header, auth_scheme, models_path,
image_models_path, generation_path, edit_path, chat_path, edit_style,
aspect_ratio_mode, size_style, size_param, send_response_format,
chat_modalities, include_models, exclude_models, extra_headers,
extra_query, allow_chat_fallback, poll. Unknown keys are rejected so typos
surface immediately.
Field | Meaning |
|
|
|
|
|
|
|
|
| regex allow/deny applied to model ids |
| e.g. Azure-style |
| e.g. |
| enables waiting for async job APIs |
Wire it into your MCP client
Replace the path with the tool venv's Python (uv tool dir → .../Scripts/python.exe
on Windows, .../bin/python elsewhere).
opencode / Claude Code (~/.claude.json)
{
"mcpServers": {
"opencode-image": {
"command": "C:/Users/YOU/AppData/Roaming/uv/tools/opencode-image-mcp/Scripts/python.exe",
"args": ["-m", "opencode_image_mcp"],
"env": {
"OPENROUTER_API_KEY": "sk-or-v1-...",
"OUTPUT_DIR": "C:/Users/YOU/Pictures/generated"
}
}
}
}Claude Desktop (claude_desktop_config.json)
{
"mcpServers": {
"opencode-image": {
"command": "/Users/YOU/.local/share/uv/tools/opencode-image-mcp/bin/python",
"args": ["-m", "opencode_image_mcp"],
"env": { "OPENAI_API_KEY": "sk-..." }
}
}
}Cursor (.cursor/mcp.json)
{
"mcpServers": {
"opencode-image": {
"command": "/path/to/uv/tools/opencode-image-mcp/bin/python",
"args": ["-m", "opencode_image_mcp"],
"env": { "GEMINI_API_KEY": "..." }
}
}
}Generic stdio client
Set the env vars in the parent shell and run python -m opencode_image_mcp.
Tools
list_providers
No arguments. Returns every known provider with configured, key_env,
dialect, default_model, supports_edit and polls_async_jobs, plus the
effective default model and aliases.
list_models(provider=None, refresh=False)
Discovers image models from configured providers, cached on disk. Each entry
has provider, id, full_id, name, source and, when the provider exposes
them, capabilities and pricing. Errors per provider are returned under
errors. Use refresh=true to bypass the cache.
add_provider(...)
Register any OpenAI-compatible image endpoint at runtime. It probes
{base_url}/models, filters to image models, persists the provider to the
config file, and makes it usable immediately and in future sessions.
Parameter | Type | Default | Description |
| string | required | Short handle for |
| string | required | API root, e.g. |
| string |
| Bearer token, stored in the gitignored config file |
| string |
| Read the key from an env var instead (ignored if |
| string |
| Model to use by default; auto-picked if exactly one image model is found |
| string |
|
|
| bool |
| Also set this as the global default model |
| object |
| Extra request headers |
| string[] |
| Regex allow/deny applied to discovered model ids |
| string |
|
|
| string |
|
|
| bool |
| Set |
Returns the discovered models, the chosen default_model, key_source,
warnings and the saved_to path. The key is never echoed back.
set_default_model(model)
Persist the model used when generate_image is called without one, e.g.
example:flux-schnell. Saved to the config file, so it applies to future runs.
remove_provider(id)
Remove a provider (including a built-in preset) from the config file. Clears the default model if it pointed at that provider.
generate_image(...)
Parameter | Type | Default | Description |
| string | required | Image description, or an edit instruction with input images |
| string | config default |
|
| string |
| e.g. |
| string |
| Explicit size, e.g. |
| string |
|
|
| int |
| Number of images |
| string |
| Exact file, a directory, or omitted for the workspace directory |
| string |
| Stem for auto-generated names |
| string |
| One reference image → edit mode |
| string[] |
| Multiple references (where supported) |
| string |
|
|
| string |
|
|
| int |
| Deterministic generation (where supported) |
| bool |
| Also embed the image in the result |
| float |
| Override the configured timeout |
| object |
| Escape hatch: merged into the request body |
Return shape (also available as structured_content):
{
"file_paths": ["C:/.../corgi_20260926_120000.png"],
"provider": "openrouter",
"model_id": "google/gemini-3.1-flash-image-preview",
"dialect": "images",
"mode": "generate",
"prompt": "a corgi astronaut",
"aspect_ratio": "16:9",
"image_count": 1,
"elapsed_ms": 8421,
"usage": { "prompt_tokens": 22, "completion_tokens": 1500, "cost": 0.06834 },
"cost_usd": 0.06834
}Example prompts
Generate a cinematic corgi astronaut in 16:9 using
openrouter:google/gemini-3.1-flash-image-preview.
List the image models my providers offer, then use the cheapest one.
Take
./photo.jpgand remove the background, save to./cutout.png.
How model selection works
provider:model— explicit and unambiguous. No discovery needed.Bare model id — the server searches every configured provider's cached catalogue (exact, then case-insensitive, then suffix match). If several providers match, it lists the candidates and asks you to pick one.
Alias — any key from
aliasesinproviders.json.Omitted —
default_modelfrom config, else the first configured provider's default.
Discovery uses OpenRouter's authoritative /images/models capability metadata
when available; otherwise it filters model ids by image-family heuristics
(flux, dall-e, gpt-image, seedream, imagen, grok-imagine,
qwen-image, …) refined by your include_models/exclude_models regexes.
Waiting for the response
Requests use a generous timeout (default 300s) — image generation is slow.
429/5xxand network errors are retried with exponential backoff and jitter, honouringRetry-After.If a provider answers with a job id instead of an image, configure
polland the server will poll until the job completes, then fetch the result (inline or viaresult_url).
Troubleshooting
Symptom | Fix |
| No API keys visible. Set them in the client's |
| Wrong/expired key for that provider; check the named env var. |
| Unsupported parameter for that model — drop |
| Model uses the other dialect; try another model/provider (chat fallback is automatic where possible). |
| The model answered with text (refusal or chatter). Rephrase or switch model. |
Wrong extension | Never happens by design — extensions come from magic bytes, not the URL. |
| Use |
Development
The test suite is local only — tests/ is gitignored and never committed.
uv venv
uv pip install -e ".[dev]"
python -m pytestLayout:
src/opencode_image_mcp/
config.py # presets, providers.json read/write, env, Settings
registry.py # model discovery, cache, resolution
dialects.py # images/chat request builders + response parsers
transport.py # httpx client, retries/backoff, downloads, polling
images.py # MIME sniffing, decode, save
errors.py # friendly error mapping
server.py # MCP toolsThe tests mock HTTP with httpx.MockTransport, so they run offline and cost
nothing.
Repository safety (keeping keys out of the cloud)
.env and providers.json are gitignored, so real keys and custom endpoints
never get committed. That is backed by a pre-commit hook in .githooks/ which
also catches git add -f and any staged diff that looks like a live API key.
The tests/ directory is gitignored too: it stays on your machine for local
runs and is never committed.
The hooks path is local git config, so enable it once per clone:
git config core.hooksPath .githooksThen verify:
git check-ignore -v .env providers.json # both should be listedBypass only if you are certain: git commit --no-verify.
Companion skill
skills/image-generation/SKILL.md is an optional agent skill with a model
selection decision tree, prompt-engineering tips, aspect-ratio guidance and
common pitfalls. Install it by copying the folder into your client's skills
directory.
License
MIT — see LICENSE.
Available Tools
6 toolsadd_providerAdd a custom providerAIdempotent
Register any OpenAI-compatible image endpoint and remember it for later.
Use this when the user names an endpoint like https://api.example.com/v1.
The server probes {base_url}/models, figures out which models can produce
images, saves the provider to the config file, and makes it available to
generate_image immediately and on every future run.
Parameters
id:
Short handle used in provider:model specs (e.g. example).
Lowercase letters, digits, - and _.
base_url:
The OpenAI-compatible API root, e.g. https://api.example.com/v1.
api_key:
Optional bearer token, stored in the gitignored config file so it
survives restarts. Prefer api_key_env if you would rather keep the
secret in an environment variable.
api_key_env:
Name of an env var holding the key (ignored when api_key is given).
Leave both unset for endpoints that need no auth.
default_model:
Model id to use by default. If omitted and exactly one image model is
found, it is selected automatically.
dialect:
auto (default), images (/images/generations) or chat
(/chat/completions with image modalities). auto uses the Images
API and transparently falls back to chat-completions on 404/405.
make_default:
Also set this provider's model as the global default model.
discover:
Set false to skip the /models probe (required for endpoints
that do not implement it).
Returns the discovered models plus any warnings; inspect models and, if
there are several, call set_default_model to choose one.
Inputs: id (required), base_url (required), api_key, dialect, +9 more. Returns: object
generate_imageGenerate or edit an imageA
Generate an image, or edit existing images, via an OpenAI-compatible provider.
Model selection
model accepts three forms:
provider:model— explicit, e.g.openrouter:google/gemini-3.1-flash-image-preview,openai:gpt-image-1,xai:grok-imagine-image-2.0. Fastest and unambiguous.a bare model id — searched across every configured provider's catalogue (run
list_modelsfirst). Ambiguous ids raise an error listing candidates.an alias — defined in
providers.json(e.g.nb2).
If omitted, the configured default model is used.
Editing
Pass input_image_path (and optionally input_image_paths) and the
prompt becomes an edit instruction. Requirements vary by provider.
Output
Images are always written to disk and their paths returned. Set
return_image_content=true to additionally embed the images in the tool
result so the model can look at them.
Inputs: prompt (required), n, seed, size, +12 more.
list_modelsList image modelsARead-onlyIdempotent
Discover image-capable models offered by configured providers.
Queries each provider's model endpoint, filters to image models, and caches
the result on disk. Set refresh=true to bypass the cache. Pass
provider to query just one provider.
Inputs: refresh, provider. Returns: object
list_providersList image providersARead-onlyIdempotent
List configured image providers and whether their API key is present.
A provider only appears as configured: true once its key env var is set.
Use the returned id values as the prefix in provider:model specs.
Inputs: no named parameters. Returns: object
remove_providerRemove a providerAIdempotent
Remove a provider (including built-in presets) from the config file.
Inputs: id (required). Returns: object
set_default_modelSet the default modelAIdempotent
Persist the model used when generate_image is called without one.
model is a provider:model spec or an alias, e.g.
example:flux-schnell. The choice is saved to the config file so it
applies to future runs.
Inputs: model (required). Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 6 tools
Each tool serves a distinct function: discovery (list_models, list_providers), provider lifecycle management (add_provider, remove_provider), configuration (set_default_model), and the core action (generate_image). There is no overlap or ambiguity in purpose.
All tool names follow a consistent snake_case verb_noun pattern: list_models, list_providers, add_provider, remove_provider, set_default_model, generate_image. The naming style is uniform and predictable.
Six tools is well-scoped for an image generation MCP server. Each tool earns its place and covers provider management, model discovery, default selection, and generation without redundancy.
The tool surface covers the full lifecycle: configure providers (add/remove/list), discover models (list_models), set defaults, and generate/edit images. No obvious gaps exist for the server's stated purpose.
Maintenance
Related MCP Connectors
Generate AI images, videos, music, SFX & speech in any AI assistant. Results appear inline in chat.
Generate AI images and videos from any compatible MCP client.
Generate images with your own ChatGPT subscription (Plus, Pro or Team), without spending API credits
Generate AI images, video, music, and sound effects, and upscale them, from any MCP client.
Related MCP Servers
- AlicenseAqualityDmaintenanceEnables image analysis, OCR, and text-to-image generation through OpenAI-compatible APIs. Supports local paths, URLs, or base64 images with configurable models and backup endpoints.3MIT
- AlicenseAqualityDmaintenanceEnables generating and editing images through OpenAI image models, with configurable output as saved files or returned URLs.2MIT
- AlicenseNot gradedqualityCmaintenanceEnables image generation through any OpenAI-compatible images/generations endpoint, saving results to disk and returning them inline for the model.MIT
- AlicenseNot gradedqualityCmaintenanceEnables text-to-image generation and image-to-image editing through the built-in relay or any OpenAI-compatible endpoint, with fast and high-precision models, square and custom-dimension sizes up to true 4K, and quality controls. Generated or edited images are written to local directories and returned as absolute file paths.46 npmMIT