convez.ai
MCP ServerAutomaçãoIntermediário
khodulov-m

SwiftMageX

khodulov-m/SwiftMageX

Geração de imagens no terminal com suporte a Claude Code via MCP

Ver no GitHub
InicialPluginScore · de 0 a 100

CLI nativo macOS para geração e edição de imagens via Gemini/Imagen com MCP server integrado. Combina processamento local (redimensionamento, remoção de fundo, composição) com modelos de IA do Google, permitindo que agentes Claude gerem e editem imagens automaticamente.

Instalação

$npx convez-ai khodulov-m/SwiftMageX

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
1
Forks
0
Acompanhando
0
Saúde
42%
Último commit
há 5 dias
Versão
v0.3.0
Issues abertas
0
Contribuidores
1

Casos de uso

  • Gerar imagens via CLI ou Claude Code durante workflows de desenvolvimento
  • Processar screenshots e criar assets para App Store automaticamente
  • Editar e compor imagens localmente sem enviar dados para servidores
  • Integrar geração de imagens em pipelines de automação macOS

Veredito

Ferramenta sólida para quem trabalha exclusivamente em macOS e precisa de geração de imagens programável. O MCP server é seu maior valor: transforma Claude em gerador de imagens nativo. Limitação clara: macOS/Apple silicon only, sem suporte a Linux ou Windows.

README

A tradução para o português deste README ainda está na fila.

SwiftMageX

English · Español · Français · Deutsch · 简体中文 · 日本語 · 한국어 · Português (BR) · Italiano · Русский

Generate, edit, and polish images straight from your terminal — and teach your AI agent to do the same. SwiftMageX is a native macOS CLI that talks to Google's image models (Gemini and Imagen) for generation and editing, and does the everyday raster work right on your Mac.

What you get:

  • 🎨 Generation and editing in one command — text-to-image, image-to-image, multi-image composition, and mask-based inpainting, with the model selectable per call to match your quality needs.
  • 🤖 Claude Code that can make pictures — the bundled MCP server (swiftmagex-mcp) exposes every capability as a tool, so Claude Code, Claude Desktop, or any MCP client learns to generate, edit, and process images as part of its workflow.
  • 📱 App Store screenshots in one run — frame a screenshot in a device bezel, drop it onto a background, add a caption, and batch-resize to App Store Connect sizes.
  • 🔒 Private and free where it counts — resize, text overlay, compositing, background removal, and smart crop run fully on-device with CoreImage / CoreText / Vision. No API key, nothing leaves your Mac.
  • 🪶 Tiny footprint — one small Swift package, exactly two external dependencies, two self-contained binaries.

See SwiftMageX-MVP-0.1-spec.md for the authoritative specification and RELEASE_NOTES.md for what shipped in v0.2.0.

Requirements

  • macOS 14+ on Apple silicon (arm64)
  • Swift 6.0+ toolchain (Xcode 16+) — only required to build from source
  • A Google AI API key in SWIFTMAGEX_GEMINI_API_KEY (or GEMINI_API_KEY) for the generate command — used for both Gemini and Imagen models. resize, text, composite, appstore, remove-bg, crop, and icon need no key.

Installation

Prebuilt binary (recommended)

Grab swiftmagex, swiftmagex-mcp, and SHA256SUMS from the v0.2.0 release, verify the checksums, then drop the binaries on your PATH:

shasum -a 256 -c SHA256SUMS
chmod +x swiftmagex swiftmagex-mcp
sudo mv swiftmagex swiftmagex-mcp /usr/local/bin/
swiftmagex --version    # 0.2.0

If macOS Gatekeeper quarantines the downloads, clear the flag:

xattr -d com.apple.quarantine /usr/local/bin/swiftmagex /usr/local/bin/swiftmagex-mcp

Build from source

git clone https://github.com/khodulov-m/SwiftMageX.git
cd SwiftMageX
swift build -c release
# binaries land in .build/arm64-apple-macosx/release/
cp .build/arm64-apple-macosx/release/swiftmagex     /usr/local/bin/
cp .build/arm64-apple-macosx/release/swiftmagex-mcp /usr/local/bin/

Run from source without installing

