Skip to main content
Glama
Jhonys

imagine-mcp

by Jhonys
README.md
# imagine-mcp

A [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server for image generation via the [OpenRouter](https://openrouter.ai) API.

Designed to work with **Cline**, **VS Code GitHub Copilot**, and **Claude Code**. Generate high-quality images directly from your editor and save them into the repository you're currently working in — no copy/paste, no context bloat.

## Features

- **4 curated models** with clear pricing and best-use cases (from **$0.04/image**)
- **Saves to disk by default** into `assets/generated-images/` of the current workspace
- **Context-friendly**: returns only metadata (path, size, media type) unless you explicitly request base64
- **Per-model validation**: catches unsupported `aspect_ratio` / `resolution` / `output_format` / `n` *before* calling the API
- **Cost transparency**: reports API cost when available, estimates it otherwise
- **Retry with backoff** for `429` / `5xx` / network errors
- **Advanced `image_config`** support (custom fonts, scoring rubrics, background color) for models that accept it
- **`list_generated_images`** tool so the assistant can reference images already produced
- **Configurable default model** via env var (cheapest by default)

## Available models

| Model ID | Name | Best for | Pricing | Max `n` |
|---|---|---|---|---|
| `bytedance-seed/seedream-4.5` | Seedream 4.5 | Cheap general use, portraits, small text | **$0.04/image** (flat) | 4 |
| `x-ai/grok-imagine-image-quality` | Grok Imagine | Photorealism, posters, text in images | from **$0.05/image** | 4 |
| `recraft/recraft-v4.1-vector` | Recraft v4.1 Vector | Logos, icons, SVG | **$0.08/image** | 1 |
| `sourceful/riverflow-v2.5-fast` | Riverflow v2.5 Fast | Quick iterations, brand-aligned variations | dynamic | 4 |

> For per-model prompting best practices, see [`docs/model-guides.md`](docs/model-guides.md).

## Prerequisites

- Node.js **>= 18**
- An OpenRouter API key — get one at https://openrouter.ai/keys

## Installation

### Option A — Use directly via `npx` (recommended, no clone needed)

The MCP clients below can launch the server with `npx -y imagine-mcp`. No local install required.

### Option B — Clone & build locally

```bash
git clone <your-repo-url> imagine-mcp
cd imagine-mcp
npm install
npm run build
```

## Client setup

The server reads your API key from the `OPENROUTER_API_KEY` environment variable. All clients below pass it through `env`.

### Cline

Add to `cline_mcp_settings.json`:

```json
{
  "mcpServers": {
    "imagine-mcp": {
      "command": "npx",
      "args": ["-y", "imagine-mcp"],
      "env": {
        "OPENROUTER_API_KEY": "sk-or-v1-xxxxxxxxxxxxxxxxxxxxxxxx"
      }
    }
  }
}
```

### VS Code GitHub Copilot

Add to `.vscode/mcp.json` in your workspace:

```json
{
  "servers": {
    "imagine-mcp": {
      "command": "npx",
      "args": ["-y", "imagine-mcp"],
      "env": {
        "OPENROUTER_API_KEY": "sk-or-v1-xxxxxxxxxxxxxxxxxxxxxxxx"
      }
    }
  }
}
```

### Claude Code

Add to `.mcp.json` in your project root (or `~/.mcp.json` for global):

```json
{
  "mcpServers": {
    "imagine-mcp": {
      "command": "npx",
      "args": ["-y", "imagine-mcp"],
      "env": {
        "OPENROUTER_API_KEY": "sk-or-v1-xxxxxxxxxxxxxxxxxxxxxxxx"
      }
    }
  }
}
```

### Local build instead of `npx`

If you cloned the repo, replace the `command`/`args` with:

```json
"command": "node",
"args": ["/absolute/path/to/imagine-mcp/build/index.js"]
```

## Environment variables

| Variable | Required | Default | Description |
|---|---|---|---|
| `OPENROUTER_API_KEY` | **yes** | — | OpenRouter API key |
| `OPENROUTER_IMAGES_DEFAULT_MODEL` | no | `bytedance-seed/seedream-4.5` | Default model when none is specified |
| `OPENROUTER_IMAGES_OUTPUT_DIR` | no | `<workspace>/assets/generated-images` | Default output directory |
| `OPENROUTER_IMAGES_TIMEOUT_MS` | no | `180000` | Per-request timeout (ms) |
| `DEBUG` | no | — | Set to `imagine-mcp` for verbose logs |

## Tools

### `generate_image`

Generate one or more images from a text prompt.

**Required:** `prompt`, `model`

**Common optional parameters:**

| Parameter | Type | Notes |
|---|---|---|
| `resolution` | `512` \| `1K` \| `2K` \| `4K` | Model-dependent |
| `aspect_ratio` | `1:1` \| `16:9` \| `9:16` \| `4:3` \| `3:4` \| `auto` \| ... | Model-dependent |
| `size` | string | Shorthand: `"2K"` or `"2048x2048"` |
| `quality` | `auto` \| `low` \| `medium` \| `high` | Not all models |
| `output_format` | `png` \| `jpeg` \| `webp` \| `svg` | `svg` only for Recraft |
| `background` | `auto` \| `transparent` \| `opaque` | |
| `n` | number | 1–10 (clamped per model) |
| `save_to_disk` | boolean | **Default `true`** — saves to `assets/generated-images/` |
| `return_b64` | boolean | Default `false`. `true` returns ~1MB+ base64 (use sparingly) |
| `output_dir` | string | Override save directory (resolved against workspace root) |
| `filename` | string | Base filename without extension |
| `image_config` | object | Advanced model-specific options (see `list_image_models`) |

**Example (assistant-style call):**

```json
{
  "prompt": "Minimalist owl logo, flat vector, geometric shapes, dark navy and gold, no text",
  "model": "recraft/recraft-v4.1-vector",
  "output_format": "svg",
  "save_to_disk": true,
  "filename": "owl_logo"
}
```

Response (abridged):

```json
{
  "success": true,
  "model": "recraft/recraft-v4.1-vector",
  "images_generated": 1,
  "images": [{ "index": 0, "media_type": "image/svg+xml", "saved_to": "/repo/assets/generated-images/owl_logo.svg" }],
  "saved_to_disk": true,
  "output_dir": "/repo/assets/generated-images",
  "usage": { "cost": 0.08, "cost_source": "api" },
  "pricing_note": "$0.08/image"
}
```

### `list_image_models`

Returns the full catalog (or a single model) with supported parameters, pricing, best-use cases, and supported `image_config` fields. **Call this first** if you're unsure which parameters a model accepts.

### `save_image`

Persist base64 image data you already have to disk. Useful when a previous call used `return_b64=true`.

### `list_generated_images`

Lists image files previously saved in the output directory (most recent first). Handy for the assistant to reference or open images already generated in the current workspace.

## How workspace detection works

On startup the server walks up from its current working directory looking for a project marker (`.git`, `package.json`, `pubspec.yaml`, `pyproject.toml`, `requirements.txt`, `Cargo.toml`, `go.mod`, `.hg`, `.svn`). The first directory containing a marker becomes the **workspace root**, and images are saved under `<workspace root>/assets/generated-images/` by default.

MCP hosts (Cline, Copilot, Claude Code) launch the server with CWD set to the open workspace, so images land in the right repo automatically.

`output_dir` is resolved against the workspace root and cannot escape it (path traversal is rejected).

## Cost transparency

- When OpenRouter returns `usage.cost`, it is reported as `usage.cost` with `cost_source: "api"`.
- When the API does not return a cost (e.g. Riverflow dynamic pricing finalizes after completion), the server estimates it from the model's flat price table and reports `usage.estimated_cost` with `cost_source: "estimated"`.
- The model's `pricing_note` is always included in the response.

## Prompting best practices

Each model responds better to a different prompting style. See [`docs/model-guides.md`](docs/model-guides.md) for official, per-model guidance:

- **Seedream 4.5** — structured `[Subject]+[Action]+[Environment]+[Style]+[Technical]+[Text]` formula; quote literal text
- **Grok Imagine** — director-style language; generate 2–3 outputs (no seed); explicit "no additional text" for clean product shots
- **Recraft v4.1 Vector** — structured vector prompts (graphic type / shape logic / color system / line discipline / constraints); name colors; "no gradients, no shadows"
- **Riverflow v2.5 Fast** — `thinking_level`, `scoring_prompt` + `scoring_rubric` for brand alignment, `font_inputs`, `background_hex_color`

## Development

```bash
npm install
npm run build      # compiles to build/index.js and sets exec bit
npm start          # runs the server
DEBUG=imagine-mcp npm start   # verbose logs
```

## License

MIT