Agents and MCP
Agents and MCP
How an AI agent talks to Paprika: connecting it, the tools it gets and the file format behind a design. Back to the README.
#Connecting an agent
HTTP (recommended, with the canvas open): start Paprika (docker compose up -d --build, or paprika serve from source) and point the agent at http://127.0.0.1:4777/mcp. With Docker, stdio works too: see docker.md.
Claude Code:
claude mcp add --transport http paprika http://127.0.0.1:4777/mcpToken (optional). By default /mcp answers anyone who can reach the port, which is fine on 127.0.0.1. Once the server listens on other addresses (--host 0.0.0.0 with the port published beyond the machine) or runs with --team, set PAPRIKA_MCP_TOKEN before paprika serve (or docker compose up -d): /mcp then requires Authorization: Bearer <token> and answers 401 with WWW-Authenticate: Bearer otherwise, in both protocol eras. The canvas, /api and /ws are not covered; they keep the Host/Origin check. The startup log says which mode is on.
export PAPRIKA_MCP_TOKEN="$(openssl rand -hex 32)"
claude mcp add --transport http paprika http://127.0.0.1:4777/mcp --header "Authorization: Bearer $PAPRIKA_MCP_TOKEN"stdio (for agents that only speak stdio). The process also serves the canvas on port 4777 if it's free:
{
"mcpServers": {
"paprika": {
"command": "<PATH>/paprika/server/bin/paprika",
"args": ["mcp", "--db", "<PATH>/design.db"]
}
}
}#Tool annotations and safe calls
Every tool in server/contract/mcp.json is served verbatim to the agent, including its MCP
annotations, and every one of the 72 tools carries them (a Go test, TestEveryToolCarriesAnnotations,
fails when a tool is added without them). Clients use them to decide what needs a confirmation before
running. A read-only tool sets only readOnlyHint: true; a writing tool sets all three hints:
destructiveHint: truewhen the tool can change or remove something that already exists: nodes, fields, geometry, tokens, assets, a cover, the undo position or a workspace. Every document write can still be undone withundo, exceptdelete_workspace.destructiveHint: falsewhen it only adds (new nodes, pages, copies, imports, workspaces, folders, pin replies) or only changes which workspace is active, listed, named or in which folder.idempotentHint: truewhen repeating the same call with the same arguments changes nothing more.
| Hints | Tools |
|---|---|
| read-only (18) | get_design_guide, get_document_outline, get_nodes, get_bounds, find_nodes, path_info, propose_tokens, get_history, list_workspaces, list_workspace_ops, lint_design, render_screenshot, export_image, export_code, analyze_image, compare_reference, list_pins, wait_for_pins |
| writes, destructive, idempotent (14) | delete_nodes, convert_to_path, normalize_paths, align_nodes, distribute_nodes, show_all, unlock_all, create_component, detach_instance, detach_tokens, set_tokens, set_assets, delete_workspace, set_workspace_cover |
| writes, destructive, not idempotent (16) | edit_path, update_nodes, move_nodes, group_nodes, combine_paths, outline_stroke, round_path_corners, ungroup_nodes, wrap_nodes, create_page, apply_ops, undo, redo, draw_diagram, fit_to_reference, resize_image |
| writes, not destructive, idempotent (9) | open_workspace, rename_folder, move_workspace, rename_workspace, archive_workspace, unarchive_workspace, claim_pin, update_pin, release_nodes |
| writes, not destructive, not idempotent (15) | create_nodes, repeat_nodes, create_shape_path, create_instance, create_workspace, create_folder, import_document, import_svg, import_html, import_image, place_reference, trace_image, duplicate_nodes, resolve_pin, reply_pin |
Read with the narrowest ladder that answers the question:
get_document_outline → find_nodes (one filter) → get_nodes for the ids you need → get_bounds.
Wide dumps of the tree are the usual way a design session runs out of context.
#MCP tools
| Tool | What it does |
|---|---|
get_design_guide |
Node model, accepted fields and recommended workflow; language: "pt-BR" for the Brazilian Portuguese version; topic: "styles" for one recipe per visual style (flat, minimalism, dark mode, neubrutalism, glassmorphism, neumorphism, claymorphism, material, aurora, bento grid), drawn on the board packages/e2e/fixtures/styles.paprika.json |
get_document_outline |
Compact tree + tokens + version. The first line is workspace <id> "<name>" plus version and node count. The second is changes: tokens=… nodes=… pages=… assets=… (change tokens: see the notes on workspaceId below). A renderer: line lists wasm or dom for each connected tab, in connection order, or none when no tab is connected. The last lines are the page content box (the union of the page's children, on any page) and the next free spot |
get_nodes / find_nodes |
Full node JSON / search by type, name (substring, or the whole name with exact: true, case-sensitive) or text. find_nodes also returns structuredContent {nodes: [{id, type, name, parentId, x, y, width, height}], truncated} next to its text lines. get_nodes returns the nodes that exist plus missing: [ids] (in structuredContent and the text) when some ids are gone, e.g. after an undo; it fails only when none exist |
path_info |
Validates SVG path data and returns the exact bounds (bezier and arc extremes included), the drawing origin (offset from the node origin), the normalized d, and anchors (flat index, subpath, position, and in/out handles); with id also returns canvas bounds, transform origin and rotated corners |
edit_path |
Moves one anchor of a path node, or its in/out handles, using the same helpers as the canvas. index is the flat index from path_info.anchors; position is in that same d space. One undo step. Refuses a locked node, a copy inside an instance, and an index past the last anchor |
get_bounds |
Absolute boxes after auto-layout (row/column, hug/fill, wrap): x/y/width/height, transform origin (box centre) and the four corners after rotation, clockwise from the unrotated top-left in the same direction as CSS rotate(); optional ids / rootId. painted: true adds painted: the box of the drawn ink per node (a path's geometry instead of its viewBox frame, plus the stroke outside the shape; for a frame or group, the union of its visible children, clipped when the frame clips; shadows left out), so "is this symbol centred in its tile" is one call. A layout.wrap frame breaks into lines like CSS flex-wrap (the same gap between items and between lines), so a hug height is the sum of the lines. ids may sit on different pages: each id gets a box, and one that exists but has none (a page, or a node hidden inside an auto-layout frame) is named in unplaced with a reason. With no ids, it covers the first page (use a page id as rootId for another) and also returns the page content box (the union of the page's children, on any page) and the next free spot |
create_nodes |
Creates nested trees in one call. Returns {ids, roots, created, version}: ids is every new id (the old list); roots is each new node whose parent was not created in that call (id, name, type, x, y, width, height); created is every new node (id, name, type, parentId). The text is that JSON plus one line per root. On a connector x/y/width/height/d follow from/to, so a copied node that carries them gets a warning instead of a refusal; a path without width/height (and without viewBox) gets a box that hugs its ink: the drawing moves to (0,0) and x/y absorb the offset, so a d in frame coordinates under x: 0, y: 0 (as trace_image {dryRun} returns) selects and lays out where it is drawn. normalize: false keeps d as written (the box runs from the node origin to the far edge); normalize: true does the move even when a size is given. place: "free" (default for a top-level node with no x/y: right of the page content, same top, gap 80, wrap past 2400), "below", "right", {near, side} or "none" (exact x/y; inside a row/column frame each root also gets layoutPositioning: "absolute" and a warning says so, unless you set layoutPositioning yourself). A new top-level node that overlaps another comes back in warnings with the nearest free spot. A rect, ellipse or path given children is created as a frame with that contour and listed in converted (see the conversion operations below) upsert: true updates the nodes whose id already exists instead of refusing them: their fields merge as in update_nodes (fields left out stay), the type must match, a node keeps its place unless it is listed under another parent, and listed children are upserted the same way; new ids are created as usual, all in one undo step. A re-run drawing script then edits the frame in place, so pins on it and children it does not list survive. prune: true also deletes the children of a listed node that the call no longer lists anywhere (a node listed without children keeps all of them). The result adds updated and deleted. |
draw_diagram |
Draws a diagram (flowchart, architecture, mind map) from a list of shapes and edges: lays the shapes out in layers (direction: down or right, to the right of existing content) and connects them with arrows that follow the shapes. Elbow and rounded routes bend around other shapes in the same parent; straight and curve do not. An edge can carry a label and a route (straight, elbow, rounded, curve) with optional radius / control. relayout: true accepts existing shape ids, updates x/y when given, and routes those connectors again in one undo step |
update_nodes / move_nodes / delete_nodes |
Atomic batch edits. A new d on a path with no width/height/viewBox in the same update renormalizes the box to the ink (x/y absorb the offset, the ink stays where the new d puts it); normalize: false in that node's props keeps d as written. index in update props or in move sets Z-order in the node's parent: a number from 0 (the back) or front / back / forward / backward, in the same undo step as the other fields |
group_nodes / ungroup_nodes |
Wraps sibling nodes in a group (the drawing stays put) / puts them back |
align_nodes / distribute_nodes |
Aligns 2+ siblings to the selection box (edge: left center right top middle bottom) / spaces 3+ siblings with equal gaps (axis: horizontal vertical). One undo step each. Rotated nodes use the axis-aligned box. Refuses a row/column parent, connectors and copies inside an instance |
wrap_nodes |
Puts siblings in a new frame (transparent, clip: false). The drawing stays put. One undo step. Returns frame |
show_all / unlock_all |
Sets visible: true on every hidden node / clears locked. pageId limits the walk to that page; omit it for the whole document. Returns the ids that changed. No history entry when nothing changes |
combine_paths |
Boolean combine of 2+ sibling path / rect / ellipse / shape nodes into one path (operation: union, subtract, intersect, exclude). operations runs a sequence in one call instead ([{op, ids, as?}, ...]): a step's as name can be used in the ids of later steps, the last step is the result, and an error names the failing step (operations[1] (subtract): ...); use ids + operation or operations, not both. style picks the style the result keeps: bottom (default, lowest z-order), top, first or last (in order of appearance), or {from: id, fill?, gradient?, stroke?, opacity?, shadow?, outline?, filter?, backdropFilter?} to copy one node's style and override fields (fill without gradient drops the copied gradient). Deletes the sources, one undo step. Returns path (the new id). No canvas menu in this tool — agents use MCP / apply_ops |
normalize_paths |
One-shot repair for paths whose box does not hug their drawing (a d in frame coordinates under x: 0, y: 0: a selection box from the origin to the far edge, far larger than and offset from the ink). d moves to (0,0), x/y absorb the offset and width/height become the ink bounds; the drawing stays exactly where it was on the canvas, rotation included. Pass ids, or rootId for a subtree, or neither for the whole workspace. Skipped with a reason: paths with a viewBox, locked paths, copies inside an instance. One undo step. Returns {normalized: [{id, before, after}], unchanged, skipped, created, version} |
convert_to_path |
Turns rect or ellipse nodes into path nodes with the same id. Corner radius is baked into d. One undo step restores the originals. The canvas context menu does the same for the topmost rect or ellipse under the pointer |
duplicate_nodes |
Copies nodes with their whole subtree in one undo step. With no offset, place defaults to the right of the source (gap 80) so the copy does not land on it; pass offset to nudge x and y, or place "free" (past the page content) / "below" / "right" (beside the source, gap 80, like {near: source, side}) / {near, side} / "none". Also parentId, scale (sizes, text, strokes, spacing and instance scale) and props written on each copy ({ "mode": "dark" } makes the light/dark pair). Instances stay instances of the same component; connectors between duplicated nodes follow the copies. Returns copies (one id per source), map (every source node to its copy), and ids / roots / created in the same shape as create_nodes, plus one text line per root |
create_page |
Adds a page; the first one moves the current canvas into "Page 1" when the document has content (on an empty document only the new page is created). ensure: true with a name returns the existing page of that name instead of creating a second one |
round_path_corners |
Rounds the corners of a polygonal path (M L H V Z; curves are refused) with circular arcs, so you do not compute fillets by hand. d is a pure helper (returns the new d, writes nothing); id updates that path node in place (one undo step; the box hugs the new ink like any d update). radius rounds every vertex; radii is one radius per vertex in the order written (null or missing = radius, 0 = sharp). Each radius is clamped to half of the shorter adjacent edge; open ends stay sharp. Returns {d, bounds} |
create_shape_path |
One path node from a parametric shape: kind star (points, radius, innerRadius, angle, cornerRadius), polygon (sides, radius, angle, cornerRadius), ring (radius, thickness or innerRadius; one path with a hole, fillRule evenodd), arc (band: radius, thickness or innerRadius, startAngle, endAngle, roundCaps) and sector (wedge: radius, startAngle, endAngle). Angles are degrees clockwise from 12 o'clock. x/y are the shape's center; props takes fill, gradient, stroke, etc. (no fill/gradient/stroke = filled #000000). The result is a plain path (d, width and height are computed), so canvas, screenshot, export and the WASM renderer paint it as any path. Same result and place/parentId/index as create_nodes |
outline_stroke |
Turns a path's stroke into a filled shape of the same look, so it can be combined or scaled without the stroke. The node keeps its id: d becomes the outline (width, cap and join as painted, miter limit 4), fill takes the stroke color, stroke is removed (keepStroke: true leaves it), the box becomes the outline's and a rotation or viewBox is baked in. One undo step. Open and closed paths work (a closed path gives an outer and an inner contour). Curves are flattened first (0.05 px), so the result is a dense polyline (M L Z, fillRule nonzero), not refitted curves, and it is not boolean-cleaned (run combine_paths to merge it). Refused: a node that also has a fill or gradient (the outline is one paint), dashed or dotted strokes, non-path nodes. Returns {id, bounds} |
repeat_nodes |
Repeats one node (with its subtree) count times in one undo step: the source stays and count - 1 copies are made, in its parent. mode radial orbits center (default the parent frame's center) over angle degrees clockwise (default 360 = an even ring; a smaller sweep puts the first and last copy on its ends; box centers orbit, the pivot of rotation), rotate: true turns each copy with the orbit; linear puts copy k at k x step {x, y}; grid fills columns (optional rows) cells of the source's size plus gap. Radial and grid need a numeric width and height. Returns copies, plus ids, roots and created like create_nodes |
create_component / create_instance / detach_instance |
Marks a frame as a component (optional props: text, boolean, variant) / places a copy (scale, overrides, propValues, slots; returns each copy id, including slot/id and nested paths) / turns an instance into plain nodes (a bind on its copies is dropped: the resolved values are already there). A bind is checked when the transaction ends, so one create_nodes can carry the bound children and component: true on their frame together |
detach_tokens |
Replaces $name on the given nodes with the literal resolved in each node's theme mode. fields limits which fields; omit it to detach every token on the node. On an instance or one of its copies only the overrides it owns are detached (root fill, a copy's fill/color); fields that come from the component are skipped and listed under skipped instead of failing |
apply_ops |
Mixed transaction (create, update, delete, move, set_tokens, set_assets, rename_document, group, ungroup, add_page, detach, detach_tokens, combine_paths, align, distribute, wrap, reveal, convert_to_path, convert_to_frame, convert_to_shape) |
propose_tokens |
Reads CSS variables, a Tailwind theme (JS theme or v4 @theme) or JSON tokens (flat or DTCG $value / value) from content and returns set_tokens operations for the agent to apply. The source is the file text; a filesystem path is refused. CSS names drop the leading -- (--color-bg → color-bg; var(--color-bg) → $color-bg). Tailwind groups are dotted (colors.brand → color.brand, borderRadius.md → radius.md). Lengths in px become numbers. A selector or prefers-color-scheme that names a mode becomes mode on that proposal |
set_tokens |
Design tokens ($name). Optional type (color, length, fontFamily, fontWeight, fontSize, lineHeight, letterSpacing, shadow) is checked on set and on use; a shadow token is CSS box-shadow text ("0 4px 12px $ink, inset 0 1px 0 #fff", up to 8 layers) that a node uses whole with shadow: "$name"; omit it and the token stays an untyped string or number (a number still fits any length field). Optional collection names the group. A typed fontWeight or lineHeight is unitless in CSS variables; other numeric tokens stay px. With mode, the values of a theme mode (the override must match the token's type). export_code cssVariables: true writes var(--token) |
set_assets |
Document image assets ($name → http(s) or data:image/). An image src of $name must match one. null removes an asset. Export inlines the URL |
list_workspaces / open_workspace / create_workspace / import_document |
Lists the workspaces (documents) of the server / makes one active for every tool and the human's canvas / creates an empty one (no page yet: make the first with create_page {name, ensure: true}) / stores a .paprika.json (e.g. from paprika export --root ID) as a new workspace without switching the active one. Archived workspaces are omitted unless includeArchived is true; each row has archived, folderId (empty at the root) and preview (shapes for the live thumbnail). The same call lists folders. import_document keeps the file's coordinates (place "none"); use import_svg, import_html or import_image to place artwork on the current page |
rename_workspace / archive_workspace / unarchive_workspace / delete_workspace |
Renames a workspace (undoable when it is the active one) / hides one without deleting it (the active one hands over to the most recently updated other that is not archived; the only one cannot be archived; opening an archived one unarchives it) / puts an archived one back on the list without making it active / deletes one for good, in two calls: without confirmToken nothing is deleted and the result is a summary of what would be lost (counts, last edit, cover, which workspace takes over) plus a token that lasts about two minutes and belongs to that workspace; the second call with the token deletes (the active one hands over to the most recently updated other; the only one cannot be deleted) |
create_folder / rename_folder / move_workspace |
Creates an overview folder / renames one / moves a workspace into a folder (folderId null or empty puts it back at the root). None of them switches the canvas |
list_workspace_ops |
The workspace operations log — create, rename, open, archive, unarchive, delete and move, each with who acted (user or the agent's name), when and which workspace; a delete entry keeps the summary, and entries outlive the workspace they name |
release_nodes |
Ends the agent's presence at once: the canvas stops showing it on the nodes it last touched, the "N active" pill drops it and following it ends, instead of waiting for the 120 s presence timeout. Call it after the last write of a task; the next call shows the agent again. Returns released (false when there was nothing to clear). In team mode the release reaches the peers too |
list_pins / claim_pin / reply_pin / resolve_pin / update_pin / wait_for_pins |
Pins: requests the human leaves on the canvas with the Point for the AI tool (I), anchored to a node (nodeId, plus its box in region) or an area (region only), with pageId and the text. list_pins (status: open (default: open and claimed), claimed, resolved, all; optional pageId, workspaceId) returns them with rev; claim_pin {id} shows the agent's name and color on the pin (refused when another agent holds it); reply_pin {id, text} appends a message without closing the pin; resolve_pin {id, reply, nodeId?} closes it and stores that reply as an agent message on replies (the thread; reply stays the latest text); update_pin {id, nodeId} re-points an open or claimed pin to another node without resolving it (and resolve_pin does the same when given nodeId): use it after a redraw (delete + create) left the pin with nodeMissing; nodeId must exist in the pin's workspace and the pin's region and pageId follow that node's box (refused when another agent holds the pin); wait_for_pins {timeoutMs ≤ 60000, since} blocks until an open pin changes after since. Every write result that reports a version carries openPins: n (and one text line) while the workspace has open pins. Pins live in their own SQLite table: not nodes, not exported, not in the undo history. In team mode they sync through the Loro sidecar (pin and reply maps), not as canvas nodes |
set_workspace_cover |
Puts an image on a workspace's overview card: a screenshot of one of its frames (rootId), an image (image, base64 or data URL) or none (clear). Without a cover the card shows a live thumbnail of the page, or the first letter when the page has no shapes |
undo / redo / get_history |
History of one workspace, shared with the human when that workspace is the active one. Optional workspaceId undoes, redoes or reads that workspace only, without switching the canvas. Every write tool takes batch, so several calls with the same batch become one undo step. get_history also returns the redo stack (redo, last item is the next redo), canUndo / canRedo, and steps: the latest undo and redo steps as { kind, actor, at, label } (actor is user for the canvas or the agent name; label is the transaction it moved), stored in SQLite so they survive a restart. Use it to find who undid a write that vanished |
lint_design |
WCAG AA contrast (against the ancestors' fills and any rect, frame, image or rect/note shape painted below that holds the whole text; over an image or a gradient it is not measured), non-text-contrast (a border or stroke under 3:1 against what is behind it, WCAG 1.4.11, unless the fill already stands out), overflow, missing tokens, small text, alt text, layout-overflow (row/column children that leave the frame), hug-was-meant (a default 100×100 layout frame), grid-span-overflow (a grid child whose start + span reaches past the declared columns or rows), geometry (detached-sibling, near-gap under 4px, fully-hidden: only a frame, rect, image or rect/note shape can cover a sibling), overlapping-boards and covered-by-overlay. rootIds scopes the check to those subtrees. The result always has groups (not an argument): each rule folded to a count and the first maxIds ids (default 8), ordered by severity; issues lists every finding unless you pass issues: false, and ignoreRules: [rule, …] skips rules for that call. report: "contrast" adds contrast: every text and border pair it measured, passing ones too, with foreground, background, ratio, min and pass. minSeverity and minFontSize quiet the list; lintIgnore on a node and scaledMock on a frame drop intentional findings |
render_screenshot |
PNG of a node, a page or the whole canvas. A page (or the canvas) is painted on the page fill, white when there is none; any other root, a frame included, is on a transparent background and the PNG has an alpha channel. path writes it under <data>/screenshots (or PAPRIKA_SCREENSHOTS; a path outside that directory is refused) and returns {path, width, height, url} with url /api/screenshot/<id>, instead of the image. Without path the image is returned as before, plus url. mode paints a subtree in that theme mode; omitted, the subtree keeps the mode it inherits. compare (PNG, JPEG, GIF or WebP: data URL, raw base64 or a path under PAPRIKA_IMPORT_DIRS) is drawn to the right of the screenshot at the same height, with a gap; width and height are the combined image and compare is true. grid (true, or {step?, labels?, color?}) draws thin lines every step frame units (default 50, 100, 200 and so on, about 8 to 16 lines on the longer side) with coordinate labels and a ruler band on the top and left edges, in the root's own coordinates (0..width) and drawn on the PNG, not in the document; region {x, y, width, height} (frame units) crops to that part and scale applies to the region, so a small region with a large scale zooms in (the render is capped at 4096px per side before the crop). Both work with compare (they apply to the screenshot only) and with path; the result reports grid.step and region (clamped to the frame). To read a position, use region and grid instead of guessing from the image. A missing or mismatched browser returns pnpm --filter @paprika/e2e exec playwright install chromium, unless the server has the render sidecar paprika-render (the slim image, ADR 0012): then both renderers draw with it, the result has painter: "paprika-render" and warnings lists the nodes it does not draw yet. Optional workspaceId screenshots that workspace without switching the canvas renderer: "wasm" loads the real canvas in headless Chromium and captures the node as the WASM renderer paints it (the DOM layer plus the WASM layer, what a person with the WASM renderer sees; mode does not apply); it needs the web app and the WASM bundle on that server, and errors instead of falling back to dom (the default). |
export_image |
PNG, JPEG, WebP, AVIF, vector PDF or SVG (the same vector SVG as export_code with format: "svg", as a text block; scale does not apply) of a node/page/canvas. Raster formats go through the same Chromium path as render_screenshot, so they match it and the canvas; without a usable Chromium they fall back to rasterizing core ExportSVG in pure Go (embedded Inter) and warnings says so. PDF draws the ExportSVG geometry as vectors, with each color's alpha; a frame, rectangle or ellipse with a shadow, filter, backdropFilter or gradient is placed as an image of that node drawn by the Go compositor at twice the scale (its children and all text stay vectors). Background as in render_screenshot: a root that is not a page is transparent (PNG/WebP/AVIF keep the alpha, JPEG is flattened onto white). The Chromium raster path caps each output side at 4096px: when scale would exceed it the scale is lowered, warnings says so, and the result reports the scale actually used next to width and height. Optional workspaceId exports that workspace without switching the canvas |
import_svg / import_html |
Turns pasted SVG (paths, shapes, groups, transforms, <text> as text nodes, <use>/<symbol> sprites) or HTML with inline styles into editable nodes; images, gradients, masks and <style> come back in warnings. import_html computed: true renders the HTML in the server's Chromium and inlines computed author styles before import; if Chromium is missing the call fails with how to install it and does not fall back. The result includes ids, roots and created in the same shape as create_nodes, plus one text line per root. Roots honor place ("free" when x and y are omitted; "none" with x/y inside a row/column frame sets layoutPositioning: "absolute" on the roots and warns). Optional workspaceId imports into that workspace without switching the canvas |
import_image |
Places a raster image (PNG, JPEG, WebP, AVIF or GIF) as an image node sized from the file. src is a data URL or a local path under PAPRIKA_IMPORT_DIRS (default: the server's working directory). Files over 3500000 bytes are refused. A .fig file and a PDF are refused: export SVG and use import_svg, or place one of the raster formats. Original bytes are kept, so animated GIF/WebP/AVIF stay animated on the canvas and in HTML exports (render_screenshot captures one frame). Inside a row/column frame, place: "none" with x/y sets layoutPositioning: "absolute" on the image and warns. Returns ids, roots and created in the same shape as create_nodes, plus one text line per root. Honors place ("free" when x and y are omitted). Optional workspaceId imports into that workspace without switching the canvas crop {x,y,width,height} (source pixels, after the JPEG rotation) keeps only that part of the image before it is stored, to place one region of a photo as its own image: PNG stays PNG, JPEG is re-encoded at quality 95, GIF and WebP come out as PNG (an animation keeps its first frame), AVIF is refused; the cropped file must still fit in 3500000 bytes. A rectangle partly outside the image is clamped (warnings says so), one fully outside is an error. naturalWidth, naturalHeight, width, height and x/y/width placement all refer to the cropped image |
place_reference |
Places that same kind of image as a locked layer at the back of a frame (frameId), fitted inside it, at 50% opacity unless opacity is set. It stays on the image paint path (locked, opacity, layoutPositioning: absolute). name defaults to Reference crop {x,y,width,height} (source pixels) keeps only that part of the image, exactly as in import_image; the cropped image is the one fitted inside the frame |
resize_image |
Resamples an image node (or creates one from src) to qhd 960×540, hd 1280×720, 2k 2560×1440, 4k 3840×2160, or {width,height}. Pure Go (golang.org/x/image CatmullRom); no Chromium. fit: contain (default), cover, fill. Animated GIF → first frame; animated WebP and AVIF refused. Same format when encodable in pure Go (PNG/JPEG/GIF), else PNG |
analyze_image |
Measures a reference image before you redraw it, in pure Go (no Chromium, about 50 ms for 1200×900). src (data URL, raw base64 or a path under PAPRIKA_IMPORT_DIRS; PNG, JPEG, GIF, WebP; AVIF refused) or nodeId (an image node). Returns the size, the background (from the borders), a palette of dominant colors (maxColors, default 8; perceptual k-means in OKLab, anti-aliasing removed) and blobs: connected regions of one palette color, largest first (minArea default 0.05%, maxBlobs default 40 with truncated). Each blob has bbox, centroid, areaPx, share, holes, orientation, elongation, mirror symmetry and fit: the best of circle, ellipse (rotation), rect/roundRect (radius), regular polygon (sides, rotation) or freeform (simplified outline, up to maxPoints), with its iou, a simplicity (always one node, plus how many numbers describe it) and a node ready for create_nodes: a roundRect whose corners differ has radius [tl, tr, br, bl], a regular polygon with rounded corners (cornerRadius) comes as the path create_shape_path would draw. regions split the image into rectangles that cover it without overlapping, each with a kind and the tool that draws it best (suggest): photo (grain, measured at up to 1600 px, not at the 640 px analysis size that would blur it away: more than 35% of the pixels differ from a blurred copy by over 3 levels and the 6 commonest of the tile's 64 median-cut colors cover under 55% of it, with weaker tiles next to a photo joining it; crop it, import_image or place_reference; tracing posterizes it; a large smooth colour field that no linear or radial ramp explains, such as a silk or mesh background, is also photo, as one region over its bounding box, and the sharp shapes on it keep their own suggest), gradient (a smooth ramp: one shape with the region's gradient {type, angle, stops} or radial {cx, cy, radius, stops}, ready for the node field, and a fitError in color levels; ramps that follow the same direction or center merge into one region that runs under the shapes sitting on it, those shapes keep their own suggest, and a ramp that fits poorly is only reported when it is large, with suggest trace_image), text (rows of small blobs of similar height on a baseline: text nodes, with the box, an estimated fontSize and lines; no OCR) and flat (the rest: primitive when most blobs fit a primitive at iou 0.93 or more, else trace_image). Each region lists its blobIds; each blob says suggest (primitive, trace_image, text, skip-in-photo, skip-in-gradient) and its region; only the 8 largest blobs of a grainy photo are listed. Flat tiles and tiles that change colour never join one smooth group, so a glow stops where the white around it begins. Choosing tools for a reference: do not trace everything, mix the tools per region in one frame, then check with compare_reference and prefer fewer, simpler nodes at equal iou. layout lists repeats, grids (rows, cols, pitch, gap) and radials (center, radius, step angle). frame {width,height} gives coordinates in that frame (image fitted and centered like place_reference); region analyzes a rectangle. Deterministic; the text content is a compact summary, structuredContent has everything |
trace_image |
Turns a reference image into editable vector paths, in pure Go (no Chromium): use it to start from the real contours of an organic shape (a wing, a monogram, a whale) and refine, instead of rebuilding them by hand. Same inputs as analyze_image (src or nodeId, region, maxColors, minArea) plus parentId (the frame to draw into; the image is fitted inside it and centered like place_reference; frame overrides the fit box). Creates ONE path per palette-color blob, fill = the blob color, largest silhouette first so nested shapes land on top; the outer contour and the holes are subpaths with fillRule: "evenodd", as cubic beziers: corners (turning angle >= smoothness, default 50 degrees) stay sharp, the rest is fitted to within tolerance px (default 1). A hole another traced blob fills is closed, one that shows the background stays open. The background color is skipped unless includeBackground (set the frame's fill to background.color); colors traces a palette subset; group (default true) wraps the paths in a group; maxPaths (default 60) caps the count with truncated. Nodes are created like create_nodes (normalize: true, one undo step, batch, place): returns ids, roots, created, per-path stats (points, segments, curves, lines, corners, error), nodeCount. dryRun: true returns each path's d and the stats without writing. Deterministic. To mix tools per region of one reference: blobIds (ids from analyze_image with the same src/nodeId, region, maxColors and minArea: both tools share one segmentation and number blobs the same way) traces only those blobs (colors and includeBackground are ignored; an unknown id is a warning), and exclude ([{x,y,width,height}] in the coordinates the paths come out in, 1 px of slack) skips the blobs whose box lies inside any of them, for example the regions you placed as images with import_image crop. skipped counts them (excluded, notListed, plus slivers) and every path carries its blobId. When more than maxPaths blobs are found the most important ones are kept (area times contrast against the background, so small high-contrast text outlives a large faint area), still drawn largest silhouette first; drawn, dropped and droppedIds (blob ids, to retrace with blobIds or a higher maxPaths) report the cut apart from pathCount. Edge fidelity: segmentation and blob ids stay at the analyze_image size (640 px on the longest side), but each contour is read from the source at up to 2000 px: every source pixel is given back to the blob it belongs to by color, an anti-aliased pixel between two colors counts in proportion to both, and the outline is the 0.5 level of that soft field, so edges sit between pixels, straight sides stay straight and small letters keep their corners when the canvas is zoomed. Anti-aliasing rims between two colors (thin blobs colored like a mix of the shapes on both sides) keep their blobId in analyze_image but are not traced (skipped.slivers): the shapes on both sides take their pixels. A shape drawn under another reaches about 1 px beneath it where they touch, so no background hairline shows between neighbours |
compare_reference |
Scores a drawing against its reference with numbers, after you draw from a picture. rootId is the frame; reference is a data URL, raw base64, a path under PAPRIKA_IMPORT_DIRS, SVG markup or the id of an image node; an SVG (markup, data:image/svg+xml or a .svg path) is rasterized at about twice the frame size, without its text or filters (a warning says so) (for instance the layer place_reference added: it is left out of the render). The frame is rendered like render_screenshot (mode, scale) and the reference is fitted to it like place_reference. Scores leave the background out: each image becomes an ink mask (pixels that differ from its own background; transparent PNGs count by alpha). The background is modelled per image: a flat color when the border is uniform, otherwise a smooth surface (a 12-by-12 grid of OKLab medians, interpolated) fitted on the pixels reachable from the border without crossing an edge, so ink is the distance from the background at that pixel, not from one border color (a sheet of solid-color tiles, a border that is mostly subject, or a background that covers under a third of the image stays flat); a gradient or vignette no longer counts as ink, on either side. background reports reference and drawn (hex; the mean of a gradient) plus referenceModel and drawnModel `{kind: flat |
fit_to_reference |
Tunes the numbers of nodes you already drew so the frame matches its reference: draw the structure, then this, then compare_reference. rootId is the frame, ids the nodes to tune (inside it; rect, ellipse, path and frame), reference as in compare_reference. params (default position and size): position, size, rotation (degrees, kept in -180..180), radius (rect and frame corners) and pathPoints (anchors of a path, handles moving with them; only the maxAnchors, default 8, with the largest local error move; paths with a viewBox are not edited). It maximizes the ink IoU of the frame against the reference (the masks of compare_reference; colors stay as they are) by coordinate descent with a shrinking step, nodes with the most error first, up to maxIterations rounds (default 60) or until the mask reaches target (default 0.99). The frame is rendered with Chromium once as it is and once with the tuned nodes left out; the tuned nodes are rasterized in software (rects, rounded rects, ellipses, paths with fill rule, strokes, rotation, group and frame offsets) on that mask, so no screenshot is taken per try (about 20 nodes in under 5 s). Numbers are snapped to whole or half units when that costs nothing. It writes one update_nodes transaction (one undo step; batch and label honored) unless dryRun, and only when the Chromium render of the new numbers is not worse than before. Nodes in a row/column layout keep their position, hug/fill sizes are not tuned, and locked, hidden, text and other node types are skipped with a reason. Returns per node changes (before/after) and pathPoints moved, iou.mask and iou.chromium (before/after; a gap over 0.03 is a warning: text, shadows, gradients and overlapping paint are not modeled), applied, pass (Chromium IoU after >= target), iterations and the time. Deterministic; needs Chromium |
export_code |
Standalone HTML, a React (TSX) component, vector SVG (boxes from core layout(doc), no headless Chromium), a React component with Tailwind utility classes (tailwind), standalone HTML with Tailwind classes (tailwind-html), a React component plus its .module.css (css-modules: two text blocks, the .tsx first and the stylesheet second), an Angular standalone component (angular: three text blocks — .ts, template, .css) or a Svelte single-file component (svelte); cssVariables: true writes tokens as var(--name) with one rule per theme mode |
The convert_to_frame and convert_to_shape operations (through apply_ops, no dedicated tool): {op: "convert_to_frame", id, adopt?: [ids]} turns a rect, an ellipse of any proportions or a path into a frame that keeps its id, parent, order, rotation, place in an auto-layout flow and every visual field, and sets clip: true. An ellipse gets contour: "ellipse". A path gets contour: "path" and a contourPath built from its d, viewBox, fillRule, strokeCap and strokeJoin: with no viewBox the box is used, and when the box proportions differ from the viewBox it is widened so the centered drawing stays where it was; its stroke becomes center (outside on a filled path, as the path drew it) and is scaled to px, and a token stroke width that the viewBox would scale is refused. adopt moves those siblings (same parent, not connectors, not instance copies) into the frame, converting their x and y so nothing moves; it is refused when the shape is rotated or its parent has an auto layout. A copy inside an instance is refused with a message to edit the component. {op: "convert_to_shape", id, shape: "rect" | "ellipse" | "path", radius?, props?} is the inverse and only accepts a plain frame (no children, layout, clip: false or other frame-only field) whose contour matches shape; radius sets the ellipse radius, and props sets shape fields afterwards (null removes one), which undo uses to restore a path exactly. The canvas uses both in one undo step with the centering.
create_nodes (and the create operation) also takes children on a rect, ellipse or path: the node is created as a frame with the matching contour, converted as above. The result lists each one under converted ({id, from, contour}) and adds a line to warnings, so the agent needs no separate conversion step.
Agent layer:
- Arguments are strict: an unknown top-level argument (
render_screenshot {id},lint_design {ids}) is an error that lists the valid arguments and suggests the likely one (rootId,rootIds), instead of being dropped and acting on the whole canvas. Every tool'sinputSchemasaysadditionalProperties: false. - The guide, tool descriptions, errors, warnings and lint messages are in English (the guide also in pt-BR, see above).
- Tools that answer JSON declare an
outputSchemaand returnstructuredContent; the text block keeps the same JSON (forget_nodesandget_history, the plain array (get_historyaddsredo,steps,canUndoandcanRedoonly tostructuredContent); foranalyze_image,compare_referenceandfit_to_reference, a compact summary).create_nodes,duplicate_nodesand the import tools also add one readable line per root. - Document tools take an optional
workspaceId(outline, nodes, bounds, create/update/delete/move/group, tokens, lint, screenshot, export, imports, undo/redo and the other document writes). Omit it to use the active workspace, which is the human's canvas. Passing it reads or writes that workspace withoutopen_workspaceand without moving the canvas. The outline's first line and every write result includeworkspaceIdandworkspaceName. Every write result also carrieschanges{tokens,nodes,pages,assets}, and the outline's second line ischanges: tokens=… nodes=… pages=… assets=…with the same values. Each one is a 16-character hash of that part of the document (tokens covers tokens, modes and token metadata; pages covers the page list, order, names and page fields other than children; nodes covers every node), so it stays the same while that part does not change, also across restarts and after an undo that brings the content back. An agent compares them with the last ones it saw and re-reads only the part whose token moved. Each workspace keeps its own history for the life of the process. An unknown id is an error that lists the workspaces. - The history names the agent after its MCP
clientInfo.name(agent:claude-code). Over HTTP the server is stateless, soinitializehands out anMcp-Session-Idthat only carries that name; without it, the User-Agent is used as before. - Both protocol eras are served on the same
/mcpendpoint and on stdio:- 2026-07-28 (stateless): no
initializeand no session. Each request carries_metawithio.modelcontextprotocol/protocolVersionandio.modelcontextprotocol/clientCapabilities(andclientInfo, whosenamenames the agent in the history). Over HTTP it also needsMCP-Protocol-Version,Mcp-Methodand, ontools/call,Mcp-Name(plain or=?base64?…?=); a header that is missing or disagrees with the body is-32020(HTTP 400). Methods:server/discover,tools/listandtools/call; every result hasresultType: "complete"andserverInfoin_meta, andserver/discoverandtools/listaddttlMs(one hour) andcacheScope: "public".pingis not part of this era (-32601, HTTP 404). - 2025-11-25 down to 2024-11-05 (with
initialize): unchanged, except that a JSON-RPC batch is refused when the request has anMCP-Protocol-Versionheader (batches left the spec in 2025-06-18; a 2025-03-26 client sends no such header and still may batch). - An unsupported version, in
_metaor in the header, is-32022(HTTP 400) withdata.supportedanddata.requested. An unknown tool is a protocol error,-32602Unknown tool: <name>, in both eras. The server announcescapabilities.toolswithoutlistChanged, since the tool list never changes while it runs.
- 2026-07-28 (stateless): no
- The open canvas reports how it paints on the WebSocket:
{type:"hello", renderer:"wasm"|"dom"}, again when the human toggles the renderer. The server answers with the same hello.get_document_outlinelists one value per connected tab, ornonewhen no tab is connected. Screenshots stay on the HTML path.
#Document format
{
"format": "paprika/1",
"name": "Demo",
"tokens": { "brand": "#c43d27", "text.md": 16 },
"rootIds": ["login"],
"nodes": {
"login": { "type": "frame", "id": "login", "parentId": null, "width": 390, "height": 760,
"layout": { "mode": "column", "gap": 20, "padding": 24 }, "children": ["t1"] },
"t1": { "type": "text", "id": "t1", "parentId": "login", "text": "Hello", "color": "$brand",
"width": "fill", "height": "hug" }
}
}Types: frame (container with paint and free, row, column or grid layout), group (wraps nodes without painting; its box follows the children), frame with component: true (a component) or instanceOf (an instance: its children are generated copies of the component, scaled by scale, with overrides), page (a separate canvas in the file; once a document has pages, every top-level node is a page and the frames live inside them), rect, ellipse, text, image, path (vector shape from SVG path data: lines, cubic and quadratic bezier curves, arcs; fill, stroke, fillRule, strokeCap, strokeJoin, optional viewBox to scale an icon grid; stroke width is in viewBox units and scales with the box; d has at most 200 000 characters and 10 000 segments).
A text node may set runs: up to 200 ranges { start, end } in UTF-16 indexes, sorted and not overlapping (touching is fine). Each run needs at least one of fontWeight (100–900 or $token), color, fontSize (number or $token), italic: true, or href (http(s), mailto, or a path starting with / or #). create_nodes and update_nodes carry runs; null on update clears them. HTML, React, SVG, PNG and PDF export keep the ranges. A copy inside an instance may override runs along with fill, color, text, src, alt, visible and opacity.
stroke is { color, width, style?, position? } with style solid|dashed|dotted (dash pattern from width; omit = solid) and position inside|center|outside (omit = inside for boxes/shapes, center for paths).
gradient is optional on frame, rect, ellipse, text, image, path, shape and page: { type: "linear"|"radial"|"conic", angle?, cx?, cy?, radius?, stops }. stops is 2 to 12 { color, offset } with offset in 0..1. Omitted angle is 180 (CSS: 0 is up, 90 is right), cx/cy are 0.5 and radius is 0.5 (0..2). When gradient is set it wins over fill. null on update removes it. A CSS gradient or url() string in fill or any color is refused on create/update (it painted black on paths): the error points to gradient, e.g. { type: "linear", angle: 90, stops: [{ color: "#fff", offset: 0 }, { color: "#000", offset: 1 }] }.
On frame, rect and image, radius is one length or [tl, tr, br, bl] (top-left, top-right, bottom-right, bottom-left). Each corner is a number or a $token, same as gap and padding. One value keeps the corners linked; the inspector toggles that link. Other nodes keep a single radius.
Sizes: a number, "hug" (fit content) or "fill" (take the parent's space); width/height do not take $tokens (tokens work for padding, gap, radius, stroke width...). layout.padding is one value, [vertical, horizontal] or [top, right, bottom, left] (CSS order; two values are stored as four); other lengths are refused with the accepted shapes. lineHeight is a multiplier of fontSize (1.4), not pixels: for a 22px line on 16px text use 1.375; values above 10 are refused with that hint. A child of a row/column frame can set layoutPositioning to "absolute" (omit or "auto" stays in the flow): it keeps x/y relative to the parent and is skipped by the flow, the gap and hug sizing. A child that stays in the flow can set layoutGrow (a number >= 0, omit = 0), flex-grow: it keeps its own main-axis size and takes a share of the free space left on that axis, split by weight (weights summing below 1 take only that fraction; a "fill" child on that axis ignores it; a hug parent has no free space). A child with layoutGrow: 1 (a 0-wide spacer works) pushes the siblings after it to the end. create_nodes and update_nodes accept the field; null on update removes it. A child outside the flow can set constraints to { horizontal: left|right|center|scale, vertical: top|bottom|center|scale } (omit = left and top). When the parent frame's width or height changes (a numeric size, or the laid-out size of a fill/hug frame, so a resized ancestor reaches nested fill frames), those children keep the left/top edge, the right/bottom margin, the center, or scale with the parent. In-flow children ignore the field. null on update removes it. Details in docs/en-US/architecture.md. Planned work lives in docs/en-US/backlog.md.
A frame with layout.mode: "grid" lays its children out as CSS Grid (ADR 0011). columns (required) and rows are lists of 1 to 24 tracks: a px number, a length $token, "<n>fr" (exported as minmax(0, <n>fr)) or "hug" (CSS auto). Left out, rows adds one "hug" row per line of children. columnGap and rowGap fall back to gap. A child takes gridColumn and gridRow { start?, span? } (start is a 1-based line); without start it goes to the next free cell, row by row (CSS grid-auto-flow: row, not dense), and a span past the last column adds "hug" columns as CSS does. width/height "fill" stretch the child over its cell; a number keeps that size and align places it in the cell; justify places the whole grid when the tracks leave room. layoutGrow and wrap do not apply. get_bounds and the SVG, PNG and PDF exports compute the same boxes as the browser; the Tailwind export writes grid-cols-[…], col-start-… and col-span-….