swift run swiftmagex <subcommand> …      # CLI
swift run swiftmagex-mcp                 # MCP server (stdio transport)
swift test                               # full test suite
scripts/check.sh                         # build + test in one step

Configuration

Export the Gemini API key in your shell profile (only needed for generate):

export SWIFTMAGEX_GEMINI_API_KEY="…"   # preferred
# or, as a fallback the tool also reads:
export GEMINI_API_KEY="…"

Never embed the key in scripts you commit. The CLI never prints, logs, or writes the key to disk — including under --verbose and inside output file metadata.

Quick manual

Eight subcommands, all sharing the same global flags:

Global flagEffect
--jsonEmit a structured JSON envelope to stdout instead of human-readable text.
-v, --verbosePrint diagnostic messages to stderr. Does not include the API key.
--cache-dir <path>Cache generate/edit responses under <path> so identical inputs replay previously-recorded provider bytes instead of calling the API. Opt-in — see Response caching.
--versionPrint 0.2.0 and exit.
-h, --helpShow help for the command.

Output file paths are always absolute in --json output and in MCP tool results — agents don't need to know the working directory.

swiftmagex generate — text-to-image via Gemini or Imagen

swiftmagex generate <prompt> [options]
OptionDefaultNotes
<prompt>—Required positional argument.
-o, --output <path>./File or directory. If a directory, files are named swiftmagex_{timestamp}_{index}.png.
-s, --size <square|portrait|landscape>squareAspect-ratio hint. Actual resolution depends on the model.
-n, --count <1–4>1Number of variants. Each variant is a separate request.
--seed <uint64>—Recorded in metadata even when the provider ignores it.
--model <id>gemini-2.5-flash-imageBuilt-ins: Gemini family (gemini-2.5-flash-image, gemini-3-pro-image-preview, gemini-3.1-flash-image-preview) and Imagen family (imagen-4.0-generate-001, imagen-4.0-fast-generate-001, imagen-4.0-ultra-generate-001). Unknown IDs route by imagen-/gemini- prefix.
# Single image to the current directory
swiftmagex generate "neon-lit cyberpunk alley in the rain"

# Four landscape variants to a directory, structured output
swiftmagex generate "mountain landscape at dawn" -n 4 -s landscape -o ./out --json

# Reproducible seed (provider-dependent)
swiftmagex generate "minimalist app icon, fox head" --seed 42 -o icon.png

Example — the call below produced the image on the right (1024×1024 PNG from gemini-2.5-flash-image):

swiftmagex generate "A simple red apple on a white background, test image" \
  -o apple.png

Each output PNG carries the prompt, model, seed, timestamp, and tool version in tEXt chunks (JPEG variants use the EXIF UserComment field).

Pick the model to match your quality needs. Models are interchangeable per call via --model — nothing else about the command changes. The default gemini-2.5-flash-image is the stable all-rounder; the newest gemini-3.1-flash-image-preview produces noticeably more detailed results and picks wider, non-square framings on its own; the Imagen family offers explicit aspect-ratio control (--size maps to aspectRatio), with imagen-4.0-fast-generate-001 tuned for speed and imagen-4.0-ultra-generate-001 for maximum fidelity (one image per call). For example, gemini-3.1-flash-image-preview produced this 1408×768 frame:

swiftmagex generate "A red fox curled up on a mossy rock in a misty autumn forest, golden leaves falling, soft photorealistic style" \
  --model gemini-3.1-flash-image-preview -o fox.png

swiftmagex edit — image-to-image / multi-image / inpainting via Gemini

Send a source image (plus any additional references and an optional mask) to a Gemini model alongside the text prompt. Each image is encoded as an inlineData part of the same :generateContent call generate uses — no new endpoint, no new dependency.

swiftmagex edit <input> <prompt> [options]
OptionDefaultNotes
<input>—Required. Primary source image (PNG or JPEG).
<prompt>—Required. Text instruction describing the edit.
--reference <path>—Repeatable. Additional reference image (PNG or JPEG). Each --reference becomes another inline image part the prompt can compose against — e.g. "take the subject from image 1 and put it in scene 2".
--mask <path>—Optional grayscale/binary mask (PNG or JPEG). White marks the region to edit on the primary input, black preserves the original.
-o, --output <path>./File or directory. If a directory, files are named swiftmagex_{timestamp}_{index}.png.
-n, --count <1–4>1Number of variants. Each variant is a separate request.
--seed <uint64>—Recorded in metadata even when the provider ignores it.
--model <id>gemini-2.5-flash-imageMust be a Gemini model — Imagen's :predict shape does not accept inline image inputs and is rejected with exit code 2.
# Change the colour of a subject
swiftmagex edit apple.png "make the apple green instead of red" -o edited.png

