aseprite-mcp
README.md
# `aseprite-mcp`
A zero-runtime-dependency **TypeScript / Node.js Model Context Protocol (MCP) server** for **Headless Batch Aseprite** (`aseprite -b --script`). Built so Antigravity, Claude Code, Cursor, and custom subagents can inspect, create, draw, animate, slice, preview, and export `.aseprite` files cleanly without opening GUI windows.
## Showcase
**Multi-layer rigged animation (`idle` / `walk` / `cast`)**

**Multi-layer animated parallax scene (`640×360`)**

**Isometric cutaway diorama (`160×160`, multi-layer with `_iso_grid` & `cast_shadows`)**

## Features
- **Zero external runtime dependencies**: Runs purely on Node.js (`>=20`) built-ins and spawns `aseprite -b --script`.
- **Dual-framing Stdio Transport**: Supports both standard MCP newline-delimited JSON-RPC 2.0 and LSP-style `Content-Length` framing.
- **Built-in Hearth 16 Palette**: Preloaded with the canonical 16-color daylight/winter hue-shifted ramp (`O = #2d1f36` outline, never pure black), plus custom hex/RGBA/paletteMap overrides.
- **28 Tools** (plus opt-in `execute_lua` when `ASEPRITE_MCP_ENABLE_EXECUTE_LUA=1`):
- `aseprite_status` — verify binary, version, and palette reference
- `inspect_sprite` — full metadata dump (layers, frames, cels, tags, slices, tilesets, palette)
- `create_sprite` — create layered/multi-frame `.aseprite` files
- `manage_layers` — `add` / `add_group` / `tilemap`, `remove`, `rename`, `parent` reparenting & `stackIndex`, `duplicate`, `merge_down`, `flatten`, `to_background` / `from_background`, `convert_to_tilemap` / `convert_to_layer`, `visible`, `editable` (lock), `continuous`, `collapsed`, `opacity`, `blendMode`, `color`, `data`
- `manage_frames` — add empty, clone, delete, set durations
- `apply_revision` — preview and propagate per-layer pixel edits across offset poses
- `manage_cels` — link/unlink cels across frames, copy, clear, keyframe opacity/`zIndex`/position
- `manage_tags` — create/update/delete animation tags
- `manage_slices` — create/update/delete slices, 9-slice centers, and pivots
- `manage_tilesets` — create/delete tilesets, add/draw tiles, export tile atlases
- `manage_tilemap` — paint, read, or clear tilemap grid cels (with flip/rotate flags)
- `draw_pixels` — paint ASCII matrices and/or pixel rectangles via compact RLE spans (uneven matrix rows are rejected unless `allowRaggedRows: true`; pixels falling off the canvas are reported in `pixelsOutsideCanvas`)
- `draw_isometric` — draw pixel-clean isometric/axonometric grids, diamonds, 3-plane shaded boxes/slabs/walls/slopes/stairs/cylinders (with configurable `anchor`: `corner`/`center`/`tile_center`), cutaway rooms, plinths, plane-projected 2D textures (`top`/`floor`, `left`/`sw_facing`/`ne_wall`, `right`/`se_facing`/`nw_wall`), palette-locked cast shadows, and scoped convex bevel ridges (`scope`, `bounds`, `footprint`) via a 3D per-pixel depth buffer
- `compose_isometric` — render 3×3/N×M isometric tiling previews (`tile_preview`) or assemble multi-tile, multi-elevation `(u, v, z)` game maps and digital-art dioramas with topological depth sorting (`compose_scene`)
- `animate_layers` — hierarchical multi-frame posing (`pose_frames` with parent→child pivots, easing, RotSprite, squash/stretch, shear, sub-pixel shifts, `clampBottomRow`, and exact-keyframe `pinBottomRow`), half-cycle limb mirroring (`mirror_cycle` with optional `rampShift`), trailing secondary drag (`follow_through`), and palette-locked attack smears (`motion_smear` with `outerEdgeOnly` / `ribbons` streaks and optional `colors`/`region` source filtering)
- `read_pixel_matrix` — convert a cel or flattened frame back into an ASCII matrix + hex legend
- `lint_pixel_art` — detect L-corner outline doubles (iso-safe for 2:1 cube corners), curve-aware `isoJaggies` (ignoring smooth monotonic arcs by default while reporting `neighborRuns`, `direction`, and `likelyCurve`), footprint overflow, 1px orphan noise, `#000000` / off-palette colors, symmetry, and grounding; supports `offset`/`limit` pagination (default 50, max 500), `filterLayer`, full `countsByLayer` + `visibleLayer` attribution on flattened frames, and standalone `outputPng` visual overlays (`overlayKinds`)
- `draw_shapes` — invoke `app.useTool` primitives (`line`, `rectangle`, `ellipse`, `paint_bucket`, etc.)
- `apply_transform` — `flip_h`, `flip_v`, `rotate_90/180/270`, `shift`, `rotsprite` (8× Scale2x arbitrary-angle rotation), `squash_stretch`, `shear`, `subpixel_shift` (ramp-locked fractional shift), `outline`, `remove_outline_doubles` (iso-safe), `selective_outline`, `iso_mirror` (horizontal mirror + lighting ramp swap), `quantize_palette`, `replace_color`, `resize_sprite`
- `export_spritesheet` — deterministic fixed-cell `grid` or native CLI `cli_pack` PNG + JSON export (with optional `meta.isometric` and Godot 4 `.tres` TileSet export)
- `export_animation` — export animated GIF, WebP, or frame sequence by tag or frame range
- `render_preview` — nearest-neighbor scaled contact sheet PNG (with `tag`, `layer`, `onionSkin`, `silhouette`, `diffOverlay`, `labelFrames`, `isoGrid`, `isoOrigin`, and `showFootprint` overlays) for visual inspection
- `execute_lua` — escape hatch for arbitrary Aseprite Lua inside a transaction (disabled by default; enable with `ASEPRITE_MCP_ENABLE_EXECUTE_LUA=1`)
- `import_reference` — turn a high-res reference image into a palette-locked pixel-art base layer (see below)
- `check_asset` — pass/fail validation of a sprite against the project's `pixel-style.json` (including isometric diamond `seamless`, `opaque_tiles`, diagonal `baseline`, and `iso_jaggies`)
- `split_layer` — move pixels from a flat layer into named (optionally grouped) layers by area and/or colour, filling the hole behind
- `analyze_motion` — check how an animation moves: spacing, duration-aware velocity, easing, twitches, stalls, 2D `arc_kink`, popping, swing balance, head bob, 1-frame pixel-boil `flicker`, `volume_drift`, planted feet that skate (including 2D diagonal isometric strides), and differences between directions (with per-tag `loop` overrides `{ idle: true, cast: false }` and a numbered motion-trail PNG)
- `preview_subject_mask` — draw traced subject polygons over a photo to check them before a photo import
- `plan_asset` — the shared, step-by-step workflow for an asset, with the project style and pre-filled tool calls (including `iso_tileset`, `iso_prop`, `iso_character`, `iso_animation`, `iso_diorama`, `iso_map`)
- **MCP Resources & Prompts**:
- `aseprite://palette/hearth_16` + auto-discovered workspace `file://.../*.aseprite` resources
- `create-character-sprite`, `inspect-and-edit-sprite`, and `create-isometric-scene` prompt templates
## Consistent results across agents
Three pieces work together:
1. **Server instructions.** The `initialize` reply carries a short `instructions` text that MCP clients add to
the agent's system prompt: call `plan_asset` first, use only the style palette, convert images with
`import_reference`, and finish only when `check_asset` passes.
2. **`plan_asset { path, assetType | workflow, referencePath?, goal? }`** returns the style that applies,
canon reference files, house rules, and an ordered list of tool calls with arguments pre-filled, ending
in the `check_asset` gate. Workflows: `portrait_from_photo`, `illustration_from_reference`, `illustration`, `character`,
`animation`, `prop`, `icon`, `tileset`, `tilemap`. With an `assetType` the workflow is picked from its kind
(a character with `tags` gets `animation`, a tile gets `tileset`); `tilemap` must be asked for by name.
It reads files only and never starts Aseprite.
3. **`pixel-style.json` + `check_asset`**, below: the shared constraints and the pass/fail gate.
**Canon references:** put approved example assets (`.aseprite`, `.png`, `.gif`) in a `canon/` folder next to
`pixel-style.json`. `plan_asset` returns the ones whose path contains the asset type or kind (otherwise all
of them, up to 8) so agents can match proportions, cluster size and detail level.
## `pixel-style.json` + `check_asset`
Put a `pixel-style.json` in a project's asset folder (or any folder above the sprites, inside the
workspace). Every tool finds the nearest one above the sprite it touches, so every agent (Claude,
Gemini, Codex, …) works from the same palette, outline colour, sizes and animation timing
without being told. Start from [`examples/pixel-style.example.json`](examples/pixel-style.example.json).
| Field | Meaning |
| --- | --- |
| `palette` | Single-character key → colour. The only colours assets may use; the keys are the `draw_pixels` matrix keys. |
| `ramps` | Named dark→light groups of palette keys (documentation for agents, validated to exist). |
| `outline` | `color` (key or hex), `allowDoubles` (default false), `maxOrphans` (default 3: more isolated 1px pixels than this warns), `maxOrphanShare` (default 0.02: more than this share of the figure fails as speckle noise). |
| `lighting` | Free text, e.g. `top_left` (derives default 3-plane isometric light/mid/dark shading). |
| `projection` | Optional axonometric projection (`type`: `orthographic` / `iso_2_1` / `iso_3_4` / `dimetric` / `military` / `oblique`, `tileWidth`, `tileHeight`, `elevationStepPx`, `apex`: `even_2px` / `even_4px` / `odd_1px`, `gridLayout`). See [`examples/pixel-style.isometric.example.json`](examples/pixel-style.isometric.example.json). |
| `assets` | Asset types. `kind` is `character`, `tile`, `icon`, `illustration`, `prop`, or `diorama` (defaults to the type's name). Options: `size` (one tile for tiles), `baselineRow`, `requirePivot`, `tags`, `maxColours`, `seamless`, `outline: false`, `opaque`, `layers`, `projection`, `footprint`, `elevationPx`, `anchor`, `directions`. |
| `animation` | `frameMs` for every frame, `tags` = frame count per tag name. `tagFrameMs` = duration per tag, as one number or one per frame (`{ "breathe_*": [250, 750], "walk_*": 130 }`; a key ending in `*` is a prefix, exact names win, then the longest prefix); it overrides `frameMs` for those frames. `airborneTags` = tags (or `prefix*`) whose frames may leave the baseline, e.g. runs and jumps; they still may not go below it. |
| `guideLayerPrefix` | Default `_`. Layers named with this prefix (or inside a group that is) are working layers: blocking shapes, ground lines, references. `check_asset` and `analyze_motion`'s whole-figure measures leave them out, so they can use any colour; `analyze_motion` can still track them by name. `""` turns this off. |
What uses it when a style applies:
- `create_sprite` / `import_reference` — style palette by default; `assetType` fills in width/height and is recorded in the sprite for `check_asset`.
- `draw_pixels` / `manage_tilesets draw_tile` — keys resolve **only** against the style (plus `paletteMap`
aliases); unknown keys and off-style colours are errors (`allowOffPalette: true` for deliberate exceptions).
- `import_reference` — snaps to the style palette and uses its keys and outline colour.
- `lint_pixel_art` — style palette and outline colour by default.
- `apply_transform` — outline actions default to the style outline; `quantize_palette` to the style palette.
`check_asset { path, assetType? }` returns `passed` plus one entry per check (`error` or `warning`):
| Check | Applies to |
| --- | --- |
| `canvas_size` / `tile_grid` | all (tiles: canvas is a multiple of the tile size) |
| `palette`, `max_colours` | all |
| `outline_doubles` or `no_outline` | all (`no_outline` when the type has `outline: false`) |
| `orphan_pixels` (warning; error above `maxOrphanShare`) | all but tiles |
| `baseline` / `baseline_consistent` (airborne tags may lift off), `empty_frames`, `pivot` | characters |
| `required_tags`, `tag_frame_counts`, `frame_duration` (per tag via `tagFrameMs`) | anything with tags / several frames |
| `required_layers` | types with `layers` (a group or a layer inside one counts) |
| `seamless`, `opaque_tiles` | tiles |
Agents should treat an asset as done only when `check_asset` passes.
## Converting an image into pixel art: `import_reference`
Don't have the agent hand-type every pixel of a reference: its spatial vision isn't precise
enough, and proportions drift (face too low, hat too big, hair mass lost). Start from
`import_reference` instead and spend the agent's effort on cleanup.
What it does (about 0.5 s for a 1254×1254 PNG to 64×64):
1. Aseprite loads the reference (any format it opens; frame 1, flattened) and hands raw RGBA to Node.
2. Palette: the given one, or `paletteSize` colours (default 16) extracted with deterministic
weighted k-means over *flat* pixels only, so anti-aliasing fringe colours don't steal slots.
Extracted colours no cell uses are dropped.
3. Every source pixel snaps to the palette; each target cell takes the **majority** colour of its
block (no averaged in-between colours).
4. Line art: the darkest colour (when dark enough), plus any colour within a small luminance band of it,
counts as ink. Cells whose block is at least `lineCoverage` ink (default 0.18) become outline, so thin
line work survives the downscale.
5. Optional `transparentBackground` flood-fills the dominant border colour to transparent.
6. The base is written to `layer` (default `reference_base`) of a new or existing sprite.
The reply carries `paletteMap` + `rows` (reuse them directly with `draw_pixels` / `lint_pixel_art`),
`outlineKey`, `nearDuplicateColours`, per-colour cell counts and `nextSteps` for the cleanup pass.
Typical flow: `import_reference` → `render_preview` next to the reference → clean up (thin doubled
outlines, reconnect lines, redraw eyes/mouth/highlights, merge near-duplicates, add shading clusters) →
`lint_pixel_art` with the returned `paletteMap` and `outlineKey` (a flat backdrop is detected and ignored).
Knobs: `fit` (`cover` / `contain` / `stretch`), `crop`, `lineArt: "off"` for lineless art,
`outlineColor` to pick the ink yourself, `lineCoverage` (raise if outlines come out thick, lower if they break).
## Modular layers: `split_layer`
Imports and image-model output arrive as one flat layer. `split_layer { path, layer, parts, sourceName?, fillBehind? }`
moves pixels into named layers so later edits stay local (recolour the roofs, hide the trees, move a building):
- each part takes pixels by **colour** (hex or palette keys, exact match), by **area** (`polygons` / `rects` in sprite
pixels), or both (a material inside an area: roof colours inside the church outline);
- parts are listed **bottom to top** and stacked above the source layer; where parts overlap, the later one wins;
- `group` puts parts in a group layer (`buildings/church`, `buildings/mill`);
- `fillBehind` (default on) fills what each part took out of the source layer from the surrounding pixels, so hiding
or moving a part shows terrain rather than a hole. The flattened image is unchanged by a split.
Add `layers` to an asset type in `pixel-style.json` to make a layer structure part of the house style; `plan_asset`
then includes the split step and `check_asset` fails without those layers.
## Checking motion: `analyze_motion`
`check_asset` judges frames one at a time. `analyze_motion { path, tag | tags | fromFrame..toFrame, trackers?, loop?,
groundRow?, groundTravelDx?, outputPng?, scale? }` judges what happens between them. Each tracker follows a part:
- by **layer** (its own pixels, even when the layer is hidden, so blocked-in limb shapes on guide layers work),
**colours** (exact match), a **region**, or a mix; with no trackers, every visible layer is followed;
- from an **anchor** point: `centroid`, the middle of an edge (`top` for a head, `bottom` for a foot) or a corner;
- with `follow: {x, y}` to stay on one connected shape when two parts share colours. Shapes that touch merge, and the
tool reports `merged` for those frames; distinct colours track more reliably.
Warnings per tracker: `spike` (rests, jumps out for one frame and straight back, 2px or more), `stall` (stops mid-move,
then carries on the same way), `jump` (a step far longer than the typical one), `no_ease` (the biggest step runs into
or out of a turnaround), `unbalanced` (more frames on one side of a swing), `pops` / `shape_pop` (missing in some frames,
or an abrupt size change). For the whole figure it reports the **bob** (top row per frame) and **ground contacts** on
the baseline row: with `groundTravelDx` (pixels the ground moves per frame, or a `{tag: dx}` map), planted contacts
that don't move that far are reported as `skate`. With several `tags` it compares directions: `bob_differs`,
`bob_phase` and `height_differs` / `size_differs` per tracker.
`outputPng` writes one panel per tag: the first frame at half strength over an onion skin of the others, with each
tracker's path drawn on top (dots brighten from the first frame, which has a dark ring, to the last).
## Photos: `source: "photo"`
Drawn art and photos need different handling. A photo has no ink lines and no flat colour areas, so the art
mode turns it into a posterised photo (dark backgrounds become outline blobs, gradients become speckle).
Photo mode works subject-first:
1. The agent (a vision model) looks at the photo and traces each person as a polygon in reference pixels:
hair and clothes inside, other people outside, the whole figure even for a head-and-shoulders portrait.
2. `preview_subject_mask { referencePath, subjects, outputPng, crop? }` writes an overlay (outside dimmed,
polygon in magenta, framing in yellow) so the agent can check and fix the trace.
3. `import_reference { source: "photo", subjects, crop: "subjects_upper" | "subjects" | {…}, background }`:
- subjects: their own colours (`paletteSize`, default 12; 8 gives a flatter, more pixel-art look),
per-cell **mean** colours (stable on photo grain), speckle removal, and a 1px silhouette outline;
- background (`simplified` default: `backgroundColours` softened colours in 2x2 clusters; `full`; or
`none`) on its own layer below;
- layers `subject` and `background`; the style palette is used for both when a `pixel-style.json` applies.
4. **Stylise** (the agent's step): the import is a flattened photo, and real proportions read as blank at 64px.
Redraw eyes, mouth, blush and hair clumps deliberately, remove things like other people's hands.
`plan_asset { path, referencePath, referenceKind: "photo" }` returns these steps in order.
**Agents with an image model** (e.g. ImageGen) pass `imageModel: true`. The plan then has the image model do
the stylising, which it does far better than placing pixels, but holds it to the house format: a prompt
with the exact target grid, the style palette and lighting, and no dithering or speckle; then
`import_reference` in art mode (`lineArt: "off"`) at the same size, so the result snaps to the style palette;
then `lint_pixel_art` to remove the isolated specks image models leave behind; then `check_asset`.
## Build & Test
```zsh
cd aseprite-mcp
npm install # once: installs the pinned build-only devDependencies (typescript, @types/node)
npm run build
npm test # unit tests (no Aseprite needed)
npm run test:e2e # end-to-end against the real Aseprite binary
```
The server itself still has zero runtime dependencies: `dist/` runs on plain Node.js, and `node_modules/`
is only needed to compile.
## Client Configuration
Pass your workspace root directory as the second entry in `args` and/or via `ASEPRITE_WORKSPACE_ROOT` (see [`mcp-config.example.json`](mcp-config.example.json)). Paths outside that root are refused.
Common client config locations:
| Agent | Config file | Scope |
| --- | --- | --- |
| Claude Code | `~/.claude.json` → top-level `mcpServers.aseprite` | user |
| Codex | `~/.codex/config.toml` → `[mcp_servers.aseprite]` | global |
| Cursor | `~/.cursor/mcp.json` → `mcpServers.aseprite` | global |
| Antigravity | `~/.gemini/config/mcp_config.json` → `mcpServers.aseprite` | global |
Notes:
- Use an absolute `node` path (such as `/opt/homebrew/bin/node` on Apple Silicon macOS) if GUI clients don't inherit your shell `PATH`.
- `ASEPRITE_BIN` is optional when Aseprite is installed in standard macOS/Steam locations or available on `PATH`.
- `execute_lua` is disabled by default; set `"ASEPRITE_MCP_ENABLE_EXECUTE_LUA": "1"` in `env` if you explicitly want to expose it.
- After `npm run build`, restart your MCP client to pick up the new `dist/`.
```json
{
"mcpServers": {
"aseprite": {
"command": "node",
"args": [
"/path/to/aseprite-mcp/dist/index.js",
"/path/to/your/workspace"
],
"env": {
"ASEPRITE_BIN": "/path/to/aseprite",
"ASEPRITE_WORKSPACE_ROOT": "/path/to/your/workspace"
}
}
}
}
```
## Review and revise a sprite
All frame numbers supplied to MCP are one-based. The atlas JSON uses zero-based indices.
| Task | Tool arguments | Result |
| --- | --- | --- |
| Review a face | `render_preview {path, review:true, beforePath, frames:[1], crop:{x:20,y:4,width:20,height:13}, scale:8, pivotSlice:"feet", outputPng}` | Native pose beside its enlarged crop, with the prior revision above the current one. Add `beforeFrames` to select different source poses. |
| Watch a loop and inspect its poses | Use review mode with `frames:[3,4,5,6,7,8]`, `columns:3` and `outputGif` | The loop plays above the selected pose strip. The response includes the saved images as MCP image blocks. Set `inline:false` for paths and metadata only. |
| Measure a stance | `analyze_motion` with two named trackers, `pair:["left boot","right boot"]`, `groundRow:62`, `phases:["contact","down","passing","contact","down","passing"]` and optionally `pairOutputPng` | One column per frame and one row per run. The first point is gold and the second cyan. Each sample gives horizontal separation and each shape’s bottom clearance. Use `anchor:"box_center"` for boot-center separation. Missing points yield null. The contact and passing means are descriptive. |
| Compare lint results | `lint_pixel_art {path, beforePath, frame, beforeFrame, outputPng, crop, scale}` | Introduced and resolved findings under the same palette and rules, including positions beyond the ordinary 50-sample cap. Red marks introduced pixels and teal marks resolved ones. The crop affects the image only. JSON includes exact counts and up to 100 positions per list. |
| Visual lint overlay & pagination | `lint_pixel_art {path, flattened:true, limit:200, filterLayer, outputPng, overlayKinds}` | Pages past 50 findings (`offset`/`limit`), reports full `countsByLayer`, ignores smooth curved arcs in `isoJaggies` (`ignoreCurves: true` default), and renders a standalone zoomed overlay PNG highlighting findings by color (`overlayLegend`). |
| Export tagged rows | `export_spritesheet {path,frameTags:["walk_s","walk_n"],outputPng,outputJson,verify:true}` | One row per tag in the supplied order. Short rows are padded with transparency. Frame indices, durations, slice keys and pivots follow the exported order. Verification decodes the PNG and compares each cell with its source frame. |
| Use a style outside the asset tree | `plan_asset {path,assetType:"character",style:"assets/aseprite/pixel-style.json"}` | The plan carries the explicit style into subsequent style-aware tool calls. Relative paths resolve against the MCP workspace. |
### Propagate an artist’s revision
```json
{
"path": "walk.aseprite",
"beforePath": "idle-before.aseprite",
"afterPath": "idle-revised.aseprite",
"sourceFrame": 1,
"layers": ["Face", "Contour"],
"targets": [{"frame": 3, "dy": 1}, {"frame": 4, "dx": -1, "dy": 1}],
"outputPng": "review/head-revision.png"
}
```
Call `apply_revision` with these arguments to see the layer delta, affected pixel count and conflicts. Optional `anchorLayer` derives the translation from that layer’s occupied bounds. Target offsets add to that translation. Set `apply:true` to write the edits. All target frames must pass the old-color check, and pixels already carrying the new value are skipped. A conflict leaves the target file intact. Edited linked cels are detached so other frames keep their artwork. Indexed revisions require matching palettes and transparency indices.
Single GIFs use cumulative centisecond rounding by default. Six 83 ms frames export as 80, 90, 80, 80, 90 and 80 ms. Set `gifTiming:"native"` for Aseprite’s native quantization. Split exports keep native timing.
## License
MIT — see [LICENSE](LICENSE).