locmodel-image
Summary: This server turns a local, offline LocModel / stable-diffusion.cpp engine into an agent-callable toolset for generating, inspecting and editing images, with no cloud cost.
Generate images (
generate_image) from a prompt, with aspect presets or explicit width/height, seeds, counts, samplers, steps, CFG, timeouts, output directories and dry-run payload inspection.Edit an existing image (
edit_image): repaint only masked regions using a mask PNG or JSON regions (rect / polygon / brush / circle / colour), guaranteeing pixels outside the mask stay identical.Redraw a whole image (
redraw_image) from a new prompt while keeping the source's composition and size.Tune workflow parameters for one call (
params), a whole session (set_workflow_params/reset_workflow_params) or inspection (get_workflow_params) — CFG, scheduler, hi-res fix, VAE tiling, LoRA and more, sent only in the HTTP payload.Manage models: list engine models (
list_models), list editing-capable models with priority (list_edit_models), and load or switch models (load_model).Diagnose the environment:
locmodel_statusfor port/model/VRAM/size policy,engine_doctorfor a self-check, andengine_discoverto force a port re-scan after restarting the engine.Handle sizing and failures gracefully: VRAM-aware area guard for tool-chosen sizes, explicit sizes honoured, engine limit clamping, and actionable errors instead of blind retries.
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., "@locmodel-image generate a 16:9 image of a modern timber building at dusk"
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.
locmodel-image-MCP
GitHub repository: jaja1620/locmodel-image-MCP — the installable package, the CLI command and the MCP server are still named
locmodel-image.
Turn your local LocModel / stable-diffusion.cpp image engine into a first-class tool for AI agents — offline, free, scriptable.
locmodel-image is a zero-dependency bridge that exposes the image engine bundled inside
LocModel (an sd-server built on stable-diffusion.cpp) through two
interfaces:
Interface | Entry point | Use it when |
MCP server (recommended) |
| Your AI client speaks Model Context Protocol (Claude Desktop, Cursor, Marvis, Continue, …). The model gets a typed tool instead of memorising shell commands. |
CLI bridge |
| Scripts, batch jobs, CI, or clients without MCP support. |
Both share the same engine layer: port auto-discovery, VRAM-aware size guard, failure classification with retry, cross-process generation lock, structured JSON output and meaningful exit codes.
English · 简体中文
Table of contents
Related MCP server: imagine
Why this exists
LocModel ships a complete local image pipeline but exposes it as a desktop GUI. Agents and
scripts cannot drive a GUI reliably, and hard-coding http://127.0.0.1:8790 breaks the moment the
port changes, the model changes, or the machine has less VRAM than yours.
This project solves exactly those three problems:
Discovery instead of hard-coded ports — five fallback layers, including parsing the
sd-serverprocess command line (the most reliable source, because LocModel chooses the port at launch).Guard instead of mysterious failures — the engine silently fails on tiny images (512×512 can return
no results) while succeeding on much larger ones. The guard works on total pixel area, not on a single edge, and rescales proportionally so the requested aspect ratio survives.Portability instead of "works on my machine" — no hard-coded user paths, resolutions, samplers or Python installs. Every default is discovered or overridable.
Requirements
Item | Requirement |
Python | 3.8+ (3.10+ recommended). Standard library only — nothing to |
Engine | LocModel desktop app with a diffusion model loaded, or any |
OS | Windows 10/11, macOS, Linux |
GPU | Any GPU the engine itself supports. 6 GB VRAM is usable; 8 GB is comfortable at 1024² |
The bridge does not load models and does not manage the engine lifecycle — start LocModel and load a model first. That is a deliberate boundary: engine startup differs per hardware and per model, and getting it wrong is the number-one cause of "workspace capacity" crashes.
Install
Two ways to install — pick one:
Installer (single-file exe, no Python needed) — recommended for normal use. Download
locmodel-image-setup.exefrom Releases, double-click it, confirm once, done. It unpacks the runtime into%LOCALAPPDATA%\locmodel-imageand registers the MCP server into every supported client it detects. Marvis users then runlocmodel-image-setup.exe emit marvisand paste the printed instructions into chat.From source (needs Python 3.9+, the original way) — clone and run, as described below.
Detailed, bilingual step-by-step guide (install + usage + troubleshooting): docs/INSTALL.md (English) · docs/INSTALL.zh-CN.md (中文)
From source
Nothing to build. Clone and run:
git clone https://github.com/jaja1620/locmodel-image-MCP.git
cd locmodel-image-MCP
python scripts/locmodel_image.py doctordoctor prints a checklist (Python version, platform, config path, engine port and how it was
found, model, GPU free memory, output directory writability) and exits non-zero if something
essential is missing.
Optional — install as a package so locmodel-image is on your PATH:
pip install .
locmodel-image doctorQuick start
# 1. Is the engine reachable, and where?
python scripts/locmodel_image.py status
# 2. Validate parameters without spending GPU time
python scripts/locmodel_image.py generate --prompt "courtyard at dusk" --aspect 16:9 --dry-run
# 3. Generate
python scripts/locmodel_image.py generate \
--prompt "modern modular building, warm timber facade, dusk, wide angle, architectural photography" \
--aspect 16:9 --out ./output --seed 424242
# 4. Two variants, fixed seed for reproducibility
python scripts/locmodel_image.py generate --prompt "..." --count 2 --seed 424242Every run writes:
output/locmodel_20261109_171204_1_seed424242.png
output/locmodel_20261109_171204_meta.json_meta.json records the effective prompt, seed, size after guard correction, steps, sampler, CFG,
requested-vs-final size and elapsed seconds — so any image can be reproduced or audited later.
Edit an existing image
v3.0 adds two verbs on top of text-to-image: repaint one region and redraw the whole frame.
You want | Use | Original pixels |
Change one area, keep the rest |
| Preserved outside the mask — enforced, not hoped for |
Same composition, new style/subject |
| Used as a structural reference only |
Give the mask three ways
Regions as JSON — no image editor needed:
{"unit": "norm", "regions": [
{"type": "rect", "x": [0.12, 0.10, 0.48, 0.42]},
{"type": "polygon", "points": [[0.60, 0.62], [0.92, 0.60], [0.78, 0.94]]}
]}unit is norm (0–1, resolution-independent, default) or px. Shapes are unioned.
A mask PNG — white = repaint, black = keep. Rescaled automatically if the size differs.
A colour threshold — "retexture that solid-colour wall" without drawing anything.
By hand — open annotator/mask_annotator.html in any browser (single file, no install).
Drag an image in, draw rectangles / polygons / freehand, then export mask.png or copy the
normalised JSON straight into edit_image.
Model selection is explicit, never silent
python scripts/locmodel_image.py edit-modelsPrints every model, which ones can edit regions, and which one would be picked automatically.
The default priority is qwen-image-edit → flux2-klein → qwen-image.
Discovery cost is bounded and cached, because probing for an engine that is not running used to
be the slowest thing in the tool: process names are checked with tasklist before PowerShell is
started to read command lines, netstat output is used to skip candidate ports that cannot be
listening, and the resulting snapshot is reused for edit.snapshot_cache_ttl seconds (default
120) across processes. A warm call answers in ~0.3 s; pass --refresh after loading a model by
hand in the LocModel window:
python scripts/locmodel_image.py edit-models --refreshedit.prefer_loaded(defaulttrue) — if an editable model is already in VRAM, use it instead of swapping to a "better" one. A swap means unload + reload: 30–60 s for a 4B model, longer for a 20B, and it can OOM on a card that was already tight.edit.auto_load(defaulttrue) — load the highest-priority editable model when nothing is loaded. Without it the priority list would be decorative.Pass
modeland it is used exactly — an unusable model raises an error listing the alternatives rather than quietly substituting another one.Only the
editfamily (Qwen-Image-Edit, FLUX.2 klein) can repaint a region. Pure generators (Qwen-Image, Z-Image, SDXL, SD1.5) can onlyredraw_image.
Every response carries a selection block (requested / chosen / family / rank / reason /
auto_loaded / candidates) so you can explain why a particular model ran.
Outside the mask cannot change
The engine is not trusted to respect the mask. Results are recomposited on the CPU —
result = where(mask > 127, edited, original) — so pixels outside the mask are byte-identical to
the source. protected_pixels / redrawn_pixels are reported for auditing.
The file at files[].path is the protected image; the engine's unguarded output is kept
beside it as *_raw.png and exposed as files[].raw (plus recomposed[].raw). files[].protected
is true when recomposition succeeded. Only hand files[].path to the user — _raw exists for
"what did the engine actually paint" debugging.
# repaint a region
python scripts/locmodel_image.py edit --image ./output/v1.png \
--prompt "night-time glass curtain wall, interior lights on" \
--region 0.25,0.18,0.62,0.55 --strength 0.8
# repaint using an exported mask
python scripts/locmodel_image.py edit --image ./output/v1.png --mask ./output/mask.png \
--prompt "oak slat ceiling"
# same composition, watercolour
python scripts/locmodel_image.py redraw --image ./output/v1.png \
--prompt "watercolour architectural sketch, loose ink lines, white paper" --strength 0.65The source image is never overwritten; each edit lands in a new file so variants can be compared.
Connect as an MCP server
The server speaks newline-delimited JSON-RPC 2.0 over stdio (it also accepts LSP-style
Content-Length framing, for clients that prefer it). Protocol versions 2025-06-18,
2025-03-26 and 2024-11-05 are negotiated.
Claude Desktop
claude_desktop_config.json:
{
"mcpServers": {
"locmodel-image": {
"command": "python",
"args": ["C:/tools/locmodel-image-MCP/scripts/locmodel_mcp.py"],
"env": { "PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "1" }
}
}
}On Windows use the absolute path of a real interpreter (for example
C:/Users/you/AppData/Local/Programs/Python/Python312/python.exe); the bare python may resolve
to the Microsoft Store stub, which silently exits.
Marvis
{
"name": "locmodel-image",
"config": {
"command": "C:\\Users\\you\\AppData\\Local\\Programs\\Python\\Python312\\python.exe",
"args": ["C:\\tools\\locmodel-image-MCP\\scripts\\locmodel_mcp.py"],
"env": { "PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "1" }
}
}Any other client
Point it at scripts/locmodel_mcp.py with stdio transport. Pin the port if discovery is
unreliable on your machine:
"env": { "LOCMODEL_SD_PORT": "8790", "PYTHONIOENCODING": "utf-8" }Tool surface
Tool | Arguments | Returns |
|
| Image paths, effective seed, final size, elapsed time |
| — | Engine state, port + how it was found, model, engine defaults, GPU memory |
|
| Edited image paths, mask stats, |
|
| Redrawn image paths, |
| — | Models with family/rank, which can edit regions, and the automatic pick |
|
| Loads/switches the engine model, verifies it took effect |
| — | Models reported by the engine |
| — | Full self-check with pass/fail per item |
| — | Force a port re-scan and report the result |
generate_image returns isError: true with a human-readable hint on failure, so the agent can
act on it instead of retrying blindly.
Install the companion Skill
SKILL.md is the prompt-side counterpart of the MCP server: it tells an agent how to write
prompts, which aspect ratio suits which subject, which parameters matter, and how to interpret
each failure — knowledge a JSON schema cannot carry.
The two are complementary, not alternatives:
MCP = the hands (typed tool, always available)
Skill = the craft (prompt structure, presets, parameter judgement)
Install by copying this repository (or just SKILL.md) into your client's skills directory:
# Claude / generic agent skills directory
cp -r . ~/.claude/skills/locmodel-image
# Marvis (Windows)
xcopy /E /I . "%APPDATA%\Tencent\Marvis\User\<your-id>\skills\custom\locmodel-image"Skills that support front-matter (name, description, version, license) will pick the
metadata up automatically.
CLI reference
locmodel_image.py [--config PATH] [--verbose] [--log-file PATH] <command> [options]Command | Purpose |
| Engine port (and detection source), model, engine defaults, GPU memory |
| Force re-discovery, print port + source |
| List models the engine reports |
| Environment self-check; exit code reflects health |
| Submit a job and wait for the image |
| Repaint a masked region of an existing image |
| Re-draw a whole image from a new prompt |
| Models that can edit, their priority, and the automatic pick |
| Load or switch the model inside the engine |
| Inspect or modify configuration |
generate options
Option | Default | Notes |
| required | Non-empty string |
|
| Negative prompt |
| engine default | Positive integers; corrected by the guard |
| — |
|
| engine default | Higher is slower with diminishing returns |
| engine default | e.g. |
| engine default | Turbo/distilled models usually want 1.0–1.5 |
|
| Fix it to reproduce |
|
| Capped by |
| — | Override model name on multi-model engines |
| config | Output directory (created if missing) |
|
| Filename prefix |
|
| Seconds per job |
|
| Retries with a new seed on transient failure |
| off | Force tier-A sizing (send the requested size verbatim) |
| off | Print the HTTP payload and exit — no GPU time spent |
edit options
Option | Default | Notes |
| required | Source image (never modified) |
| required | What should appear inside the mask |
| — | Mask PNG, white = repaint. Wins over |
| — |
|
|
|
|
| off | Invert the generated mask |
|
| Denoising strength; raise to repaint more freely |
|
| Feather the mask edge to avoid seams |
|
| Grow the mask before the engine sees it |
|
|
|
| auto | Exact model; error rather than substitution |
|
| Re-read the output and check it |
| off | Print the payload (no engine contact, no GPU time) |
redraw takes the same options minus the mask ones, and defaults to --strength 0.6.
Exit codes
Code | Name | Meaning |
0 |
| Success |
1 |
| Unexpected error (network, filesystem, JSON) |
2 |
| Engine accepted the job but produced no image |
3 |
| No reachable engine after all discovery layers |
4 |
| Invalid input (empty prompt, |
Scripts can branch on the code; agents can branch on the error field in the JSON body.
Workflow parameters
Anything the engine's sample_params, hires, vae_tiling_params, high_noise_sample_params
or lora blocks accept can be set from this tool as of 3.2, and the enumerations (samplers,
schedulers, upscalers, output formats) are adopted from the live engine instead of being hard-coded. Parameters travel inside the HTTP
payload only — never through config.json. LocModel owns that file and rewrites it from its own
panel state, so anything written there is silently reverted; the payload is the only channel that
actually holds.
Three scopes, deliberately different lifetimes:
Scope | MCP | CLI | Lifetime |
One call |
|
| that job only |
This session |
|
| MCP process memory; gone on restart |
Back to defaults |
|
| immediately follows the GUI panel again |
Precedence: per-call params > session parameters > LocModel GUI panel / engine defaults.
When nobody asks for a parameter, nothing is sent and generation follows the GUI panel exactly as
before — the table is a switch, not a form to fill in.
Read live defaults at any time:
python scripts/locmodel_image.py params list # 14 core parameters, with live defaults
python scripts/locmodel_image.py params list --all # include folded groups
python scripts/locmodel_image.py params show --param cfgsource: engine means the value came from /sdcpp/v1/capabilities; source: tool means the engine
did not advertise it and a built-in fallback was used; source: session means it is currently
overridden in this process.
Core parameters (14)
Parameter | Aliases | Range | Notes |
|
| 0–30 | prompt adherence vs. highlight blow-out |
| — | 0–30 | conditional image branch; empty disables |
|
| 1–200 | turbo/flow models peak at 8–12 |
|
| 22 values |
|
| — | 19 values |
|
| — | 0–100 | flow-matching models, 2–5 is noticeable |
| — | -1–1000 | leave at 0 |
| — | 0–1 | SDE samplers: noise injection |
| — | 0–30 | distilled/accelerated checkpoints |
| — | -10–10 | skip-layer guidance, 0 disables |
| — | -64–12 | -1 = engine default |
| — | 0–1 | edit/img2img only: 0.35 subtle, 0.75 normal |
| — | -1 or int | -1 randomises, fix it for A/B |
| — | 1–8 | also capped by |
Folded groups
These stay out of the way until a task needs them; params list --all prints them with the same
live defaults.
hires —
hires_enabled,hires_upscaler(9 engine names, e.g.Latent (nearest)),hires_scale(multiplier),hires_target_width,hires_target_height,hires_steps,hires_denoising_strength,hires_upscale_tile_size,hires_custom_sigmasvae via tiling —
vae_tiling,vae_tile_size_w,vae_tile_size_h,vae_rel_size_w,vae_rel_size_h,vae_extra_tiling_args,vae_target_overlap,vae_temporal_tiling(18 GB of VRAM not required: turn this on before shrinking the canvas)output —
output_format(png/jpeg/webp) andoutput_compression(0–100)high noise —
high_noise_steps,high_noise_cfg,high_noise_samplerslg detail —
slg_layers,slg_layer_start,slg_layer_endraw passthrough —
custom_sigmas,extra_sample_args,lora([{"path": "x.safetensors", "multiplier": 0.8}]; requires--lora-model-diron the engine)
Validation is client-side
The engine returns 202 queued for nonsense (scheduler="bogus", steps="abc") and then hangs the
job. Every value is therefore type- and range-checked here first; a bad value fails fast with
bad_arguments and a hint, before any GPU time is spent. Aliases are accepted
(cfg_scale→cfg, sample_steps→steps, Karras→karras, "7,8,9"→[7, 8, 9]).
Configuration reference
Location (first match wins):
--config <path>LOCMODEL_IMAGE_CONFIGenvironment variable~/.locmodel-image/config.json(created on firstconfig set)
Resolution order for the port:
LOCMODEL_SD_PORTenvironment variablecached value in
config.jsoncommand line of a running
sd-serverprocess (most reliable)scan of
port_candidatesscan of local listening ports
Keys (defaults shown):
{
"port": null, // cached port; null = auto-discover every run
"host": "127.0.0.1",
"port_candidates": [8790, 8791, ...],// fallback scan list
"engine": {
"process_names": ["sd-server", "sd-server.exe", "sd.exe", "stable-diffusion"],
"capabilities_path": "/sdcpp/v1/capabilities",
"img_gen_path": "/sdcpp/v1/img_gen",
"jobs_path": "/sdcpp/v1/jobs",
"models_path": "/sdapi/v1/sd-models",
"status_path": "/sdcpp/v1/models/status",
"probe_timeout": 1.5
},
"size": {
"min_area": 589824, // 768x768 — the floor for tool-chosen sizes
"multiple": 8, // align edges to this
"max_side": 1536, // auto-shrinks with VRAM when max_side_auto
"max_side_auto": true,
"hard_max_side": 4096, // engine limits.max_width/height
"explicit_respect": true, // caller-supplied width/height wins over the tiers
"vram_mb_per_mp": 1600 // warning threshold per megapixel
},
"generate": {
"timeout": 900,
"retry": 2,
"poll_interval": 2.0,
"max_count": 8, // engine limits.max_batch_count
"max_download_mb": 64,
"lock": true,
"lock_wait": 900
},
"edit": {
"priority": ["qwen-image-edit", "flux2-klein", "qwen-image"],
"prefer_loaded": true, // keep the loaded model, don't swap for a better rank
"auto_load": true, // load the best editable model when none is loaded
"auto_load_timeout": 240,
"channel": "auto", // img_gen -> img2img fallback
"strength": 0.75, // region edit
"redraw_strength": 0.6, // whole-image redraw
"timeout": 900,
"mask_blur": 8,
"inpaint_padding": 32,
"verify": "agent",
"models_dirs": [], // extra folders to scan when the engine reports none
"load_endpoint": null,
"resolved_channel": null,
"engine_cache_ttl": 20, // seconds; in-process memo
"snapshot_cache_ttl": 120 // seconds; the snapshot survives processes
},
"discover": {
"process_cache_ttl": 20, // reuse the process command lines
"budget_seconds": 20, // hard ceiling for all port probing
"listen_budget_seconds": 4 // ceiling for the netstat leftover sweep
},
"gpu": { "min_free_mb_warn": 500 },
"output": { "dir": "./output" }
}Useful recipes:
locmodel_image.py config set engine.probe_timeout 3 # slow / remote machine
locmodel_image.py config set generate.max_count 2 # 6 GB VRAM users
locmodel_image.py config set size.max_side_auto false # pin the ceiling yourself
locmodel_image.py config set generate.lock false # single-process only
locmodel_image.py config set edit.prefer_loaded false # always swap to the top-priority model
locmodel_image.py config set edit.priority '["flux2-klein","qwen-image-edit"]'
locmodel_image.py config set edit.models_dirs '["F:/AI-Models"]' # scan when the engine is idleSizing and VRAM strategy
Two tiers, because the two situations want opposite things: a caller who asked for a specific canvas should get that canvas, while a tool that picks the canvas itself should stay inside the smooth band.
Tier A — the caller supplied width/height (or --no-guard on the CLI). The numbers are
sent as asked. Only two things can change them:
edges are aligned to
size.multiple(default 8)the engine's own
limits(64 … 4096 per edge, read live) clamp the result — with a warning, never silently
Everything else is advice, not action: below size.min_area or above the VRAM heuristic you get a
warning in notes and the image is rendered anyway.
Tier B — the tool picked the size (aspect preset, or no size at all). The old guard applies:
width/height(or the aspect preset) is normalised tosize.multipletotal area below
size.min_area→ scaled up proportionally (aspect ratio preserved)longest edge beyond the effective ceiling → scaled down proportionally
the effective ceiling is
size.max_side, lowered automatically from measured VRAM whenmax_side_autois on, never abovehard_max_side(4096, i.e. the engine limit)
The guard exists because the two failure modes produce misleading errors: too few pixels
(generate_image returned no results) and too many pixels (OOM / workspace capacity check,
which on Windows can surface as ucrtbase.dll 0xc0000409 / BEX64).
Practical presets:
VRAM | Suggested | Notes |
4–6 GB | 768×768, 1024×576, | keep |
8 GB | 1024×1024, 1280×720, | the tested sweet spot for turbo models |
12 GB+ | 1536×864, 1536×1536 | raise |
One more habit that prevents most mysterious failures: keep exactly one image engine resident.
Running LocModel plus an LM Studio model plus a second diffusion engine on the same GPU is the
classic cause of workspace capacity check crashes. When switching models inside LocModel, restart
LocModel so the previous engine releases VRAM.
How it works
┌──────────────┐ MCP stdio ┌──────────────────┐ HTTP ┌──────────────┐
│ AI client │ ────────────► │ locmodel_mcp.py │ ────────► │ │
│ (Claude, │ │ or │ /sdcpp │ sd-server │
│ Cursor, │ ◄──────────── │ locmodel_image.py│ ◄──────── │ (LocModel) │
│ Marvis) │ JSON result └──────────────────┘ polling └──────────────┘
└──────────────┘ │
▼
PNG + _meta.json on diskJob flow: POST /sdcpp/v1/img_gen → poll GET /sdcpp/v1/jobs/<id> (queued → running →
succeeded) → decode result.images[].b64_json (or fetch a loopback-only URL, up to
max_download_mb) → write PNG and metadata.
Failures are classified rather than blindly retried:
Class | Trigger | Action |
|
| retry with the same prompt, shrunk ×0.85 |
| HTTP 400 / invalid argument | no retry — the request itself is wrong |
| timeouts, connection resets | retry as-is |
A cross-process lock in ~/.locmodel-image/generate.lock serialises generations, because two jobs
competing for one GPU is the most common cause of capacity failures. Stale locks from dead PIDs are
reclaimed immediately; locks older than lock_wait + 600 s are reclaimed as expired.
Testing
# Unit tests — no engine required
python -m pytest tests/test_core.py -q
# End-to-end matrix — needs a live engine
python tests/e2e_matrix.py --stage core # status / models / doctor / dry-run
python tests/e2e_matrix.py --stage gen # real generations, aspect presets, batch, guard
python tests/e2e_matrix.py --stage diag # bad arguments, missing engine, config round-trip
python tests/e2e_matrix.py --stage mcp # MCP handshake, framing, tool calls
python tests/e2e_matrix.py --stage all # everything (slow: ~10 min on 8 GB)Each stage writes a JSON report and prints a pass/fail summary. Stages are split so a flaky GPU session cannot hide which part broke.
Troubleshooting
Symptom | Likely cause | Fix |
| LocModel closed, no model loaded, or unusual port | Start LocModel and load a model → |
| Not enough free VRAM, or two engines competing | Close LM Studio / browser hardware acceleration; one engine only; lower size or |
Job stuck in | Engine has a single slot and is busy | Wait; check no orphaned generator process holds the lock |
Generation > 3 min | Size too large, steps too high, GPU shared | Lower size, restore default steps, free the GPU |
Prompt seems ignored | CFG too low for a distilled model | Try |
Text renders as gibberish | Diffusion models cannot spell | Do not fight it — overlay text in PPT/PS/Figma |
MCP client shows no tools | Wrong interpreter, or Windows Store | Use the absolute interpreter path; set |
| Two engines resident; VRAM exhausted | Restart LocModel so a single engine owns the GPU |
Run doctor first for anything odd — it reports port source, model, GPU free memory and output
directory writability in one shot.
Compatibility and limitations
API surface: targets the
/sdcpp/v1/*API of stable-diffusion.cpp servers. It is not Automatic1111-compatible (/sdapi/v1/txt2imgis not used). Paths are configurable, so a fork with slightly different routes can be adapted viaconfig set engine.*_path.Discovery is heuristic: on machines where several engines run simultaneously, pin the port explicitly. Guessing wrong is silent otherwise, which is why
statusalways reports how the port was found.No model management: loading/unloading, model switching and VRAM budgeting remain LocModel's job. This tool never kills processes or unloads models on your behalf.
Not implemented: standalone upscaling of an existing image, and video generation. Hires-fix upscaling during generation is supported (
hires_enabled+hires_scale/hires_upscaler); the engine advertises no video mode, sogenerate_videostays out rather than half-working.Text in images: a limitation of the models, not of the bridge.
What changed in 3.2
Engine capabilities are adopted, not assumed —
adopt_capabilities()overwrites the sampler, scheduler, upscaler, output-format and preview-mode lists from/sdcpp/v1/capabilities, readslimits(64 … 4096 per edge, batch 8) andfeatures.locmodel_statusreports all of it.Latent upscalers actually work — the tool shipped
Latent(nearest); the engine spells itLatent (nearest)and rejected the space-less form with400 invalid generation parameters. Fixed, and enum matching is now whitespace-insensitive, solatent(nearest)/JPEGnormalise.Explicit sizes are honoured — two size tiers (see Sizing and VRAM strategy): a caller-supplied
width/heightis sent as asked and only clamped by the engine's own limits, with a warning; tool-chosen sizes keep the area floor and VRAM-tiered ceiling.Fallback defaults match the engine —
cfg 1.0 / steps 4 / eulerinstead of the old7.0 / 20, anddefaults_by_modeis read whendefaultsis missing.New parameters —
hires_scale,hires_custom_sigmas,output_format,output_compression,vae_rel_size_w/h,vae_extra_tiling_args(42 total). JPEG/WebP output works; the extension followsoutput_format.guard/dry_runongenerate_image— inspect the exact payload andsize_policybefore spending GPU time.Unsupported knobs are reported — asking for a parameter the loaded model cannot honour produces a note instead of a silent no-op.
What changed in 3.1
Workflow parameter channel —
paramsongenerate_image/generate --param, plusset_workflow_params/get_workflow_params/reset_workflow_params. Values are merged into the HTTP payload, never intoconfig.json, because the LocModel GUI rewrites that file from its own panel state. Defaults are read live from the engine so the documented numbers cannot drift.cfgreachable from MCP —generate_imageacceptedstepsandsamplerbefore but silently droppedcfg; it is now wired through.Client-side validation — the engine accepts junk values and hangs the job, so type and range checks happen before submission.
Session scope — parameters set with
set_workflow_paramsapply to every later job in the same MCP process and vanish on restart;edit_image/redraw_imagehonour them too.
What changed in 3.0
edit_image/redraw_image— prompt-driven editing on an existing image, without downloading a dedicated inpainting checkpoint. The engine's existinginit_image+mask_imagepath is used; masks are built on the CPU with the standard library only.Mask outside the mask is guaranteed — results are recomposited on the CPU against the original, so "keep everything except this area" is a real guarantee rather than a hope.
Model priority without silent surprises —
edit.priorityplusedit.prefer_loaded/edit.auto_load, and an explicit error instead of a substitution when the requested model cannot edit.list_edit_models/load_model— see which models can edit, why one was chosen, and load or switch models without leaving the agent.annotator/mask_annotator.html— a single-file browser mask painter (rect / polygon / brush) that exports a mask PNG or normalised JSON.Faster probes — engine discovery is cached (
edit.engine_cache_ttl), so a closed engine no longer costs a scan on every call.Still zero dependencies: standard library only, Python 3.8+.
What changed in 2.0
See CHANGELOG.md for the full list, and docs/IMPROVEMENTS.md for every hard-coded assumption that had to go before this could run on someone else's machine. Highlights:
No hard-coded user paths, ports, resolutions, samplers or Python installs
Area-based size guard with VRAM-aware ceiling and
--aspectpresetsFailure classification (
capacity/parameter/transient) with proportional shrink on retryCross-process generation lock with stale-lock reclamation
--dry-run,--no-guard,--log-file,--config,config get/set/pathStable exit codes;
expects_errorhandling instead of crashesMCP: protocol negotiation, dual framing (newline +
Content-Length),engine_doctor/engine_discovertools,isErrorwith actionable hintsTests: 46 unit tests + staged e2e matrix
License
MIT — see LICENSE.
Available Tools
12 toolsedit_imageA
EDIT an existing local image: repaint only the masked area (inpainting) while the rest stays pixel-identical -- the tool re-composes the result on the CPU, so outside-mask pixels cannot drift. Give either mask_image or regions. Models are chosen by priority (qwen-image-edit > flux2-klein > qwen-image); the loaded model wins when it can region-edit. Returns absolute PNG paths for the agent to inspect.
Inputs: prompt (required), init_image (required), seed, model, +15 more.
engine_discoverA
Force engine port re-discovery (use after restarting LocModel, which may pick a different port).
Inputs: no named parameters.
engine_doctorA
Self-check: python, engine reachability, model, VRAM vendor, output directory writability, available helper tools. Use this first when generation fails.
Inputs: no named parameters.
generate_imageA
Generate images with the LOCAL LocModel / stable-diffusion.cpp engine (offline, no cloud cost). Pass an already-optimised English prompt; the tool returns absolute image paths plus the seed used for reproduction. Sizing: when the tool picks the size: 576k-pixel minimum area, long edge <= 1536px, multiple of 8. An explicit width/height is honoured as requested -- only the engine's hard limits (64-4096px per edge) can shrink it, and big canvases come back with a VRAM warning instead of being resized. One 1024x1024 image takes roughly 20-60 s on a mid-range GPU.
Inputs: prompt (required), cfg, seed, count, +13 more.
get_workflow_paramsA
List every workflow parameter this tool accepts, with its default value, valid range / options, the payload path it maps to, and whether the default came from the live engine or from the built-in fallback. Use it before setting parameters so you do not guess a name or a range.
Inputs: live_defaults, include_folded.
list_edit_modelsA
List every model that can be used for editing, with family, priority rank, whether it supports region editing, and which one would be picked automatically right now. Call this before editing when you are unsure what is installed.
Inputs: refresh, models_dir.
list_modelsA
List the models the local engine reports (A1111-compatible /sdapi/v1/sd-models).
Inputs: no named parameters.
load_modelA
Load / switch the model in the local engine, and wait until the engine reports it. Use it when the model you need for an edit is not the one currently loaded.
Inputs: model (required), timeout_s.
locmodel_statusB
Inspect the local engine: port and discovery source, loaded model, engine-reported generation defaults, VRAM and the active size policy.
Inputs: no named parameters.
redraw_imageA
REDRAW an existing local image from a new prompt, keeping its composition and size (whole-image img2img). The character of the picture changes but the geometry stays. Use edit_image instead when only part of the picture should change.
Inputs: prompt (required), init_image (required), seed, model, +11 more.
reset_workflow_paramsA
Clear the session parameter set (all of it, or the listed keys) so generation goes back to the LocModel GUI panel settings. This is the one-command restore.
Inputs: keys.
set_workflow_paramsA
Remember workflow parameters for the rest of this session (CFG, steps, sampler, scheduler, flow_shift, eta, hi-res fix, VAE tiling, LoRA ...). Use it for batch runs where every image shares the same look, instead of repeating params on each call. Values are sent in the HTTP payload per job -- they never touch LocModel's config.json, which the GUI rewrites. Returns the effective parameter table with defaults, ranges and the source of each default. Call reset_workflow_params to drop everything and fall back to the LocModel GUI panel settings.
Inputs: params (required), merge.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 12 tools
The three image-producing tools (generate_image, edit_image, redraw_image) are explicitly differentiated in their descriptions by input type and scope, and list_models vs list_edit_models is spelled out. The only fuzzy zone is the engine trio: locmodel_status, engine_doctor, and engine_discover all touch port/reachability information and could be confused at a glance, though the descriptions do draw lines.
Most tools follow a clean verb_noun pattern (generate_image, edit_image, redraw_image, list_models, load_model, set/get/reset_workflow_params). However engine_discover, engine_doctor, and locmodel_status flip to noun_verb or noun_noun, breaking the pattern for exactly the tools that are hardest to tell apart.
12 tools is well within the ideal band and each one maps to a distinct capability: generation, two edit modes, model discovery/loading, parameter management, and engine diagnostics. Nothing looks redundant or like filler.
The surface covers the full lifecycle of local image generation: inspect engine, load model, set params, generate, edit, redraw. Minor gaps remain, such as batch/variation generation, output listing or cleanup, and any upscale/post-process step, but core workflows have no dead ends.
Maintenance
Related MCP Connectors
PDF and image tools for AI agents: compress, merge, split, OCR, sign. Runs locally, never uploads.
Generate AI images and videos from your agent: list models, start jobs, and fetch the results.
LLM chat, text tools, image generation, editing, batch image jobs, and asynchronous video generation
Generate and edit images, video, voice, lip-sync and 3D models from your AI agent.
Related MCP Servers
- AlicenseAqualityBmaintenanceEnables AI agents to generate images on a local Stable Diffusion Forge Neo instance, automatically inferring prompt style and sampling parameters from the user's setup and past generations, and providing tools for LoRA search, model management, and module checks.101MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI assistants to generate and edit images locally on Apple silicon using FLUX.2 Klein models, fully offline, with tools for generation, editing, and listing available models.2MIT
- FlicenseNot gradedqualityAmaintenanceExposes tools for local text-to-image generation, listing available models, and browsing past generations over the Model Context Protocol, with stdio entrypoints plus SSE and Streamable HTTP transports so AI agents can create and retrieve images.-
- AlicenseNot gradedqualityFmaintenanceEnables AI agents to generate and edit local PNG images from text prompts or reference images through an OpenAI-compatible Images API, with selectable style templates and offline reference examples.MIT