# Inpaint a region with a mask
swiftmagex edit photo.png "replace the marked region with a sunset sky" \
  --mask sky-mask.png -o photo_edited.png

# Compose across two reference images
swiftmagex edit person.png "place the person from image 1 into the scene of image 2" \
  --reference street.png -o composed.png

# Four variants of the same edit
swiftmagex edit shot.jpg "add a snowy mountain in the background" -n 4 -o ./out

Examples — three before / after pairs (sources and edits in examples/):

SourceEditedEdit prompt
"Change the apple's color from red to bright green, keep everything else identical"
"Add a single colorful hot-air balloon floating in the sky above the mountains"
"Transform the scene from a sunny summer day to a snowy winter day"

Multi-image composition — combine a subject with a scene via --reference:

Input (subject)Reference (scene)Result
swiftmagex edit examples/canoe.png \
  "Place the canoe from image 1 onto the lake from image 2, match the lighting and add reflections" \
  --reference examples/mountain.png -o examples/canoe-on-mountain-lake.png

Edited outputs carry the same tEXt/EXIF metadata as generate — the prompt recorded is the edit instruction, not the original generation prompt.

Response caching

Pass --cache-dir <path> to generate or edit to short-circuit the network call when an identical request has already been served. The cache is content-addressed: the key is a SHA-256 over model, prompt, size, count, seed, plus the SHA-256 of every reference image and mask byte payload. On a hit, the bytes are replayed from disk and a fresh output file is still written with up-to-date tEXt/EXIF metadata (timestamp, tool version), so downstream pipelines behave identically.

# First call hits the API; second call replays from /tmp/sx-cache.
swiftmagex generate "a red apple on white" --cache-dir /tmp/sx-cache
swiftmagex generate "a red apple on white" --cache-dir /tmp/sx-cache --json
# → "cached": true in the JSON output for every replayed image

