sd-api-mcp
# sd-api-mcp
An MCP (Model Context Protocol) server that exposes a Stable Diffusion REST API to AI agents. Supports SD1.5, SDXL, Illustrious XL, Flux, and Z-Image pipelines for text-to-image generation, inpainting, model management, model merging, browsing saved outputs, and finding and downloading models from Civitai.
It sits on top of the [SD API Backend](https://github.com/mcaimi/sd-api-backend.git) project.
Built with the [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) and managed with [uv](https://docs.astral.sh/uv/).
## Requirements
- Python >= 3.11
- [uv](https://docs.astral.sh/uv/) package manager
- A running [Stable Diffusion API](https://github.com/mcaimi/sd-api-backend.git) instance (default: `http://localhost:8000`)
## Installation
```bash
git clone <repo-url>
cd sd-api-mcp
uv sync
```
## Usage
### stdio (default)
For use with MCP clients that manage the server process (e.g., Claude Code, Claude Desktop):
```bash
uv run sd-api-mcp
```
### SSE
```bash
uv run sd-api-mcp --transport sse --host 0.0.0.0 --port 8080
```
### Streamable HTTP (recommended for networked deployments)
```bash
uv run sd-api-mcp --transport streamable-http --host 0.0.0.0 --port 8080
```
The MCP endpoint will be available at `http://<host>:<port>/mcp`.
### Claude Desktop configuration
Add to your `claude_desktop_config.json`:
```json
{
"mcpServers": {
"stable-diffusion": {
"command": "uv",
"args": ["run", "--project", "/path/to/sd-api-mcp", "sd-api-mcp"],
"env": {
"SD_API_URL": "http://localhost:8000"
}
}
}
}
```
### Claude Code configuration
```bash
claude mcp add stable-diffusion -- uv run --project /path/to/sd-api-mcp sd-api-mcp
```
### OpenCode configuration
Add to your `opencode.json`:
```json
{
"mcp": {
"stable-diffusion": {
"type": "stdio",
"command": "uv",
"args": ["run", "--project", "/path/to/sd-api-mcp", "sd-api-mcp"],
"env": {
"SD_API_URL": "http://localhost:8000"
}
}
}
}
```
For SSE or Streamable HTTP transports, start the server separately and use a remote URL instead:
```json
{
"mcp": {
"stable-diffusion": {
"type": "sse",
"url": "http://localhost:8080/sse"
}
}
}
```
## Environment Variables
| Variable | Default | Description |
|---|---|---|
| `SD_API_URL` | `http://localhost:8000` | Base URL of the Stable Diffusion API |
| `SD_POLL_INTERVAL` | `2.0` | Seconds between job status polls |
| `SD_POLL_TIMEOUT` | `600.0` | Maximum seconds to wait for job completion |
| `SD_DOWNLOAD_TIMEOUT` | `3600.0` | Maximum seconds `civitai_download` waits when `wait=true` |
| `SD_HTTP_TIMEOUT` | `30.0` | Timeout in seconds for a single HTTP request to the SD API |
| `SD_IDENTIFY_TIMEOUT` | `600.0` | HTTP timeout for `civitai_identify` (hashes the model file) |
| `MCP_TRANSPORT` | `stdio` | Transport protocol (`stdio`, `sse`, `streamable-http`) |
| `MCP_HOST` | `127.0.0.1` | Bind address for SSE/HTTP transports |
| `MCP_PORT` | `8080` | Port for SSE/HTTP transports |
## Available Tools
### Image Generation
| Tool | Description |
|---|---|
| `generate_image` | Generate an image and wait for the result |
| `inpaint_image` | Inpaint a masked region and wait for the result |
| `submit_generate` | Submit a generation job, return the job ID immediately |
| `submit_inpaint` | Submit an inpainting job, return the job ID immediately |
| `batch_generate` | Submit up to 10 generation requests at once |
| `compare_models` | Generate with 2-6 models using the same prompt for comparison |
All generation tools accept a `pipeline` parameter: `"sd15"`, `"sdxl"`, `"illustrious"`, `"flux"`, or `"zimage"`.
Optional sampling parameters (`width`, `height`, `steps`, `cfg_scale`, `scheduler`) are only sent when set, so leaving them out gives you the backend's defaults for that pipeline:
| Pipeline | Size | Steps | CFG | Scheduler |
|---|---|---|---|---|
| `sd15` / `sdxl` / `illustrious` | 512×512 | 30 | 7.0 | `DPM++ 2M` |
| `flux` | 512×512 | 30 | 3.5 (distilled guidance) | `FlowMatch Euler` |
| `zimage` | 1024×1024 | per variant | per variant | `FlowMatch Euler` |
Pipeline-specific options:
- **Flux:** `true_cfg_scale` (1-10, default 1.0). Set it above 1.0 to enable `negative_prompt`.
- **Z-Image:** `variant`, either `"turbo"` (default) or `"base"`.
- **Flux and Z-Image inpainting:** `strength` (0-1) controls how strongly the masked area is re-noised.
These options are only sent to the pipelines that support them. Flux and Z-Image use flow-matching schedulers; list them with `list_schedulers(model_type="flux")` or `list_schedulers(model_type="zimage")`.
### Model Management
| Tool | Description |
|---|---|
| `list_models` | List available checkpoints, LoRAs, or VAEs |
| `get_model_metadata` | Read metadata from a model's safetensors header |
| `get_model_preview` | Return a model's Civitai preview image |
`list_models` entries include Civitai details (when known), whether a preview is available, and for Flux checkpoints which components the file bundles.
### Outputs
| Tool | Description |
|---|---|
| `list_outputs` | List saved generation outputs, newest first (paginated) |
| `get_output_image` | Return the image of a saved output |
| `get_output_metadata` | Get the generation parameters of a saved output |
| `delete_output` | Delete a saved output's image and metadata |
### Civitai
| Tool | Description |
|---|---|
| `civitai_status` | Whether Civitai is enabled, plus the valid base models and sort/period options |
| `civitai_search` | Search Civitai for checkpoints, LoRAs, or VAEs for a pipeline (paginated with `cursor`) |
| `civitai_get_model` | Get a model's versions and files, with compatibility and whether each is already downloaded |
| `civitai_file_layout` | Check which components a Flux checkpoint bundles, without downloading it |
| `civitai_download` | Download a file as a background job (`wait=true` to block until it finishes) |
| `civitai_identify` | Match a local model on Civitai by SHA256 and save its details and preview |
If a file's base model doesn't match `model_type`, `civitai_download` fails and shows the backend's warnings. Call it again with `accept_mismatch=true` to download anyway.
### Job Management
| Tool | Description |
|---|---|
| `list_jobs` | List all jobs with status and progress |
| `get_job_status` | Get status, progress, detail, and result of a specific job |
| `cancel_job` | Cancel a pending or running job |
### System
| Tool | Description |
|---|---|
| `health_check` | Check if the SD API is reachable |
| `system_info` | Get GPU, cache, and queue statistics |
| `list_schedulers` | List available noise schedulers (optionally per `model_type`) |
| `get_app_settings` | Get current configuration parameters |
### Model Merging
| Tool | Description |
|---|---|
| `merge_models` | Merge two checkpoints (linear, slerp, additive, subtract) |
| `batch_merge_models` | Merge a base model with multiple targets |
| `recipe_merge` | Execute a multi-step merge recipe |
All merge tools accept `output_dtype` (`"auto"` by default, which keeps the source precision).
## Examples
### Generate an image (agent perspective)
An AI agent would call the `generate_image` tool with:
```json
{
"pipeline": "sdxl",
"positive_prompt": "a cat sitting on a windowsill, golden hour lighting, photorealistic",
"negative_prompt": "blurry, low quality",
"model_checkpoint": "dreamshaperXL_v2.safetensors",
"width": 1024,
"height": 1024,
"steps": 30,
"cfg_scale": 7.0,
"seed": -1,
"scheduler": "DPM++ 2M"
}
```
The tool submits the job to the SD API, polls until completion, and returns the full result including the generated image.
### List available models
```json
{
"model_type": "sdxl",
"resource_type": "checkpoints"
}
```
### Merge two models
```json
{
"model_type": "sd15",
"base_model": "v1-5-pruned.safetensors",
"target_model": "dreamshaper_8.safetensors",
"output_name": "merged_model.safetensors",
"method": "slerp",
"alpha": 0.5
}
```
## Project Structure
```
src/sd_api_mcp/
__init__.py # CLI entry point with transport selection
server.py # MCPServer instance and tool definitions
client.py # Async HTTP client for the SD API
```
## License
This project is licensed under the GNU General Public License v3.0. See [LICENSE](LICENSE) for details.
TDQS
Scored across 18 tools
Most tools target distinct operations (sync generation, async submission, batch, compare, merge variants), and descriptions clarify the differences. A few near pairs such as generate_image/submit_generate and batch_merge_models/recipe_merge could cause misselection, but the descriptions separate them well.
The dominant verb_noun pattern (list_models, get_job_status, merge_models) is readable, but there are notable deviations like health_check, system_info, recipe_merge, and submit_generate. The mix of verb-first and noun-first names is inconsistent enough to slow an agent down.
Eighteen tools is slightly above the ideal 3-15 range, but the breadth is justified by covering generation, async jobs, model metadata, system health, and model merging. It feels like a complete API surface rather than an inflated one.
The surface covers generation, inpainting, async job lifecycle, model listing/metadata, schedulers, and multiple merge workflows. Obvious gaps are minor, such as the lack of a general image-to-image tool or batch async variants, but core workflows have no dead ends.