Caveats:

  • Opt-in by design. Gemini does not honor --seed, so identical inputs are meant to vary across calls — a cache hit silently turns that intentional non-determinism into "same bytes every time." Only pass --cache-dir when you want that.
  • Best-effort. Cache I/O failures (unwritable directory, corrupt entry) degrade to a normal network call rather than aborting the command.
  • No eviction. The cache grows until you rm -rf the directory.
  • Cache surface lives on generate / edit only (the local raster commands don't hit a provider). The MCP server doesn't expose caching in 0.1; the CLI flag is the only entry point today.

swiftmagex resize — local resize / crop / format conversion

swiftmagex resize <input> [options]
OptionDefaultNotes
<input>—PNG, JPEG, HEIC, or WebP. Write is PNG / JPEG only.
-w, --width <px>—At least one of width / height is required.
-h, --height <px>—When only one is given, the other is computed by aspect ratio.
--fit <contain|cover|fill>containcover and fill require both dimensions.
-o, --output <path>sibling of sourceDefaults next to the source file.
--format <png|jpeg>matches sourceHEIC / WebP sources default to PNG.
--quality <0.0–1.0>0.9JPEG only.
# Square thumbnail, crop overflow
swiftmagex resize photo.png -w 512 -h 512 --fit cover -o thumb.png

# 1200-wide banner, JPEG re-encode at 80 % quality
swiftmagex resize banner.png -w 1200 --format jpeg --quality 0.8

# Half-size, aspect ratio preserved (only width given)
swiftmagex resize cover.heic -w 1024 -o cover_1024.png

swiftmagex text — text overlay

swiftmagex text <input> --text "<string>" [options]
OptionDefaultNotes
<input>—Image to draw on.
--text <string>—Required. \n produces a line break; long lines word-wrap.
--positionbottomOne of top, center, bottom, top-left, top-right, bottom-left, bottom-right.
--font <name>system fontE.g. "Helvetica-Bold".
--font-size <pt>48
--color <hex>#FFFFFF#RRGGBB or #RRGGBBAA.
--stroke <hex>—Omit for no stroke.
--stroke-width <pt>2.0Only used when --stroke is set.
-o, --output <path>sibling of source
swiftmagex text screenshot.png --text "Download on the App Store" --position bottom
swiftmagex text cover.png --text "SALE" --position center --font-size 96 --stroke "#000000"

swiftmagex composite — paste one image onto another

swiftmagex composite <background> --overlay <foreground> [options]
OptionDefaultNotes
<background>—The canvas image.
--overlay <path>—Required. Foreground pasted on top (alpha respected).
--positioncenterSame seven anchors as text.
--scale <fraction>1.0Foreground size as a fraction of the background; aspect ratio preserved.
--offset-x, --offset-y <px>0Nudge from the anchor (positive = right / down).
--opacity <0.0–1.0>1.0Foreground blend opacity.
-o, --output <path>sibling of background
--format <png|jpeg>, --qualitymatches background / 0.9
swiftmagex composite bg.png --overlay logo.png --position top-right --scale 0.2 -o hero.png

swiftmagex appstore — App Store Connect screenshots

Frames a screenshot inside a device bezel, scales it onto a background, overlays an optional caption, and writes the result at one or more App Store Connect iPhone pixel sizes — batched in a single run.

swiftmagex appstore <screenshot> --background <bg> [options]
OptionDefaultNotes
<screenshot>—The captured screenshot placed into the frame.
--background <path>—Required. Filled (cover) behind the device.
--frame <path|id>autoiPhone bezel: a PNG path with a transparent screen cutout, or a bundled frame id (e.g. iphone-6.5-pommeplate-spacegray). Omit to auto-pick a bundled frame for the requested device.
--list-frames—List the bundled device frames and exit. Pair with --json for a parseable shape.
--screen-rect <x,y,w,h>auto-detectWhere the screenshot goes inside the frame. Auto-detected from the frame's alpha when omitted.
--device <id>iphone-6.9Repeatable. One of iphone-6.9 (1290×2796), iphone-6.5 (1242×2688), iphone-5.5 (1242×2208), or all.
--orientation <portrait|landscape>portraitSwaps the device dimensions.
--scale <fraction>0.85Framed-device size as a fraction of the canvas.
--position, --offset-x, --offset-ycenter, 0, 0Where the device sits on the background.
--caption <string>—Optional caption text.
--caption-position, --font, --font-size, --color, --stroke, --stroke-widthbottom, system, 96, #FFFFFF, —, 0Caption styling (same engine as text).
-o, --output <dir>./Output directory; files are named appstore_{device}_{w}x{h}.png.
# Use the bundled iPhone 6.5" bezel (no --frame needed)
swiftmagex appstore shot.png --background bg.png --device iphone-6.5 \
  --caption "Plan your week" --stroke "#000000" --stroke-width 6

# Custom bezel, every catalogued iPhone size in one go
swiftmagex appstore shot.png --background bg.png --frame iphone.png --device all -o ./shots

Built-in device frames

SwiftMageX ships a CC0-licensed iPhone 11 Pro Max / XS Max bezel from PommePlate (Space Grey, derivative with a punched screen cutout — see Resources/Frames/ATTRIBUTION.md). Pass --device iphone-6.5 and it's used automatically; supply --frame <path> to override with your own art. To list everything bundled:

swiftmagex appstore --list-frames
# → iphone-6.5-pommeplate-spacegray  iphone-6.5  iPhone 11 Pro Max / XS Max — Space Grey (PommePlate)

User-supplied frames still work the same way — any PNG with a transparent screen hole; the screen region is auto-detected from the alpha channel (or pin it with --screen-rect).

swiftmagex remove-bg — local background removal

Cuts out the salient foreground subject and leaves it on a transparent background, using Vision's on-device segmentation — no AI API, no key, zero quota. The result always carries an alpha channel, so it is written as PNG (a non-.png --output extension is coerced to .png).

swiftmagex remove-bg <input> [options]
OptionDefaultNotes
<input>—PNG, JPEG, HEIC, or WebP.
-o, --output <path>sibling of sourceAlways written as PNG.
# Cut out the subject onto a transparent background
swiftmagex remove-bg photo.jpg -o cutout.png

# Defaults to a PNG sibling of the source
swiftmagex remove-bg product.heic

If no salient foreground subject is detected, the command fails with a raster error (exit 1).

swiftmagex crop — saliency-aware aspect-ratio crop

Crops to a user-supplied aspect ratio with the crop window centered on the salient subject picked by Vision's on-device attention model — not the geometric centre. No AI API, no key, zero quota. The output keeps the source's pixel scale (this is a crop, not a resize) and defaults to the source format.

swiftmagex crop <input> --aspect <W:H> [options]
OptionDefaultNotes
<input>—PNG, JPEG, HEIC, or WebP. Write is PNG / JPEG only.
--aspect <W:H>—Required. Two positive integers, e.g. 1:1, 4:5, 9:16.
-o, --output <path>sibling of source
--format <png|jpeg>matches sourceHEIC / WebP sources default to PNG.
--quality <0.0–1.0>0.9JPEG only.
# Square crop centered on the salient subject
swiftmagex crop photo.jpg --aspect 1:1

# 9:16 portrait crop, re-encode as JPEG
swiftmagex crop photo.jpg --aspect 9:16 -o portrait.jpg --format jpeg --quality 0.85

When saliency finds no salient objects (rare; flat or uniform images), falls back to a centre crop so the requested aspect ratio is still honoured.

swiftmagex icon — Icon Composer .icon packages

Assembles an Icon Composer .icon package — the layered Liquid Glass app-icon format for iOS 26+ / macOS 26+ — from prepared layer images. Fully local, no key. Layers are listed bottom-to-top and stacked on Icon Composer's 1024-pt canvas; the command writes icon.json plus Assets/ and reports the absolute package path. Prepare the layers first with generate, remove-bg, or resize.

swiftmagex icon <layer[,key=value...]>... [options]

Per-layer options are appended to the path, comma-separated: name=…, glass=true|false (Liquid Glass, default true), scale=N (multiplier on the layer's natural size, 1 source pixel = 1 point), dx=N / dy=N (offset in points from centered placement, positive = right/down), fill=#RRGGBB[AA] (solid tint), group=N (1-based; layers of one group must be contiguous, max 4 per group).

OptionDefaultNotes
<layer>...—Bottom-to-top. PNG with transparency recommended; other formats are re-encoded to PNG.
-o, --output <path>AppIcon.icon.icon is appended when missing.
--fill <solid:#HEX|auto:#HEX>solid:#FFFFFFIcon background; auto: is the system gradient seeded from one color.
--overwriteoffReplace an existing package atomically.
--flat-previewoffAlso write a flat 1024×1024 PNG composite (<name>-flat.png) — no Liquid Glass, no squircle mask — for READMEs and non-Xcode consumers.
--flat-preview-output <path>beside the package
--validateoffCompile-check the package with Xcode's actool (requires Xcode 26). Exit 4 when actool is missing, exit 2 when the package fails to compile.
# Background + glass mark, gradient fill, with a preview and a compile check
swiftmagex icon bg.png mark.png,scale=0.8,dy=-20 \
  --fill auto:#7B1FA2 -o AppIcon.icon --flat-preview --validate

# Badge pinned to the bottom-right corner, no glass, white tint, own group
swiftmagex icon art.png badge.png,glass=false,fill=#FFFFFF,dx=222,dy=223,group=2

Drop the resulting AppIcon.icon into an Xcode 26 project (or open it in Icon Composer) — Xcode renders the Liquid Glass treatment and generates the flat fallbacks for older OS versions.

JSON output schema

Every command emits the same envelope under --json. Keys are sorted; nil fields are omitted entirely (no null placeholders).

Success:

{
  "command": "generate",
  "model": "gemini-2.5-flash-image",
  "outputs": [
    { "format": "png", "height": 1024, "path": "/abs/out/swiftmagex_…_1.png", "width": 1024 }
  ],
  "provider": "gemini",
  "status": "ok"
}

Error (resize, text, remove-bg, and crop omit provider / model):

{
  "command": "generate",
  "error": { "category": "configuration", "code": 4, "message": "missing SWIFTMAGEX_GEMINI_API_KEY" },
  "status": "error"
}

Stream conventions: results → stdout; diagnostics (--verbose) → stderr. Error JSON is also written to stdout under --json so an agent can parse it in one place.

Exit codes

CodeMeaningExample
0Success—
1Unexpected / raster / I/O failureinput file unreadable, encoder failure
2Invalid inputbad --fit combo, malformed hex color, --count out of 1–4
3Provider / API failureGemini 5xx, 429 after 5 retries
4Configurationmissing SWIFTMAGEX_GEMINI_API_KEY

429 retry policy: up to 5 retries with exponential backoff 1 s → 2 s → 4 s → 8 s → 16 s.

MCP server

swiftmagex-mcp exposes ten tools — generate_image, edit_image, resize_image, overlay_text, composite_images, appstore_screenshots, list_frames, remove_background, smart_crop, and compose_icon — over stdio. Tool arguments mirror the CLI flags above (snake_case keys, e.g. font_size, screen_rect, devices); tool results report absolute file paths so the calling agent doesn't need to know the server's working directory. generate_image and edit_image additionally return the image bytes as MCP image content so the calling model can inspect what was produced. list_frames enumerates the bundled device bezels that appstore_screenshots's frame argument accepts as an id. compose_icon mirrors swiftmagex icon (layers as an array of objects) and returns the flat preview as image content when flat_preview is set — the natural agent flow is generate_image → remove_background → compose_icon.

Configure Claude Code

Claude Code registers MCP servers via claude mcp add. Inside the repo where you want SwiftMageX available, run:

claude mcp add swiftmagex /usr/local/bin/swiftmagex-mcp \
  -e SWIFTMAGEX_GEMINI_API_KEY=your-key-here

To make it available in every Claude Code session on this machine, use the user scope:

claude mcp add -s user swiftmagex /usr/local/bin/swiftmagex-mcp \
  -e SWIFTMAGEX_GEMINI_API_KEY=your-key-here

Inspect what's registered with claude mcp list or claude mcp get swiftmagex, and remove it with claude mcp remove swiftmagex. Stdio is the default transport — no --transport flag needed.

Configure Claude Desktop

Add an entry to ~/Library/Application Support/Claude/claude_desktop_config.json:

{
  "mcpServers": {
    "swiftmagex": {
      "command": "/usr/local/bin/swiftmagex-mcp",
      "env": {
        "SWIFTMAGEX_GEMINI_API_KEY": "your-key-here"
      }
    }
  }
}

The env block scopes the API key to this server only — it never lands on disk in the client's general environment.

Troubleshooting

SymptomLikely causeFix
Configuration error: missing SWIFTMAGEX_GEMINI_API_KEY (exit 4)No API key in the environment when running generate or invoking generate_image.Export SWIFTMAGEX_GEMINI_API_KEY (or the fallback GEMINI_API_KEY) — or, for MCP, add it to the client's env block as shown above.
Provider error: quota exhausted after 5 retries (exit 3)Gemini returned 429 on every attempt in the backoff window (1 s → 16 s).Wait for quota to refill, switch projects, or run again later. The backoff schedule is fixed; see spec §13.
I/O error: input file not found: /…/foo.png (exit 1)The path passed to a local command (resize / text / composite / appstore / remove-bg / crop, or their MCP tools) doesn't exist or isn't readable.Pass an absolute path, verify permissions, or check that the file format is one of PNG / JPEG / HEIC / WebP (write is PNG / JPEG only).
"swiftmagex" cannot be opened because the developer cannot be verifiedGatekeeper quarantine on a downloaded binary.xattr -d com.apple.quarantine /usr/local/bin/swiftmagex (and the same for swiftmagex-mcp).

Scope and status

This is the 0.1 MVP — three commands, two Google AI image providers (Gemini and Imagen), one MCP server — plus five post-0.1 local additions: composite, appstore, remove-bg, crop, and icon (image compositing, App Store Connect screenshots, Vision-based background removal, saliency-aware smart crop, and Icon Composer .icon packages). Anything outside that boundary is deferred; see spec §2 Scope of version 0.1 for the full out-of-scope list (edit / inpainting, local providers, Homebrew distribution, config file, Keychain, …).

License

MIT. See LICENSE for the full text.

Ver o original no GitHub

Bom para

Relacionados