# Brief to deck pdf intake Source: https://docs.moda.app/.mintlify/skills/moda-api/recipes/brief-to-deck-pdf-intake # Brief-to-deck (PDF intake) **Problem:** A user uploads a brief PDF to your app. You want to produce a branded pitch deck from it and return a PPTX download URL. ## Primitives * `POST /v1/uploads` — upload the PDF (multipart) * `POST /v1/tasks` with `attachments: [{file_id, role: "source"}]` + `brand_kit_id` + `number_of_slides` * Webhook OR polling to detect completion * `POST /v1/canvases/{id}/export?format=pptx` — signed URL inline, or a `task_id` to poll ## TypeScript (Node 20+) ```ts theme={null} // server/api/generate-deck.ts import { FastifyInstance } from "fastify"; import fs from "node:fs"; const HEADERS = { Authorization: `Bearer ${process.env.MODA_API_KEY!}`, "Moda-Version": "2026-05-01", }; export default async function (app: FastifyInstance) { app.post("/generate-deck", async (req, reply) => { const { pdfPath, userId } = (await req.body) as { pdfPath: string; userId: string }; // 1. upload the brief const form = new FormData(); form.set("file", new Blob([fs.readFileSync(pdfPath)]), "brief.pdf"); const uploadRes = await fetch("https://api.moda.app/v1/uploads", { method: "POST", headers: { Authorization: HEADERS.Authorization, "Moda-Version": HEADERS["Moda-Version"] }, body: form, }); const brief = await uploadRes.json(); // { id: "file_...", ... } // 2. find default brand kit const kits = await fetch("https://api.moda.app/v1/brand-kits", { headers: HEADERS }).then(r => r.json()); const kit = kits.data.find((k: any) => k.is_default); // 3. start the design task const task = await fetch("https://api.moda.app/v1/tasks", { method: "POST", headers: { ...HEADERS, "Content-Type": "application/json" }, body: JSON.stringify({ prompt: "Build a pitch deck from the attached brief. Use our brand styling. " + "Prioritize real data and quotes from the brief; do not invent specifics.", format: { category: "slides", width: 1920, height: 1080 }, number_of_slides: 10, brand_kit_id: kit?.id, attachments: [ { file_id: brief.id, role: "source", label: "Brief" }, ], callback_url: "https://myapp.com/webhooks/moda", idempotency_key: `deck:${userId}:${brief.id}`, }), }).then(r => r.json()); reply.send({ message: "Generating deck — takes 2–10 minutes. You'll get a notification when it's ready.", task_id: task.id, canvas_url: task.links?.canvas ?? null, // useful placeholder while it cooks }); }); } ``` Webhook handler (abbreviated — full handler in [`webhook-receiver.md`](./webhook-receiver.md)): ```ts theme={null} async function handleAsync(event: any) { if (event.type !== "task.succeeded") return; const canvas_id = event.data.result.canvas_id; // 4. export — completed inline, or an in-progress handle to poll let exp = await fetch( `https://api.moda.app/v1/canvases/${canvas_id}/export?format=pptx`, { method: "POST", headers: HEADERS }, ).then(r => r.json()); if (exp.status === "in_progress") { const taskId = exp.task_id; do { await new Promise(r => setTimeout(r, (exp.retry_after_seconds ?? 5) * 1000)); exp = await fetch( `https://api.moda.app/v1/canvases/${canvas_id}/export-status?task_id=${taskId}`, { headers: HEADERS }, ).then(r => r.json()); } while (exp.is_terminal === false); } if (exp.status !== "completed") { // retryable: a fresh export can still succeed — requeue instead of telling the user it failed. if (exp.retryable) return void scheduleExportRetry(canvas_id, event.id); await notifyUser(eventIdToUserId(event.id), `Deck export failed: ${exp.error ?? "unknown error"}`); return; } // exp.url — signed URL valid 7 days await notifyUser( eventIdToUserId(event.id), `Your deck is ready: ${event.data.result.canvas_url}\nPPTX: ${exp.url}`, ); } ``` ## Python (FastAPI + httpx) ```python theme={null} # server/api/generate_deck.py import os, httpx from fastapi import APIRouter, UploadFile, File, Form router = APIRouter() HEADERS = { "Authorization": f"Bearer {os.environ['MODA_API_KEY']}", "Moda-Version": "2026-05-01", } @router.post("/generate-deck") async def generate_deck( file: UploadFile = File(...), user_id: str = Form(...), ): async with httpx.AsyncClient( base_url="https://api.moda.app/v1", headers=HEADERS, timeout=60, ) as c: # 1. upload content = await file.read() brief = (await c.post( "/uploads", files={"file": (file.filename, content, file.content_type)}, )).json() # 2. default brand kit kits = (await c.get("/brand-kits")).json() kit_id = next((k["id"] for k in kits["data"] if k["is_default"]), None) # 3. start task task = (await c.post("/tasks", json={ "prompt": ( "Build a pitch deck from the attached brief. Use our brand styling. " "Prioritize real data and quotes from the brief; do not invent specifics." ), "format": {"category": "slides", "width": 1920, "height": 1080}, "number_of_slides": 10, "brand_kit_id": kit_id, "attachments": [ {"file_id": brief["id"], "role": "source", "label": "Brief"}, ], "callback_url": "https://myapp.com/webhooks/moda", "idempotency_key": f"deck:{user_id}:{brief['id']}", })).json() return { "message": "Generating deck — takes 2–10 minutes.", "task_id": task["id"], } ``` Webhook handler does the export: ```python theme={null} import asyncio, json @app.post("/webhooks/moda") async def moda_webhook(...): # ... verify signature (see webhook-receiver.md) ... event = json.loads(body) if event["type"] == "task.succeeded": canvas_id = event["data"]["result"]["canvas_id"] async with httpx.AsyncClient(base_url="https://api.moda.app/v1", headers=HEADERS) as c: exp = (await c.post( f"/canvases/{canvas_id}/export", params={"format": "pptx"}, )).json() if exp.get("status") == "in_progress": # slow render; poll it out task_id = exp["task_id"] while exp.get("is_terminal") is not True: await asyncio.sleep(exp.get("retry_after_seconds") or 5) exp = (await c.get( f"/canvases/{canvas_id}/export-status", params={"task_id": task_id}, )).json() if exp.get("status") != "completed": # .get: an error envelope has no "status" if exp.get("retryable"): # transient — requeue out of band await schedule_export_retry(canvas_id, event["id"]) else: await notify_export_failure(user_for_event(event["id"]), exp.get("error")) return {"ok": True} # ack either way — never make Moda retry the webhook await notify_user(user_for_event(event["id"]), canvas_url=event["data"]["result"]["canvas_url"], pptx_url=exp["url"]) return {"ok": True} ``` ## Gotchas * **`idempotency_key` encoding.** Using `{user_id}:{file_id}` means re-uploading the same PDF for the same user hits the same task (desirable — idempotent, no wasted compute). If you want a fresh task each time, include a timestamp. * **Brief → `role: "source"`.** The agent extracts content. Passing it as `reference` would make the deck mimic the PDF's formatting — not what you want. * **`number_of_slides` is a hint, not a hard cap.** If the brief is thin, the agent may produce fewer; if it's rich, marginally more. * **Don't tell the user a retryable export failed.** The poll response's `retryable` separates a transient fault (requeue it) from a terminal one (the canvas content has to change). Acknowledge the webhook in both cases — retrying the *webhook* never fixes an export. * **Export has two response shapes.** `{status: "completed", url}` when the render lands inside the \~20s wait budget, `{status: "in_progress", task_id}` when it doesn't — then poll `/canvases/{id}/export-status`. A ten-slide PPTX usually completes inline; don't rely on it. * **You may not need the export call at all.** A programmatic design task auto-exports its result, and `task.succeeded` carries it at `data.result.export` (`{status, url, format, page_count}`) in the canvas's category-default format. Read that when PPTX is the category default. * **Signed PPTX URL expires after 7 days.** Either surface it directly to the user (they'll click within minutes usually) or download + re-host yourself. * **`callback_url` requires API-key auth.** This recipe runs server-side so that's fine. An OAuth / MCP caller can't set `callback_url` — they'd have to poll. * **If `brand_kit_id` is null** (empty team), the design task still runs but without brand styling — or you can error out. Decide based on UX: for internal tools, off-brand is fine; for customer-facing, force the user to set up a brand kit first. ## See also * [`../references/uploads.md`](../references/uploads.md) — multipart upload details * [`../references/idempotency.md`](../references/idempotency.md) — key design * [`../references/canvases-and-exports.md`](../references/canvases-and-exports.md) — export semantics * [`webhook-receiver.md`](./webhook-receiver.md) — production-grade handler * [`scheduled-generation.md`](./scheduled-generation.md) — cron-driven variant # Bulk personalization Source: https://docs.moda.app/.mintlify/skills/moda-api/recipes/bulk-personalization # Bulk personalization **Problem:** You have a CSV of 50 prospects. Produce one personalized follow-up deck per prospect, using an uploaded brief as the content source and the team's default brand kit. Collect the canvas URLs when they're done. ## Primitives * `POST /v1/uploads` — upload the shared brief (once) * `POST /v1/tasks` — fan out one task per prospect with `idempotency_key` * `callback_url` webhook — receive terminal state per task (preferred) OR polling pool (fallback) ## TypeScript (Node 20+, `fetch`) ```ts theme={null} import fs from "node:fs"; import Papa from "papaparse"; const HEADERS = { Authorization: `Bearer ${process.env.MODA_API_KEY!}`, "Moda-Version": "2026-05-01", "Content-Type": "application/json", }; const CALLBACK_URL = "https://myapp.com/webhooks/moda"; // 1. upload the brief once const briefForm = new FormData(); briefForm.set("file", new Blob([fs.readFileSync("brief.pdf")]), "brief.pdf"); const brief = await fetch("https://api.moda.app/v1/uploads", { method: "POST", headers: { Authorization: HEADERS.Authorization, "Moda-Version": HEADERS["Moda-Version"] }, body: briefForm, }).then(r => r.json()); // brief.id = "file_01HT9..." // 2. fan out — one task per prospect const csv = Papa.parse(fs.readFileSync("prospects.csv", "utf8"), { header: true }); const kits = await fetch("https://api.moda.app/v1/brand-kits", { headers: HEADERS }).then(r => r.json()); const defaultKit = kits.data.find((k: any) => k.is_default); const results: { prospect: string; task_id: string }[] = []; for (const row of csv.data as any[]) { const res = await fetch("https://api.moda.app/v1/tasks", { method: "POST", headers: HEADERS, body: JSON.stringify({ prompt: `Personalized follow-up deck for ${row.company}. Prospect: ${row.contact_name}, ${row.contact_role}. Their focus area: ${row.focus_area}. Use the attached brief as the source of truth for our product claims.`, format: { category: "slides", width: 1920, height: 1080 }, number_of_slides: 8, brand_kit_id: defaultKit?.id, attachments: [ { file_id: brief.id, role: "source", label: "Master brief" }, ], callback_url: CALLBACK_URL, idempotency_key: `prospect-deck:${row.id}`, // stable per prospect }), }); if (res.status === 429) { // rate limited — respect Retry-After and retry this prospect const waitSec = Number(res.headers.get("Retry-After") ?? 10); await new Promise(r => setTimeout(r, waitSec * 1000)); // simpler: push back onto the queue; full rate-limit handling left as an exercise } const task = await res.json(); results.push({ prospect: row.company, task_id: task.id }); } fs.writeFileSync("tasks.json", JSON.stringify(results, null, 2)); console.log(`Queued ${results.length} tasks. Webhook will deliver results.`); ``` Webhook handler (same shape as [`webhook-receiver.md`](./webhook-receiver.md)) looks up `event.data.id` in `tasks.json`, matches it to a prospect, writes the canvas URL to a CRM / database / Slack. ## Python (`httpx`) ```python theme={null} import csv, os, httpx HEADERS = { "Authorization": f"Bearer {os.environ['MODA_API_KEY']}", "Moda-Version": "2026-05-01", } with httpx.Client(base_url="https://api.moda.app/v1", headers=HEADERS, timeout=60) as c: # 1. upload shared brief with open("brief.pdf", "rb") as f: brief = c.post( "/uploads", files={"file": ("brief.pdf", f, "application/pdf")}, ).json() # 2. find default brand kit kits = c.get("/brand-kits").json() default_kit_id = next( (k["id"] for k in kits["data"] if k["is_default"]), None, ) # 3. fan out results = [] with open("prospects.csv") as f: for row in csv.DictReader(f): resp = c.post("/tasks", json={ "prompt": ( f"Personalized follow-up deck for {row['company']}.\n" f"Prospect: {row['contact_name']}, {row['contact_role']}.\n" f"Their focus area: {row['focus_area']}.\n" "Use the attached brief as the source of truth for our product claims." ), "format": {"category": "slides", "width": 1920, "height": 1080}, "number_of_slides": 8, "brand_kit_id": default_kit_id, "attachments": [ {"file_id": brief["id"], "role": "source", "label": "Master brief"}, ], "callback_url": "https://myapp.com/webhooks/moda", "idempotency_key": f"prospect-deck:{row['id']}", }) if resp.status_code == 429: # respect Retry-After then re-queue this prospect (omitted for brevity) continue task = resp.json() results.append({"prospect": row["company"], "task_id": task["id"]}) # store task_id → prospect mapping for the webhook handler to look up with open("tasks.json", "w") as f: import json json.dump(results, f, indent=2) ``` ## Polling fallback (no webhook server) If you can't run a webhook receiver, poll all 50 tasks in a concurrency-capped pool instead: ```python theme={null} import asyncio, time async def poll(c: httpx.AsyncClient, task_id: str): while True: t = (await c.get(f"/tasks/{task_id}")).json() if t["status"] in {"succeeded", "failed", "canceled", "expired"}: return t await asyncio.sleep((t.get("retry_after_ms") or 3000) / 1000) async def main(task_ids: list[str]): sem = asyncio.Semaphore(8) # cap parallelism async def guarded(tid): async with sem: return await poll(c, tid) async with httpx.AsyncClient(base_url="https://api.moda.app/v1", headers=HEADERS) as c: return await asyncio.gather(*(guarded(t) for t in task_ids)) ``` ## Gotchas * **`idempotency_key` per prospect + run.** `"prospect-deck:{id}"` works if each prospect only gets one deck per logical run. If you re-run monthly, include the month: `"prospect-deck:{id}:2026-04"`. * **Rate limits are real.** If you fan out 50 tasks in a tight loop, you may hit a per-key or per-team cap. Back off on `429` using `Retry-After`. Serialize if recurring. * **`brand_kit_id` is the team default** by default (so you can technically omit it). Passing it explicitly makes the code's intent clear and future-proofs it if the team adds more kits. * **Don't poll AND have a webhook.** Pick one. Doubling up wastes your rate budget and may trigger two Slack pings. * **On task failure**, you need a way to surface which prospect failed. The `idempotency_key` or the mapping file is your link. ## See also * [`../references/idempotency.md`](../references/idempotency.md) * [`../references/uploads.md`](../references/uploads.md) — multipart vs from-URL * [`webhook-receiver.md`](./webhook-receiver.md) — the webhook handler in isolation * [`scheduled-generation.md`](./scheduled-generation.md) — single-task pattern for comparison # Design to code ci Source: https://docs.moda.app/.mintlify/skills/moda-api/recipes/design-to-code-ci # Design-to-code in CI **Problem:** You have a canonical Moda canvas that represents your design tokens (colors, fonts, radii, spacing variables). On every push to `main`, regenerate `tailwind.theme.ts` (or equivalent) from the canvas and commit the diff, so code always tracks design. ## Primitives * `GET /v1/canvases/{id}/tokens` — structured JSON of colors / fonts / radii / variables * A tiny codegen step in your CI (Node / Python / Deno) * Commit + PR if the diff is non-empty Scope used: `designs:read` only. Note that a key created in **Settings → Developer → REST API** has no scope picker — it carries the default grant (every scope except `admin`), so the CI key is a full-privilege credential even though this recipe only reads tokens. Give CI its own key, store it as a repository secret, and revoke it independently. ## TypeScript — GitHub Actions `.github/workflows/sync-theme.yml`: ```yaml theme={null} name: Sync design tokens on: push: branches: [main] schedule: - cron: "0 9 * * 1" # also weekly on Monday 09:00 UTC permissions: contents: write pull-requests: write jobs: sync: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: { node-version: "20" } - name: Regenerate theme env: MODA_API_KEY: ${{ secrets.MODA_API_KEY_READONLY }} CANVAS_ID: cvs_01HT9WK8N3M2J4A5Z6P7Q8R9TV run: node scripts/sync-theme.mjs - name: Open PR if changed uses: peter-evans/create-pull-request@v6 with: branch: design-tokens-sync title: "chore: sync design tokens from Moda" commit-message: "chore: sync design tokens from Moda" body: "Auto-generated from [canvas](https://moda.app/canvas/${{ env.CANVAS_ID }})." ``` `scripts/sync-theme.mjs`: ```js theme={null} import fs from "node:fs"; const API = "https://api.moda.app/v1"; const HEADERS = { Authorization: `Bearer ${process.env.MODA_API_KEY}`, "Moda-Version": "2026-05-01", }; const res = await fetch(`${API}/canvases/${process.env.CANVAS_ID}/tokens`, { headers: HEADERS, }); if (!res.ok) { const err = await res.json().catch(() => null); console.error("Moda fetch failed:", err?.error ?? res.statusText); process.exit(1); } const { variables, colors, fonts, radii } = await res.json(); // Emit a predictable, diffable TS file. const body = `// AUTO-GENERATED — edit the Moda canvas instead. // Source: cvs_${process.env.CANVAS_ID} // Generated: ${new Date().toISOString()} export const theme = { colors: { ${Object.entries(variables) .filter(([, v]) => typeof v === "string" && v.startsWith("#")) .map(([k, v]) => ` ${JSON.stringify(k)}: ${JSON.stringify(v)},`) .join("\n")} }, palette: ${JSON.stringify(colors, null, 2).replace(/\n/g, "\n ")}, fonts: ${JSON.stringify(fonts, null, 2).replace(/\n/g, "\n ")}, radii: ${JSON.stringify(radii, null, 2).replace(/\n/g, "\n ")}, } as const; `; fs.writeFileSync("src/design/theme.ts", body); console.log("Wrote src/design/theme.ts"); ``` ## Python — GitLab CI variant `.gitlab-ci.yml`: ```yaml theme={null} sync-theme: image: python:3.12 rules: - if: $CI_PIPELINE_SOURCE == "schedule" - if: $CI_COMMIT_REF_NAME == "main" before_script: - pip install httpx script: - python scripts/sync_theme.py - | if ! git diff --quiet src/design/theme.py; then git config user.email "ci@example.com" git config user.name "CI" git checkout -b design-tokens-sync git add src/design/theme.py git commit -m "chore: sync design tokens from Moda" git push origin design-tokens-sync -o merge_request.create fi variables: MODA_API_KEY: $MODA_API_KEY_READONLY CANVAS_ID: cvs_01HT9WK8N3M2J4A5Z6P7Q8R9TV ``` `scripts/sync_theme.py`: ```python theme={null} import os, sys, datetime, httpx HEADERS = { "Authorization": f"Bearer {os.environ['MODA_API_KEY']}", "Moda-Version": "2026-05-01", } r = httpx.get( f"https://api.moda.app/v1/canvases/{os.environ['CANVAS_ID']}/tokens", headers=HEADERS, timeout=30, ) if r.status_code != 200: print("Moda fetch failed:", r.json().get("error")) sys.exit(1) tokens = r.json() generated_at = datetime.datetime.utcnow().isoformat(timespec="seconds") + "Z" with open("src/design/theme.py", "w") as f: f.write(f'''"""AUTO-GENERATED — edit the Moda canvas instead. Source: {os.environ["CANVAS_ID"]} Generated: {generated_at} """ COLORS = {tokens["variables"]!r} PALETTE = {tokens["colors"]!r} FONTS = {tokens["fonts"]!r} RADII = {tokens["radii"]!r} ''') print("Wrote src/design/theme.py") ``` ## Why tokens, not `get_canvas` `GET /v1/canvases/{id}/tokens` is a dedicated endpoint that returns structured JSON. Parsing tokens out of the pseudo-HTML from `GET /v1/canvases/{id}` works but is fragile — layer names / HTML shape can change without signaling a token change. Use the dedicated endpoint for CI. ## Making it diffable * **Sort all arrays** before emitting — otherwise insertion order in the canvas creates spurious diffs on every run. * **Emit a deterministic timestamp header** (or omit the timestamp entirely; git tells you when the file changed). * **Name variables** in the Moda canvas — named variables land as keys in the `variables` object and become your `colors.primary`, `colors.background`, etc. ## Gotchas * **Treat the CI key as full-privilege.** This recipe only uses `designs:read`, but a Settings-created key carries the default grant — a leak is not limited to token reads. Isolate by key (one per integration) and rotate on any suspicion. * **Unknown response fields** may appear over time. Don't fail the build if the JSON has new keys — only fail if the keys you need are missing. * **Cache-bust properly.** If your codegen reads other files (a base theme, palette overrides), include them in the cache key for the CI action. * **Don't bypass PR review** by committing directly to `main`. PR the change — design tokens can have visual fallout. * **The canvas must be team-accessible** to the API key's team. Share links do NOT grant design token reads in CI — use a canvas URL + a team-scoped key. ## See also * [`../references/canvases-and-exports.md`](../references/canvases-and-exports.md) — tokens endpoint reference * [`../references/authentication.md`](../references/authentication.md) — scopes * `moda-mcp/references/gotchas.md` — its Design-to-code section, the IDE-side story for turning a canvas into code # Export pipeline Source: https://docs.moda.app/.mintlify/skills/moda-api/recipes/export-pipeline # Export pipeline **Problem:** Archive every canvas on the team as a PDF. Upload each to S3 / Google Drive. Skip canvases that have an in-flight design task. ## Primitives * `GET /v1/canvases` — cursor-paginate all canvases * `POST /v1/canvases/{id}/export?format=pdf` — returns a signed URL, or a `task_id` to poll * Handle `409 canvas_active_job` — back off and retry * Upload the file bytes to your storage of choice ## TypeScript (Node 20+) ```ts theme={null} import fs from "node:fs"; import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; const HEADERS = { Authorization: `Bearer ${process.env.MODA_API_KEY!}`, "Moda-Version": "2026-05-01", }; const s3 = new S3Client({ region: process.env.AWS_REGION }); const BUCKET = process.env.EXPORT_BUCKET!; async function* listAllCanvases() { let cursor: string | null = null; for (;;) { const u = new URL("https://api.moda.app/v1/canvases"); u.searchParams.set("limit", "100"); if (cursor) u.searchParams.set("cursor", cursor); const { data, next_cursor } = await fetch(u, { headers: HEADERS }).then(r => r.json()); for (const c of data) yield c; if (!next_cursor) return; cursor = next_cursor; } } async function exportWithRetry(canvasId: string, retries = 3): Promise { attempts: for (let attempt = 1; attempt <= retries; attempt++) { const res = await fetch( `https://api.moda.app/v1/canvases/${canvasId}/export?format=pdf`, { method: "POST", headers: HEADERS }, ); if (res.ok) { let exp = await res.json(); if (exp.status === "in_progress") { // slow render; poll it out const taskId = exp.task_id; for (;;) { await new Promise(r => setTimeout(r, (exp.retry_after_seconds ?? 5) * 1000)); const poll = await fetch( `https://api.moda.app/v1/canvases/${canvasId}/export-status?task_id=${taskId}`, { headers: HEADERS }, ); if (!poll.ok) continue attempts; // 429/5xx polling — not an export failure exp = await poll.json(); if (exp.is_terminal !== false) break; // terminal, or a shape we don't recognise } } if (exp.status !== "completed") { console.error(`Canvas ${canvasId}: export failed`, exp.error, exp.error_code); if (exp.retryable) continue; // transient — spend another attempt return null; // terminal for this canvas's content } return exp.url; } if (res.status === 409) { // canvas_active_job const wait = Number(res.headers.get("Retry-After") ?? 10) * 1000; console.log(`Canvas ${canvasId}: task running; waiting ${wait / 1000}s`); await new Promise(r => setTimeout(r, wait)); continue; } if (res.status === 429) { // rate limit const wait = Number(res.headers.get("Retry-After") ?? 10) * 1000; await new Promise(r => setTimeout(r, wait)); continue; } const body = await res.json().catch(() => null); console.error(`Canvas ${canvasId}: export failed`, body?.error); return null; } return null; } for await (const canvas of listAllCanvases()) { const exportUrl = await exportWithRetry(canvas.id); if (!exportUrl) continue; const bytes = Buffer.from(await (await fetch(exportUrl)).arrayBuffer()); await s3.send(new PutObjectCommand({ Bucket: BUCKET, Key: `canvases/${canvas.id}.pdf`, Body: bytes, ContentType: "application/pdf", Metadata: { "canvas-name": canvas.name, "updated-at": canvas.updated_at }, })); console.log(`Archived ${canvas.name} (${canvas.id})`); } ``` ## Python (`httpx`) ```python theme={null} import os, time, httpx, boto3 HEADERS = { "Authorization": f"Bearer {os.environ['MODA_API_KEY']}", "Moda-Version": "2026-05-01", } s3 = boto3.client("s3") BUCKET = os.environ["EXPORT_BUCKET"] def iter_canvases(c): cursor = None while True: params = {"limit": 100} if cursor: params["cursor"] = cursor resp = c.get("/canvases", params=params).json() yield from resp["data"] cursor = resp["next_cursor"] if cursor is None: return def export_with_retry(c, canvas_id, attempts=3): for _ in range(attempts): r = c.post(f"/canvases/{canvas_id}/export", params={"format": "pdf"}) if r.is_success: exp = r.json() polling_failed = False if exp.get("status") == "in_progress": # slow render; poll it out task_id = exp["task_id"] while exp.get("is_terminal") is not True: time.sleep(exp.get("retry_after_seconds") or 5) poll = c.get(f"/canvases/{canvas_id}/export-status", params={"task_id": task_id}) if not poll.is_success: # 429/5xx polling — not an export failure polling_failed = True break exp = poll.json() if polling_failed: continue # re-POST the export (cache-first, so cheap) if exp.get("status") != "completed": # .get: an error envelope has no "status" print(f"export failed for {canvas_id}: {exp.get('error')} ({exp.get('error_code')})") if exp.get("retryable"): # transient — spend another attempt continue return None # terminal for this canvas's content return exp["url"] if r.status_code in (409, 429): wait = int(r.headers.get("Retry-After", 10)) time.sleep(wait) continue print(f"export failed for {canvas_id}: {r.json().get('error')}") return None return None with httpx.Client(base_url="https://api.moda.app/v1", headers=HEADERS, timeout=120) as c: for canvas in iter_canvases(c): url = export_with_retry(c, canvas["id"]) if not url: continue # download and push to S3 content = httpx.get(url, timeout=120).content s3.put_object( Bucket=BUCKET, Key=f"canvases/{canvas['id']}.pdf", Body=content, ContentType="application/pdf", Metadata={"canvas-name": canvas["name"], "updated-at": canvas["updated_at"]}, ) print(f"Archived {canvas['name']} ({canvas['id']})") ``` ## Gotchas * **Export has two response shapes.** A cache hit or a quick render returns `{status: "completed", url}`; anything slower than the \~20s wait budget returns `{status: "in_progress", task_id}` and you poll `/canvases/{id}/export-status` until `is_terminal`. Full-team PDF archives hit the slow path routinely, so branch on `status` — reading `url` blindly gets you `null`. * **A failed *poll* is not a failed export.** A 429 or 5xx on `/export-status` says nothing about the render — retry the poll (or re-POST the export, which is cache-first) instead of treating it as a terminal failure. * **A failed export is not always final.** The poll response's `retryable` says whether a fresh attempt can succeed; `retryable: false` (e.g. `error_code: "no_renderable_content"`) means the canvas itself has to change first. Retrying those burns rate budget for nothing. * **Signed URLs expire after 7 days.** Download and re-upload immediately — don't persist the signed URL itself. * **`409 canvas_active_job`** is the retry signal when a design task is running on the canvas. Respect `Retry-After` (default 10s). * **`429 rate_limited`** applies per-endpoint — exports have their own cap (25/min by default, raisable per-org; see [Usage Limits](/api-reference/usage-limits)). Respect `Retry-After`. * **Cursor pagination is sequential.** Can't parallelize page fetches. Parallelize the **per-canvas work** within a page instead (cap to \~4–8 concurrent exports). * **Scope requirements:** `canvases:read` for listing, `designs:export` for the export endpoint. Team membership required — a share-token-only caller can't export. * **Don't export the same canvas twice in a row.** If you re-run this job often, compare `updated_at` against your archive and skip unchanged canvases. ## Variant: filter by search If you only want canvases matching a pattern: ```python theme={null} resp = c.get("/canvases/search", params={"q": "Q2 client decks", "limit": 100}).json() for canvas in resp["canvases"]: ... ``` `/canvases/search` is the one **offset**-paginated endpoint: items are under `canvases` (not `data`), and you page with `offset + limit` while `has_more` is `true`. ## See also * [`../references/canvases-and-exports.md`](../references/canvases-and-exports.md) — export semantics, 409 pattern * [`../references/pagination.md`](../references/pagination.md) * [`../references/errors.md`](../references/errors.md) — rate-limit handling # Scheduled generation Source: https://docs.moda.app/.mintlify/skills/moda-api/recipes/scheduled-generation # Scheduled generation **Problem:** A cron fires weekly. It should generate a branded status deck from yesterday's KPIs and post the canvas URL to a Slack channel. No human in the loop. ## Primitives * `POST /v1/tasks` with `callback_url` + `idempotency_key` * Webhook handler verifies signature and posts to Slack * (Optional) `POST /v1/canvases/{id}/export` if you want a PPTX link, not just the canvas URL ## Pattern Cron → start task with a stable `idempotency_key` → return immediately. The webhook fires 2–10 minutes later and does the Slack post. ## TypeScript (Node 20+) Cron entry point: ```ts theme={null} // cron/weekly-deck.ts — runs via GitHub Actions / Cloud Scheduler / your runner const MODA_API_KEY = process.env.MODA_API_KEY!; const CALLBACK_URL = "https://myapp.com/webhooks/moda"; const isoWeek = new Date().toISOString().slice(0, 10); // safe-enough stable key const kpis = await fetchWeeklyKPIs(); const res = await fetch("https://api.moda.app/v1/tasks", { method: "POST", headers: { Authorization: `Bearer ${MODA_API_KEY}`, "Moda-Version": "2026-05-01", "Content-Type": "application/json", }, body: JSON.stringify({ prompt: `Weekly status deck for the week of ${isoWeek}. Cover: - Headline metrics: ${JSON.stringify(kpis.headline)} - Product highlights this week - Next-week plan`, format: { category: "slides", width: 1920, height: 1080 }, number_of_slides: 8, callback_url: CALLBACK_URL, idempotency_key: `weekly-deck:${isoWeek}`, }), }); const task = await res.json(); // task.id = task_01HT9..., task.status = "queued" | "running", retry_after_ms: 3000 console.log(`Queued task ${task.id}; expect webhook to fire in 2–10 min`); ``` Webhook handler (Express): ```ts theme={null} // server/webhooks/moda.ts import crypto from "node:crypto"; import express from "express"; const SECRET = process.env.MODA_WEBHOOK_SECRET!; const app = express(); // raw body needed for signature verification app.post( "/webhooks/moda", express.raw({ type: "application/json" }), async (req, res) => { const ts = req.header("x-webhook-timestamp"); const sig = req.header("x-webhook-signature"); if (!ts || !sig) return res.status(400).end(); // replay protection if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return res.status(401).end(); const expected = crypto .createHmac("sha256", SECRET) .update(`${ts}.${req.body.toString("utf8")}`) .digest("hex"); const received = sig.replace(/^v1=/, ""); if ( !crypto.timingSafeEqual(Buffer.from(expected, "hex"), Buffer.from(received, "hex")) ) return res.status(401).end(); const event = JSON.parse(req.body.toString("utf8")); // dedupe on evt_… id (use Redis in production) if (await alreadyProcessed(event.id)) return res.status(200).json({ ok: true }); await markProcessed(event.id); res.status(200).json({ ok: true }); // 200 fast — process async void processAsync(event); }, ); async function processAsync(event: any) { if (event.type === "task.succeeded") { const { canvas_url } = event.data.result; await postToSlack(`Weekly deck ready: ${canvas_url}`); } else if (event.type === "task.failed") { await postToSlack( `Weekly deck failed: ${event.data.error?.message ?? "unknown"} ` + `(request_id=${event.data.error?.request_id ?? "?"})`, ); } } ``` ## Python (FastAPI + httpx) Cron entry point: ```python theme={null} # cron/weekly_deck.py import datetime, os, httpx, json MODA_API_KEY = os.environ["MODA_API_KEY"] CALLBACK_URL = "https://myapp.com/webhooks/moda" iso_week = datetime.datetime.utcnow().strftime("%Y-W%V") kpis = fetch_weekly_kpis() with httpx.Client( base_url="https://api.moda.app/v1", headers={ "Authorization": f"Bearer {MODA_API_KEY}", "Moda-Version": "2026-05-01", }, timeout=30, ) as c: task = c.post("/tasks", json={ "prompt": f"""Weekly status deck for {iso_week}. - Headline metrics: {json.dumps(kpis['headline'])} - Product highlights this week - Next-week plan""", "format": {"category": "slides", "width": 1920, "height": 1080}, "number_of_slides": 8, "callback_url": CALLBACK_URL, "idempotency_key": f"weekly-deck:{iso_week}", }).json() print(f"Queued task {task['id']}; webhook fires in 2–10 min") ``` Webhook handler (FastAPI): ```python theme={null} # server/webhooks.py import hashlib, hmac, os, time from fastapi import FastAPI, Header, HTTPException, Request app = FastAPI() SECRET = os.environ["MODA_WEBHOOK_SECRET"] processed: set[str] = set() # swap for Redis in production @app.post("/webhooks/moda") async def moda_webhook( req: Request, x_webhook_signature: str = Header(...), x_webhook_timestamp: str = Header(...), ): body = await req.body() if abs(time.time() - int(x_webhook_timestamp)) > 300: raise HTTPException(401, "stale timestamp") expected = hmac.new( SECRET.encode(), f"{x_webhook_timestamp}.{body.decode()}".encode(), hashlib.sha256, ).hexdigest() if not hmac.compare_digest(expected, x_webhook_signature.removeprefix("v1=")): raise HTTPException(401, "bad signature") event = await req.json() if event["id"] in processed: return {"ok": True} processed.add(event["id"]) # 200 fast; process async enqueue(event) # e.g. Celery / Arq / RQ return {"ok": True} ``` ## Gotchas * **Don't block the cron on the task.** Design tasks take 2–10 min, so a synchronous wait would time out — and the webhook fires anyway. Use the callback pattern. * **`idempotency_key` must be stable and unique per cron fire.** `"weekly-deck:2026-W17"` is good. `"weekly-deck"` alone is a landmine (every week reuses the same key → same task every time). * **`callback_url` is API-key-auth only.** The cron needs a real `moda_live_…` key. * **Slow webhook handlers get retried.** Stay under 30s wall time by enqueueing async. * **On `task.failed`**, check `data.error.retryable` — transient failures may retry inside Moda automatically; permanent ones won't. Either way, notify a channel — failures silently swallowed are the worst case. ## See also * [`../references/webhooks.md`](../references/webhooks.md) — signing details, event types * [`../references/idempotency.md`](../references/idempotency.md) — key design * [`webhook-receiver.md`](./webhook-receiver.md) — the handler in isolation # Webhook receiver Source: https://docs.moda.app/.mintlify/skills/moda-api/recipes/webhook-receiver # Webhook receiver **Problem:** Stand up a production-grade endpoint that verifies Moda webhook signatures, rejects replays, deduplicates, acknowledges fast, and hands off event processing to a background worker. ## Primitives * Raw request body (for HMAC) * `X-Webhook-Signature` + `X-Webhook-Timestamp` headers * Webhook signing secret (stored with the API key — **not** the API key itself) * Event envelope `id` as the dedupe key * Async worker (queue / task runner / Pub-Sub topic) for the actual work ## TypeScript — Express ```ts theme={null} // server/webhooks/moda.ts import express from "express"; import crypto from "node:crypto"; import { createClient } from "redis"; // use your dedupe store of choice const app = express(); const SECRET = process.env.MODA_WEBHOOK_SECRET!; const redis = createClient({ url: process.env.REDIS_URL }); await redis.connect(); // IMPORTANT: use express.raw here, NOT express.json — we need the exact bytes for HMAC. app.post( "/webhooks/moda", express.raw({ type: "application/json", limit: "1mb" }), async (req, res) => { const tsHeader = req.header("x-webhook-timestamp"); const sigHeader = req.header("x-webhook-signature"); if (!tsHeader || !sigHeader) return res.status(400).end(); // 1. replay protection const skew = Math.abs(Date.now() / 1000 - Number(tsHeader)); if (!Number.isFinite(skew) || skew > 300) return res.status(401).end(); // 2. signature verification const expected = crypto .createHmac("sha256", SECRET) .update(`${tsHeader}.${req.body.toString("utf8")}`) .digest("hex"); const received = sigHeader.replace(/^v1=/, ""); const sigOk = expected.length === received.length && crypto.timingSafeEqual( Buffer.from(expected, "hex"), Buffer.from(received, "hex"), ); if (!sigOk) return res.status(401).end(); // 3. parse + dedupe on event id const event = JSON.parse(req.body.toString("utf8")); const dedupeKey = `moda:evt:${event.id}`; const firstTime = await redis.set(dedupeKey, "1", { NX: true, EX: 60 * 60 * 24 * 7 }); if (!firstTime) return res.status(200).json({ ok: true }); // already handled // 4. ack fast; process in the background res.status(200).json({ ok: true }); void handleAsync(event); }, ); async function handleAsync(event: any) { try { switch (event.type) { case "task.succeeded": { const { canvas_url } = event.data.result; await notifySuccess(event.data.id, canvas_url); break; } case "task.failed": { const retryable = event.data.error?.retryable ?? false; await notifyFailure(event.data.id, event.data.error?.message, retryable); break; } case "task.canceled": // handle as needed break; case "export.succeeded": case "export.failed": // declared in the taxonomy, but nothing emits them today — keep the // arms so an unexpected delivery doesn't fall into the warn branch break; default: // unexpected event type → log for ops, not for the user console.warn("Unknown Moda event type", event.type, event.id); } } catch (e) { console.error("Handler threw", e, "event=", event.id); // do not re-throw — webhook was already acked } } ``` ## Python — FastAPI ```python theme={null} # server/webhooks/moda.py import hashlib, hmac, json, os, time from fastapi import FastAPI, Header, HTTPException, Request from redis.asyncio import Redis app = FastAPI() SECRET = os.environ["MODA_WEBHOOK_SECRET"] redis = Redis.from_url(os.environ["REDIS_URL"]) @app.post("/webhooks/moda") async def moda_webhook( req: Request, x_webhook_signature: str = Header(...), x_webhook_timestamp: str = Header(...), ): body = await req.body() # 1. replay protection try: skew = abs(time.time() - int(x_webhook_timestamp)) except ValueError: raise HTTPException(401, "bad timestamp") if skew > 300: raise HTTPException(401, "stale timestamp") # 2. signature verification expected = hmac.new( SECRET.encode(), f"{x_webhook_timestamp}.{body.decode()}".encode(), hashlib.sha256, ).hexdigest() received = x_webhook_signature.removeprefix("v1=") if not hmac.compare_digest(expected, received): raise HTTPException(401, "bad signature") # 3. dedupe on event id event = json.loads(body) first_time = await redis.set( f"moda:evt:{event['id']}", "1", nx=True, ex=60 * 60 * 24 * 7, ) if not first_time: return {"ok": True} # 4. enqueue async work; return fast await enqueue(event) # e.g. Celery, Arq, RQ, Pub/Sub return {"ok": True} async def enqueue(event: dict) -> None: # Your enqueue implementation. Must return in < a few seconds. ... ``` ## What to do per event type ``` task.succeeded → grab data.result.canvas_url, notify the user / CRM / Slack task.failed → check data.error.retryable: - retryable true: transient; task already dead-lettered after N attempts - retryable false: permanent; surface to the user task.canceled → quiet path; log only, or notify if cancellation was unexpected export.succeeded → declared, not emitted today — poll GET /v1/canvases/{id}/export-status export.failed → declared, not emitted today — same idea ``` Always log `data.error.request_id` on failures — it's the handle support will use to find your request. ## Gotchas * **Use raw body** for HMAC. Express / FastAPI default JSON parsing hides the exact bytes. `express.raw` or `await req.body()` (not `await req.json()` before reading body). * **Return 200 in \< 30s**, always. On a non-2xx or timeout, Moda makes up to 3 delivery attempts total (initial + 2 retries, \~1s then \~5s apart), then drops. * **Dedupe on `event.id`**, not `event.data.id`. Same task can have multiple events (succeeded vs failed, though rare; future: export for the same task). Using `event.id` dedupes **retries of the same event**; using `task.id` would dedupe legitimate different events. * **TTL your dedupe keys.** 7 days is plenty — Moda's retry window is minutes. * **Reject stale timestamps.** 5 minutes is the conventional bound. Anything older is almost certainly a replay attack. * **Use constant-time compare** (`timingSafeEqual` / `compare_digest`). Raw `==` leaks timing info. * **HTTPS only.** Moda won't deliver to plain-HTTP `callback_url`. * **Don't do work inside the handler.** Enqueue, then 200. If Postgres is down or Slack is slow, you want to 200 anyway and retry the downstream work yourself — not force Moda to retry. * **Test with the wrong signature** in staging to make sure you reject. A handler that silently accepts unsigned bodies is the worst case. ## Local testing without public HTTPS ``` ngrok http 3000 # or `tailscale serve` / `cloudflared tunnel` ``` Point the task's `callback_url` at the ngrok HTTPS URL. Signing still works — the signing secret is per-API-key, not per-URL. ## See also * [`../references/webhooks.md`](../references/webhooks.md) — full event list, retry curve * [`scheduled-generation.md`](./scheduled-generation.md) — the cron that produces the task * [`../references/authentication.md`](../references/authentication.md) — where the signing secret comes from # Authentication Source: https://docs.moda.app/.mintlify/skills/moda-api/references/authentication # Authentication (REST API) ## Header ``` Authorization: Bearer moda_live_ ``` Every request. Always pair with `Moda-Version: 2026-05-01`. ## Creating a key 1. Open the Moda app → **Settings → Developer → REST API → Create Key**. 2. Name the key for the integration it belongs to ("CI Pipeline", "Slack bot"). 3. Copy the key immediately — it's shown once. 4. Copy the **webhook signing secret** shown in the same banner. This is used to verify webhook payloads. You cannot retrieve it later. **There is no scope picker on that screen.** A key created there carries the **default grant** — every recognized scope except `admin`. Treat it as broadly privileged: one key per integration, stored as a production secret, revoked the moment it is no longer needed. Keys start with `moda_live_`. They are hashed at rest; only the prefix is safe to log. Lost a key? Revoke it and create a new one. ## Scopes (22) Twenty-two scopes are recognized; twenty-one of them are in the default grant. `admin` is opt-in only and never granted by default. | Scope | Grants | Default | | - | - | - | | `canvases:read` | List and search canvases; enumerate drive folders and files | ✅ | | `canvases:write` | Canvas actions (direct edits), imports, remix, embed sessions, share links | ✅ | | `designs:read` | Fetch canvas pseudo-HTML, tokens, page metadata; poll export status | ✅ | | `designs:export` | Export PNG / JPEG / PDF / PPTX / MP4 / GIF | ✅ | | `tasks:read` | Get task status; list tasks | ✅ | | `tasks:write` | Start design tasks | ✅ | | `tasks:cancel` | Cancel in-flight tasks | ✅ | | `brand_kits:read` | List brand kits | ✅ | | `brand_kits:write` | Create, update, delete brand kits; attach images | ✅ | | `uploads:write` | Upload files (multipart, signed-URL mint + register, from-URL) | ✅ | | `organizations:read` | List organizations and teams | ✅ | | `credits:read` | Check credit balance | ✅ | | `webhooks:manage` | Webhook configuration — recognized, guards no endpoint today | ✅ | | `publish:share` | Publish / unpublish hosted websites | ✅ | | `media:generate` | Metered media generation (credit-precharged per call) | ✅ | | `web:search` | Metered web search + page read | ✅ | | `websites:read` | Read hosted websites | ✅ | | `websites:write` | Create / update / delete hosted websites | ✅ | | `drive:write` | Create folders; move / rename / delete items; change visibility | ✅ | | `files:read` | Download file content (`GET /v1/drive/files/{id}/download`) | ✅ | | `expert:ask` | Grounded product Q\&A (free, read-only) | ✅ | | `admin` | Reserved for org-admin verbs — recognized, guards no endpoint today | ❌ | Drive **reads** (folder list / tree / file list / file metadata) ride `canvases:read`; only file **bytes** need `files:read`. ## Scope recipes by integration type What each integration actually *exercises* — useful for auditing an integration's blast radius, not something the Settings key creator lets you enforce. | Integration | Scopes | | - | - | | Read-only dashboard (list canvases, show tokens) | `canvases:read`, `designs:read`, `organizations:read` | | Scheduled design generator with Slack webhook | `brand_kits:read`, `uploads:write`, `tasks:write`, `tasks:read`, `designs:export`, `canvases:read` | | Export pipeline (every canvas → S3) | `canvases:read`, `designs:export` | | Theme regeneration in CI | `designs:read` | | Full-service automation | all scopes (least recommended — split by integration) | ## Security best practices * **Keep keys server-side.** Never expose them in frontend code, mobile apps, or client bundles. * **One key per integration.** Revocation affects one system; rotation doesn't cascade. * **Narrow scopes.** A read-only dashboard shouldn't have `tasks:write`. * **Rotate on a schedule** or after any suspected leak. Revoke in the app; issue a fresh key; update config. * **Store in a secret manager.** `.env` works for local dev; production should use Vault / AWS Secrets Manager / GCP Secret Manager / Doppler. * **Log the `request_id`** from error envelopes — it's how support finds your request in logs. Don't log the key itself. ## Revoking **Settings → Developer → REST API → Delete.** Takes effect immediately. All requests using that key return `401 Unauthorized` instantly. ## Errors | Status | Meaning | | - | - | | `401 authentication` | Missing, invalid, revoked, or expired key | | `403 permission` | Valid key, but missing the scope for this endpoint, or resource belongs to a different team | Both come with a `WWW-Authenticate: Bearer` header. Errors carry the standard typed envelope; see [`errors.md`](./errors.md). ## Common wrong guesses * **Committing a `moda_live_…` key to a repo.** Even private repos leak eventually. Use env vars + a secret manager. * **Assuming a key is narrow because the integration is.** Keys minted in Settings carry the default grant regardless of what the integration calls. Isolate by key, not by scope. * **Logging the full key for debugging.** Only log the prefix (`moda_live_`) — the suffix is a secret. * **Using the same key across production and staging.** Keys should be environment-specific so you can revoke independently. * **Forgetting the webhook signing secret.** It's shown once alongside the key. Store it adjacent to the key in your secret manager — you'll need it to verify webhook payloads. ## Upstream * [`docs.moda.app/api/authentication`](https://docs.moda.app/api/authentication) * [`docs.moda.app/api/webhooks`](https://docs.moda.app/api/webhooks) — signing secret details # Brand kits Source: https://docs.moda.app/.mintlify/skills/moda-api/references/brand-kits # Brand kits (REST) Full CRUD-ish lifecycle for brand kits. All endpoints under `/v1/brand-kits`. ## Endpoints | Verb | Path | Scope | Purpose | | - | - | - | - | | GET | `/brand-kits` | `brand_kits:read` | Cursor-paginated list for the key's team | | POST | `/brand-kits` | `brand_kits:write` | Extract from a URL (Firecrawl) and create a kit | | POST | `/brand-kits/extractions` | `brand_kits:write` | Extract a URL's brand in the background (`202`), creating no kit | | GET | `/brand-kits/extractions/{job_id}` | `brand_kits:read` | Poll an extraction; `completed` carries the brand | | PATCH | `/brand-kits/{id}` | `brand_kits:write` | Partial update | | DELETE | `/brand-kits/{id}` | `brand_kits:write` | Soft delete; returns `204` | | POST | `/brand-kits/{id}/images` | `brand_kits:write` | Attach uploaded file as logo / reference / asset | | GET | `/brand-kits/{id}/images` | `brand_kits:read` | List attached images (the only source of `image_id`) | | DELETE | `/brand-kits/{id}/images/{image_id}` | `brand_kits:write` | Remove an attached image; returns `204` | ## Default kit The **first brand kit created for a team becomes the default automatically.** `POST /v1/tasks` with no `brand_kit_id` uses the default. At most one default per team. Promote another kit with `PATCH /brand-kits/{id}` and `{"is_default": true}` — it clears whichever kit held the default, in the same transaction as any field writes in the same body, so a correct-and-promote cannot half-land. `is_default: false` is a `400`: demoting without naming a replacement would leave the team with no default at all, so promote the replacement instead. Omit the field to leave the flag alone. ## List ``` GET /v1/brand-kits?limit=100 ``` ```json theme={null} { "data": [ { "id": "bk_01HT9...", "title": "Acme Corp", "is_default": true, "company_name": "Acme Corp", "company_url": "https://acme.com", "company_description": "…", "tagline": "…", "brand_values": ["…"], "brand_aesthetic": ["…"], "brand_tone_of_voice": ["…"], "colors": [{ "color": "#2563eb", "label": "Primary" }, …], "fonts": [{ "family": "Inter", "label": "Body", "weight": 400, "supported": true }, …], "logos": [{ "group_name": "Primary Logo", "images": [{ "name": "logo.svg", "url": "…" }] }], "default_theme_canvas_id": "cvs_01HT9…", "created_at": "2026-…", "updated_at": "2026-…" } ], "next_cursor": "…" | null } ``` `default_theme_canvas_id` is the prefixed `cvs_…` ID of the kit's saved default slides theme canvas (`null` if none). Returned on reads and **writable via `PATCH`** (see below). Fresh-canvas design tasks auto-apply it when present, and so does a blank `POST /v1/canvases` with `category: "slides"` and this kit's `brand_kit_id` — the create response reports the attached theme as `theme_canvas_id` (`null` when the kit has no usable theme; the create still succeeds). Cursor-paginated; iterate with `?cursor=`. See [`pagination.md`](./pagination.md). ## Create from URL ``` POST /v1/brand-kits Content-Type: application/json {"url": "stripe.com"} ``` Server scrapes the URL via Firecrawl and extracts colors, fonts, logos, tone, values, aesthetic. The call is synchronous and **blocks for 10–30 seconds**. Returns the created brand-kit record (same shape as list items). URL accepts bare domain (`stripe.com`) or full URL (`https://stripe.com`). Cached — re-calling with the same URL returns the cached result quickly. If the URL can't be scraped (blocked by robots, 404, login-required): `422 scraping_user_error`. A kit built from a URL also carries what the extraction saw of the page: ```json theme={null} "screenshot": {"file_id": "…", "url": "https://…", "captured_at": "2026-…", "source_url": "https://stripe.com"}, "personality": {"tone": "professional", "energy": "low"} ``` `screenshot` is the homepage capture (`null` when none was taken). Its `url` is a signed, expiring URL that loads without auth on `GET /brand-kits/{id}`; it is `null` on create and `PATCH` responses, so keep `file_id` as the durable reference. `personality` is the site's tone and energy as Firecrawl's branding read reports them (`null` when it reported none). ## Extract a brand without creating a kit For a client that stores the brand itself and wants Moda only to read the site. Same extraction as create-from-URL (15–32 s cold, p90 28 s), so it runs as a job: ``` POST /v1/brand-kits/extractions {"url": "stripe.com"} → 202 {"job_id": "…", "status": "queued", "message": "Queued for extraction.", "retry_after_seconds": 2} GET /v1/brand-kits/extractions/{job_id} → 200 {"status": "running", …} → 200 {"status": "completed", "extraction": { "company_name", "company_url", "company_description", "tagline", "brand_values", "brand_tone_of_voice", "colors", "fonts", "logos": [{"group_name", "images": [{"name", "file_id", "url"}]}], "screenshot": {"file_id", "url", "captured_at", "source_url"} | null, "personality": {"tone", "energy"} | null }} → 200 {"status": "failed", "code": "scrape_failed" | "extraction_timeout" | "extraction_failed", "error": "…"} ``` No kit is created and nothing appears in the team's kit list, drive or library. The logo and screenshot files are kept for 24 hours so their URLs can be served, and those URLs are signed at each poll. Attach a `file_id` to a kit in that window (`logo_file_ids` on create, or `POST /v1/brand-kits/{id}/images`) and the kit keeps the file; any other `file_id` stops resolving after 24 hours, while URLs already signed keep working until they lapse. Download what you keep. A job whose worker died reads as `failed` with `extraction_failed`: start it again. Jobs are pollable for an hour; a job started on another team is `404`. `idempotency_key` makes a retried start return the first job. ## Update (partial) ``` PATCH /v1/brand-kits/{id} Content-Type: application/json { "title": "Acme Corp (Updated)", "colors": [ {"color": "#2563eb", "label": "Primary"}, {"color": "#0a2540", "label": "Dark"}, {"color": "#ff6b35", "label": "Accent"} ] } ``` Pass only the fields to change. Omitted fields keep their current values. **Array fields replace wholesale.** Passing `colors` overwrites the entire array — not a merge. To add one color, fetch the existing array, append, and PATCH the full list: ```python theme={null} existing = c.get(f"/brand-kits/{kit_id}").json() # full record c.patch(f"/brand-kits/{kit_id}", json={ "colors": [*existing["colors"], {"color": "#ff6b35", "label": "Accent"}], }) ``` Same rule for `fonts`, `brand_values`, `brand_aesthetic`, `brand_tone_of_voice`. **Setting the default theme canvas.** PATCH `default_theme_canvas_id` with a `cvs_…` ID (a bare UUID is also accepted) to point the kit at a slides theme canvas; send `null` to clear it: ```python theme={null} c.patch(f"/brand-kits/{kit_id}", json={"default_theme_canvas_id": "cvs_01HT9…"}) # set c.patch(f"/brand-kits/{kit_id}", json={"default_theme_canvas_id": None}) # clear ``` The ID must reference a canvas with `template_type='theme'` on the same team — anything else returns `400 invalid_theme_canvas`. Omitting the field leaves the current value unchanged. **Promoting the team default.** PATCH `is_default: true` to make this the team's default kit, clearing whichever kit held it. It applies in the same transaction as any field writes in the same body, so correcting a value and promoting the kit is one call that cannot half-land: ```python theme={null} c.patch(f"/brand-kits/{kit_id}", json={"colors": corrected, "is_default": True}) ``` Promote-only: `is_default: false` returns `400`. Demoting without naming a replacement leaves the team with no default at all, so promote the replacement kit instead. Omitting the field leaves the flag unchanged. Returns the updated record. ## Add images (logos / references / assets) ``` POST /v1/brand-kits/{id}/images Content-Type: application/json { "file_id": "file_01HT9...", "role": "logo", // one of: "logo" | "reference" | "asset" "label": "Dark mode logo" } ``` Requires an existing `file_id` from `POST /v1/uploads`. Attaches the uploaded file to the kit in the named role. Role here is **about the kit** (what this image represents in the brand) — different from the `role` field on task `attachments` (`source` / `reference` / `asset` / `import`). | Role (brand kit) | Meaning | | - | - | | `logo` | Logo asset (Moda uses it automatically on title slides, footers, etc.) | | `reference` | Style reference for the design agent | | `asset` | Miscellaneous asset | Returns the updated brand-kit record. ## List and remove images ``` GET /v1/brand-kits/{id}/images ``` ```json theme={null} { "data": [ { "id": "bki_01HT9...", "role": "logo", "file_id": "file_01HT9...", "url": "https://…", "name": "Dark mode logo", "group_id": "…", "group_name": "Logos" } ], "returned": 1, "total": 1 } ``` Returns the full list — not cursor-paginated. `total` always equals `returned`. **Read-back roles are `logo` or `reference` only.** `logo` rows come from the kit's logos; `reference` rows come from the design-assets bucket, which is shared by the `reference` **and** `asset` add-time roles — so an image attached with `role: "asset"` reads back as `reference`. Filtering the list for `role == "asset"` always returns nothing. ``` DELETE /v1/brand-kits/{id}/images/{image_id} ``` `image_id` is the `id` field (`bki_…`) from `GET /brand-kits/{id}/images` — **not** `file_id`, and not anything in the add-image response, which returns the whole kit record without image IDs. Returns `204 No Content`. A repeat DELETE on the same id returns `404` rather than erroring; a wrong-prefix id (e.g. a `file_` one) fails path validation with `422` before the handler runs. ## Delete ``` DELETE /v1/brand-kits/{id} ``` Returns `204 No Content`. Soft delete — historical tasks that referenced this kit continue to show it in their audit record. New design tasks with `brand_kit_id` pointing at a deleted kit get `404 not_found`. If the deleted kit was the team's default, there is no new default automatically. The team operates brand-kit-less until another kit is promoted (`PATCH /brand-kits/{id}` with `{"is_default": true}`) or a new kit is created. ## In-task usage Pass `brand_kit_id` explicitly on `POST /v1/tasks` to override the default: ```json theme={null} { "prompt": "…", "brand_kit_id": "bk_01HT9...", ... } ``` Or `skip_brand_kit: true` to apply no kit: ```json theme={null} { "prompt": "…", "skip_brand_kit": true, ... } ``` `skip_brand_kit` overrides `brand_kit_id` when both are present. ## Common wrong guesses * **Merging array updates client-side without reading first.** You'll overwrite the kit's colors / fonts with just the new entries. Always read, append, PATCH. * **Sending `is_default: false` to clear a default.** `400`. The field is promote-only — set `is_default: true` on the kit you want instead, which clears the incumbent for you. * **Expecting `POST /v1/brand-kits` to return immediately.** The call is synchronous: it returns the completed kit, but blocks for 10–30s — budget for that in your client timeout. * **Passing `brand_kit_id` for a deleted kit.** `404`. Check the kit exists before submitting the task. * **Filtering the images list for `role: "asset"`.** Reads only ever return `logo` or `reference` — `asset` and `reference` share one bucket, so `asset` attachments come back as `reference`. * **Passing a `file_` id to `DELETE /brand-kits/{id}/images/{image_id}`.** The path wants the `bki_` id from `GET /brand-kits/{id}/images`; a `file_` id fails path validation with `422`. `404` is the answer for a well-formed `bki_` id that isn't attached. * **Mixing up the task-attachment `role` and the brand-kit-image `role`.** Task `role` is `source` / `reference` / `asset` / `import`. Brand-kit image `role` is `logo` / `reference` / `asset`. Similar words, different values. * **Pointing `default_theme_canvas_id` at a deck instead of a theme.** It must be a `template_type='theme'` canvas on the same team, not a regular design/deck canvas. Anything else is `400 invalid_theme_canvas`. ## Upstream * [`docs.moda.app/api/brand-kits/listBrandKits`](https://docs.moda.app/api/brand-kits/listBrandKits) * [`docs.moda.app/api/brand-kits/createBrandKit`](https://docs.moda.app/api/brand-kits/createBrandKit) * [`docs.moda.app/api/brand-kits/updateBrandKit`](https://docs.moda.app/api/brand-kits/updateBrandKit) * [`docs.moda.app/api/brand-kits/addBrandKitImage`](https://docs.moda.app/api/brand-kits/addBrandKitImage) * [`docs.moda.app/api/brand-kits/listBrandKitImages`](https://docs.moda.app/api/brand-kits/listBrandKitImages) * [`docs.moda.app/api/brand-kits/removeBrandKitImage`](https://docs.moda.app/api/brand-kits/removeBrandKitImage) * [`docs.moda.app/api/brand-kits/deleteBrandKit`](https://docs.moda.app/api/brand-kits/deleteBrandKit) # Canvases and exports Source: https://docs.moda.app/.mintlify/skills/moda-api/references/canvases-and-exports # Canvases and exports All canvas-shaped read + export flows live under `/v1/canvases` and `/v1/remix`. Plus the share-token read pattern for public canvases and the `/v1/share_links/resolve` helper. ## Endpoints | Verb | Path | Scope | | - | - | - | | GET | `/canvases` | `canvases:read` | | GET | `/canvases/search` | `canvases:read` | | GET | `/canvases/{id}` | `designs:read` | | GET | `/canvases/{id}/tokens` | `designs:read` | | GET | `/canvases/{id}/pages` | `designs:read` | | POST | `/canvases/{id}/export` | `designs:export` | | POST | `/canvases/{id}/share` | `canvases:write` | | PATCH | `/canvases/{id}` | `canvases:write` | | POST | `/remix` | `canvases:write` | | POST | `/share_links/resolve` | (public) | ## Listing and search ``` GET /v1/canvases?limit=100 GET /v1/canvases/search?q=summer+launch&limit=50 ``` `GET /canvases` is cursor-paginated (`{data, next_cursor}`), sorted `(created_at DESC, id DESC)`. `GET /canvases/search` is the one offset-paginated lane in this catalog: it takes `q` / `limit` / `offset` and returns `{canvases, returned, limit, offset, has_more}`. See [`pagination.md`](./pagination.md). List items include `id`, `name`, `url`, `category`, `visibility`, `created_at`, `updated_at`. ## Reading a canvas ``` GET /v1/canvases/{id} ``` Returns the canvas as semantic pseudo-HTML with CSS properties + embedded design tokens. Same format as MCP's `get_moda_canvas`. Requires team access. ### Reading a public share ``` GET /v1/canvases/{id}?share_token= ``` Share-token-authenticated callers can read the canvas (view / view\_remix permission) without team access. Use in combination with `POST /v1/share_links/resolve` to parse a share URL first: ``` POST /v1/share_links/resolve { "url": "https://moda.app/s/abc123" } → { "canvas_id": "cvs_…", "share_token": "abc123", "permission": "view_remix", "expires_at": null } ``` Share-link-only callers can read but **cannot export** (see below). ### Tokens only ``` GET /v1/canvases/{id}/tokens ``` Returns `{variables, colors, fonts, radii, dimensions}` — fast path for theme regeneration in CI. ### Pages metadata ``` GET /v1/canvases/{id}/pages ``` Returns `{canvas_name, total_pages, pages: [{page_number, id, name, width, height, node_count}], id_note?}`. Call before `GET /v1/canvases/{id}?page_number=N` on multi-page canvases to plan per-page fetches. Which identifier to use depends on the endpoint. The design read (`GET /v1/canvases/{id}?page_number=N`) and the export take `page_number`; the authoring and capture endpoints take `id`. Prefer `id` where it is accepted — an ordinal renumbers when a page is deleted or reordered, so it names a different page over time. `id` is either a durable real page id (`page-1786730909610-172273165`) or a session-scoped short ref (`p_a`); `id_note` is returned only in the latter case and states the lifetime, so re-list rather than storing one. A page-less canvas lists one entry with no `id`. ### Updating a canvas ``` PATCH /v1/canvases/{id} { "name": "New name", "description": "...", "template_type": "template" } ``` Partial update — only send the fields you want to change. `description` and `template_type` both treat an explicit `null` as "clear the field." `template_type` is `template` (any canvas) or `theme` (slides canvases only). Returns the updated canvas record. ## Export — two response shapes ``` POST /v1/canvases/{id}/export?format=pptx ``` Query parameters: | Param | Values | Default | | - | - | - | | `format` | `png` / `jpeg` / `pdf` / `pptx` / `mp4` / `gif` | `png` | | `page_number` | integer ≥ 1 | omit for **all** pages (PDF/PPTX bundle natively; multi-page PNG/JPEG come back as a `.zip` of per-page files). `mp4` / `gif` export exactly one page — required on a multi-page canvas | | `pixel_ratio` | 1–4 (PPTX ignores it) | server default | | `flatten` | bool (PDF only — raster-only no text) | `true` | | `wait` | bool — block up to \~20s for the render before handing back a polling handle | `true` | | `force_refresh` | bool — bypass the cache and force a fresh render | `false` | The response carries one of two shapes, discriminated by `status`: ```json theme={null} { "status": "completed", "url": "https://assets-cdn.moda.app/.../deck.pptx", "format": "pptx", "source": "render" } ``` ```json theme={null} { "status": "in_progress", "task_id": "…", "retry_after_seconds": 5, "format": "pptx" } ``` **Branch on `status`.** A cache hit or a quick render finishes inside the \~20s wait budget and returns `completed`. A slow one (long documents, `mp4` / `gif` animation renders) returns `in_progress` — the work continues in the background; poll for the URL: ``` GET /v1/canvases/{id}/export-status?task_id=… → { "task_id": "…", "status": "running", "is_terminal": false, "retry_after_seconds": 5, "url": null } → { "task_id": "…", "status": "completed", "is_terminal": true, "url": "https://…", "format": "pptx" } ``` Poll until `is_terminal` is `true`; `status` is then `completed` (with `url`) or `failed`. A failed task carries `error`, sometimes a typed `error_code`, and — decisively — `retryable`: `false` means a fresh export of the same canvas cannot succeed either (e.g. `no_renderable_content`, `native_export_declined` — fix the content first), `true` means a transient fault worth one more attempt. Branch on `retryable` rather than treating every failure as final. `wait=false` skips the blocking wait and hands back the `in_progress` handle immediately. `format` in either shape reports what was actually **delivered** — `zip` for a bundled multi-page image export, even though the request asked for `png` / `jpeg`. **The URL expires after 7 days.** Download promptly. ### Caching Exports are **cache-first**. A repeat export of an unchanged canvas — same `format`, `page_number`, `pixel_ratio`, `flatten` — returns the previously rendered artifact with no new browser render. The `source` field reports how the response was served: * `render` — freshly rendered. * `cache` — a previously rendered artifact was reused. * `slice` — a single page extracted server-side from a cached full-document export (no render). The cache invalidates automatically when the canvas changes. Pass `force_refresh=true` only to skip the cache deliberately (e.g. you changed something the cache key doesn't capture) — the default path is faster and cheaper. Scope: `designs:export` **and** team membership. Share-token-only callers (no team access) cannot export — reads via `share_token` are not enough. ### Export when a design task is running If the target canvas has an in-flight design task, export returns: ``` HTTP/1.1 409 Conflict Retry-After: 10 Content-Type: application/json { "error": { "type": "conflict", "code": "canvas_active_job", "message": "Canvas cvs_… has an active design task; retry after it completes.", "request_id": "019d8996-…" } } ``` Back off for `Retry-After` seconds and retry. But in a task → export pipeline you often don't need a separate export call at all: a programmatic design task **auto-exports its result** when it finishes, and the completion webhook payload carries it at `data.result.export` (`{status, url, format, page_count}`). Read that instead of polling, retrying the 409, or issuing your own export. The auto-export uses the canvas's category-default format — pass `export_on_complete` to `POST /v1/tasks` to override the format or disable it. ### An export is not a Task Unlike design / remix / brand-kit extraction, an export never returns a Task envelope — even the async shape. Its `task_id` belongs to the export lane, so poll `GET /v1/canvases/{id}/export-status?task_id=…`, never `GET /v1/tasks/{id}`. The `export` task kind and the `export.*` webhook event types are declared in the public taxonomy but nothing emits them today, so don't wait on a webhook for an export either. ## Sharing — blocking thumbnail default ``` POST /v1/canvases/{id}/share { "wait_for_thumbnail": true } // default ``` Returns the share URL + share token. **By default, this call blocks until a thumbnail is generated** so the URL unfurls properly on social media / Slack. Thumbnail generation usually takes a few seconds; pass `wait_for_thumbnail: false` to skip if you don't care about unfurls. ## Remix ``` POST /v1/remix { "canvas_id": "cvs_01HT9...", "prompt": "Change to dark mode", // optional "new_name": "Q2 Deck (dark)", // optional "brand_kit_id": "bk_01HT9..." // optional, only used with a prompt } ``` Returns a Task envelope (`kind: "remix"`). Without a `prompt`: the task is synchronous, returns `status: "succeeded"` inline, `result.canvas_id` is the new canvas. With a prompt: queues a design task on the copy, returns non-terminal; poll same as `/tasks/{id}`. The source canvas is **never** modified. ## Design-to-code walk ``` # Discover structure pages = GET /v1/canvases/{id}/pages # → { total_pages: N, pages: [ { page_number, name, width, height, node_count } ] } # Extract tokens for theme tokens = GET /v1/canvases/{id}/tokens # → { variables, colors, fonts, radii, dimensions } # Walk pages for page in pages.pages: html = GET /v1/canvases/{id}?page_number={page.page_number} # → pseudo-HTML + embedded tokens ``` For visual reference on complex layouts, pair with `POST /v1/canvases/{id}/export?format=png`. ## Common wrong guesses * **Expecting `POST /v1/canvases/{id}/export` to return a Task envelope.** It returns its own two-shape payload — `{status: "completed", url, format, source}` or `{status: "in_progress", task_id, retry_after_seconds}`. * **Reading `url` without checking `status`.** `url` is `null` on the `in_progress` shape. Poll `/export-status` with the `task_id`. * **Assuming `page_number` defaults to page 1.** Omitting it exports **every** page; multi-page PNG/JPEG arrive as a `.zip` (`format: "zip"`). * **Passing `force_refresh=true` on every export.** The default is cache-first — a repeat export of an unchanged canvas is served from cache with no render. Only force a refresh when you deliberately need to bypass the cache. * **Issuing a separate export after a design task.** A programmatic task auto-exports; the completion webhook carries it at `data.result.export`. Re-exporting just hits the cache, but reading the webhook field is one fewer call. * **Treating the `409 canvas_active_job` response as a bug.** It's the intended retry signal when chaining task → export. * **Ignoring `Retry-After` on the 409 response.** Back off the suggested seconds; don't hammer. * **Using `share_token=` to export.** Only reads are permitted via share token. Export requires team access. * **Skipping `wait_for_thumbnail: false` on `/share` calls in a script.** By default it blocks — in a batch share-link generator, the latency adds up. Pass `false` if you don't care about unfurls. * **Treating `GET /v1/canvases/{id}` without `page_number` as cheap on multi-page designs.** It returns all pages concatenated. * **Holding an export URL longer than 7 days.** Expires. Re-export if needed. * **Storing the `X-Request-ID` header from a successful export** to use as an idempotency key. That's what the body-field `idempotency_key` on `POST /v1/tasks` is for — exports don't need it (stateless + fast). ## Upstream * [`docs.moda.app/api/canvases/listCanvases`](https://docs.moda.app/api/canvases/listCanvases) * [`docs.moda.app/api/canvases/getCanvas`](https://docs.moda.app/api/canvases/getCanvas) * [`docs.moda.app/api/canvases/exportCanvas`](https://docs.moda.app/api/canvases/exportCanvas) * [`docs.moda.app/api/canvases/makeCanvasPublic`](https://docs.moda.app/api/canvases/makeCanvasPublic) * [`docs.moda.app/api/remix/remixCanvas`](https://docs.moda.app/api/remix/remixCanvas) * [`docs.moda.app/api/share-links/resolveShareLink`](https://docs.moda.app/api/share-links/resolveShareLink) # Endpoints Source: https://docs.moda.app/.mintlify/skills/moda-api/references/endpoints # Endpoints Compressed catalog of every `2026-05-01` endpoint by router, with scope and a one-line purpose. Not a substitute for the OpenAPI spec — a scannable index. Base URL: `https://api.moda.app/v1` ## Tasks | Verb | Path | Operation | Scope | Purpose | | - | - | - | - | - | | POST | `/tasks` | `startTask` | `tasks:write` | Start an AI design task. Returns Task envelope immediately; poll or webhook. | | GET | `/tasks/{id}` | `getTask` | `tasks:read` | Fetch current task envelope. | | GET | `/tasks` | `listTasks` | `tasks:read` | Cursor-paginated list of team's tasks. | | POST | `/tasks/{id}/cancel` | `cancelTask` | `tasks:cancel` | Request cancellation. Returns 202 + updated envelope. | ## Remix | Verb | Path | Operation | Scope | Purpose | | - | - | - | - | - | | POST | `/remix` | `remixCanvas` | `canvases:write` | Duplicate canvas and optionally run a design task on the copy. Always returns a Task envelope (`kind: "remix"`). | Without a `prompt`: completes synchronously, returns `status: "succeeded"` inline. With a prompt: queues a task, returns non-terminal envelope; poll. ## Canvases | Verb | Path | Operation | Scope | Purpose | | - | - | - | - | - | | GET | `/canvases` | `listCanvases` | `canvases:read` | Cursor-paginated list of team canvases. | | GET | `/canvases/search` | `searchCanvases` | `canvases:read` | Relevance-ranked search by name/content (`q` query param). Offset-paginated — the one non-cursor list in this catalog. | | GET | `/canvases/{id}` | `getCanvas` | `designs:read` | Fetch canvas spec (pseudo-HTML + CSS). `share_token` query param for public reads. | | GET | `/canvases/{id}/tokens` | `getCanvasTokens` | `designs:read` | Extract design variables / colors / fonts / radii only. | | GET | `/canvases/{id}/pages` | `listCanvasPages` | `designs:read` | List page metadata (id, name, dimensions, node\_count). | | POST | `/canvases/{id}/export` | `exportCanvas` | `designs:export` | Export to PNG / JPEG / PDF / PPTX / MP4 / GIF. Returns `{status: "completed", url, format}` when it finishes inside the \~20s wait budget, else `{status: "in_progress", task_id}`. `409 + Retry-After: 10` when an active design task runs on this canvas. | | GET | `/canvases/{id}/export-status` | `getExportStatus` | `designs:read` | Poll an in-progress export by `task_id` until `is_terminal`. | | POST | `/canvases/{id}/share` | `makeCanvasPublic` | `canvases:write` | Create / retrieve a public share link. Blocks on thumbnail generation by default; pass `wait_for_thumbnail=false` to skip. | | PATCH | `/canvases/{id}` | `updateCanvas` | `canvases:write` | Update a canvas's name, description, or template\_type. | See [`canvases-and-exports.md`](./canvases-and-exports.md) for the export semantics and the share-token read pattern. ## Brand kits | Verb | Path | Operation | Scope | Purpose | | - | - | - | - | - | | GET | `/brand-kits` | `listBrandKits` | `brand_kits:read` | Cursor-paginated list. Team is implicit from the API key context. | | POST | `/brand-kits` | `createBrandKit` | `brand_kits:write` | Extract brand data from a URL (Firecrawl-backed). Returns the kit record. | | POST | `/brand-kits/extractions` | `startBrandExtraction` | `brand_kits:write` | Extract a URL's brand in the background (202 + `job_id`) without creating a kit. | | GET | `/brand-kits/extractions/{job_id}` | `getBrandExtraction` | `brand_kits:read` | Poll an extraction; `completed` carries the brand as `extraction`. | | PATCH | `/brand-kits/{id}` | `updateBrandKit` | `brand_kits:write` | Partial update. Array fields (`colors`, `fonts`) replace wholesale. | | DELETE | `/brand-kits/{id}` | `deleteBrandKit` | `brand_kits:write` | Soft delete. Returns 204. | | POST | `/brand-kits/{id}/images` | `addBrandKitImage` | `brand_kits:write` | Attach an uploaded file (logo / reference / asset). Requires `file_id` from `POST /uploads`. | | GET | `/brand-kits/{id}/images` | `listBrandKitImages` | `brand_kits:read` | List images attached to a brand kit. | | DELETE | `/brand-kits/{id}/images/{image_id}` | `removeBrandKitImage` | `brand_kits:write` | Remove an attached image. Returns 204. | See [`brand-kits.md`](./brand-kits.md) for update semantics. ## Uploads | Verb | Path | Operation | Scope | Purpose | | - | - | - | - | - | | POST | `/uploads` | `uploadFile` | `uploads:write` | Multipart upload, files up to \~32 MiB (gateway body cap). Returns `{id: "file_...", url, filename, mime_type, size_bytes, was_duplicate}`. | | POST | `/uploads/url` | `createUploadUrl` | `uploads:write` | Mint a short-lived signed PUT URL for direct-to-storage upload. Step 1 of the large-file flow. | | POST | `/uploads/register` | `registerUpload` | `uploads:write` | Finalize a signed-URL upload into a file row. Returns the same shape as `uploadFile`. Step 3. | | POST | `/uploads/from-url` | `uploadFromUrl` | `uploads:write` | Server fetches from a public URL, validates MIME, stores. SSRF-validated. | Deduplicates by content hash. Files are capped at `max_file_bytes` on every path — that ceiling is per-workspace (250 MB is the deployment maximum, a free workspace is lower), so read it from `GET /v1/uploads/limits` rather than hard-coding a number; the multipart path is additionally capped at \~32 MiB by the gateway, so larger files must use `/uploads/url` + `/uploads/register`. See [`uploads.md`](./uploads.md). ## Organizations | Verb | Path | Operation | Scope | Purpose | | - | - | - | - | - | | GET | `/organizations` | `listOrganizations` | `organizations:read` | Cursor-paginated list of orgs + teams the key's owner belongs to. | Role scoped: admins see all, members see their own. ## Credits | Verb | Path | Operation | Scope | Purpose | | - | - | - | - | - | | GET | `/credits` | `getCredits` | `credits:read` | Current balance, plan, reset date. `null` fields when billing is disabled. | ## Share links | Verb | Path | Operation | Scope | Purpose | | - | - | - | - | - | | POST | `/share_links/resolve` | `resolveShareLink` | (none — public-ish) | Parse a `moda.app/s/…` URL into `{canvas_id, share_token, permission, expires_at}`. Distinguishes `share_link_revoked` from `share_link_not_found`. | ## Usage / events (observability) | Verb | Path | Operation | Scope | Purpose | | - | - | - | - | - | | GET | `/usage` | `getApiUsage` | (admin) | Summary + daily / per-key / per-operation aggregates. 7-day default, 90-day max window. | | GET | `/events` | `listApiEvents` | (admin) | Cursor-paginated activity log. Rows include HTTP status, `operation_id`, `timestamp`, `trigger_source` (api / mcp). | Admins see everything; members see only their own keys' events. ## Webhook deliveries | Verb | Path | Operation | Scope | Purpose | | - | - | - | - | - | | GET | `/webhook_deliveries` | `listWebhookDeliveries` | (any authenticated key) | Cursor-paginated delivery log for the team; role-scoped (admins see all, members see their own keys' deliveries). `from` / `to` window defaults to the last 7 days, 90-day max — pass them explicitly to look further back. | | POST | `/webhook_deliveries/{id}/redeliver` | `redeliverWebhook` | (any authenticated key) | Queue a manual replay of a delivery. Returns 202. `403` unless you created the dispatching key or are a team admin — if that key has since been deleted, only admins can replay; `409` if the source task no longer exists. | ## Cross-cutting request headers | Header | Required | Notes | | - | - | - | | `Authorization: Bearer moda_live_…` | Yes (except `/share_links/resolve`) | See [`authentication.md`](./authentication.md) | | `Moda-Version: 2026-05-01` | Should | Pin in production. Omitting resolves to default. | | `Content-Type: application/json` | POST / PATCH | | | `Prefer: wait=` | No — **not implemented**; ignored | Use webhooks or polling instead. | | `Idempotency-Key` (header) | No — **not yet implemented** | Body field `idempotency_key` instead. | ## Cross-cutting response headers | Header | Always present | | - | - | | `Moda-Version` | Yes — the resolved version | | `X-Request-ID` | Yes — matches the `request_id` in error envelopes | | `Retry-After` | On `429 rate_limited` and `409 canvas_active_job` | ## Common wrong guesses * **Using the operation ID (`startTask`) as the path.** Operation IDs are for SDKs; the HTTP path is what matters. * **Expecting `/tasks/{id}/cancel` to be a DELETE.** It's a POST. * **Confusing `POST /canvases/{id}/share` with generating a share link on every call.** It creates one if missing, returns the existing one otherwise. It also blocks on thumbnail generation by default. * **Calling `GET /canvases/{id}` without `share_token=` on a share-only-visible canvas.** You'll get `404` — the call resolves through the key's team access, not the share link. * **Reading `url` off an export response without checking `status`.** A slow export returns `{status: "in_progress", task_id}` with `url: null` — poll `/canvases/{id}/export-status`. It is still not a Task envelope, so don't poll `/tasks/{id}`. * **Treating `409 + Retry-After: 10` on export as a failure.** It's the retry signal when a design task is running on the canvas. ## Upstream * Full OpenAPI spec: [`docs.moda.app/openapi/moda-public-api.yaml`](https://docs.moda.app/openapi/moda-public-api.yaml) * Per-endpoint docs: [`docs.moda.app/api/*`](https://docs.moda.app/api) # Errors Source: https://docs.moda.app/.mintlify/skills/moda-api/references/errors # Errors Every error response carries a single typed envelope under an `error` key. Branch on `type`, not HTTP status. ## Shape ```json theme={null} { "error": { "type": "not_found", "code": "file_not_found", "message": "Canvas cvs_abc123 not found", "doc_url": "https://docs.moda.app/api-reference/errors", "request_id": "019d8996-16b3-73ee-841a-5bc5038eb972", "details": null, "retry_after_ms": null, "causes": null } } ``` ## Fields | Field | Type | Notes | | - | - | - | | `type` | string | Stable high-level category. Branch your retry logic on this. | | `code` | string | Narrow machine-readable identifier. Stable once published. | | `message` | string | For developers. Not localized, not user-facing. **Don't parse.** | | `doc_url` | string | Permalink to the error-catalog page. A constant — `https://docs.moda.app/api-reference/errors` — on every envelope, not a per-code URL. | | `request_id` | string | Correlator. Also echoed in the `X-Request-ID` response header. | | `details` | object / null | Code-specific. Example for `validation_failed`: `{"fields": [{"field": "body.canvas_id", "code": "string_too_short"}]}` | | `retry_after_ms` | number / null | Hint for transient / rate-limited errors | | `causes` | array / null | Nested envelopes for aggregated failures (e.g. multi-page export with per-page errors) | ## Types (branch on these) | Type | HTTP | Retryable? | Action | | - | - | - | - | | `invalid_request` | 400 | No | Fix the request shape / values | | `authentication` | 401 | No | Renew / check the API key | | `permission` | 403 | No | Missing scope, or resource belongs to another team | | `not_found` | 404 | No | Bad ID, or the key's team doesn't see it | | `conflict` | 409 | No | Name collision, resource state conflict | | `idempotency_conflict` | 409 | No | Same `idempotency_key`, different body | | `unprocessable` | 422 | No | Well-formed request but validation failed | | `rate_limited` | 429 | Yes | Respect `Retry-After` header (seconds) or `retry_after_ms` | | `upstream_error` | 502 / 503 / 504 | Yes | Transient — back off and retry | | `internal_error` | 500 | Yes | Server bug — retry with backoff; include `request_id` when reporting | ## Selected codes worth knowing | Code | Type | Typical trigger | | - | - | - | | `unsupported_version` | `invalid_request` | Unknown `Moda-Version` header. `details.supported` lists valid versions. | | `validation_failed` | `unprocessable` | Body field failed a validation rule. `details.fields[]` names the offenders. | | `share_link_revoked` | `not_found` | Share link exists but is disabled. | | `share_link_not_found` | `not_found` | No share with that token. | | `scraping_user_error` | `unprocessable` | Brand-kit URL scrape failed (blocked by robots, 404, etc.). | | `canvas_active_job` | `conflict` | Export attempted on a canvas with an in-flight design task. `409 + Retry-After: 10`. See [`canvases-and-exports.md`](./canvases-and-exports.md). | | `source_url_unreachable` | `invalid_request` | `POST /uploads/from-url` could not fetch the URL (DNS, timeout, connection, TLS, redirect loop, upstream 3xx/4xx). The envelope's `retryable` says whether this cause is transient (timeout, 429) or needs a different URL (404). | | `unusable_source_url` | `invalid_request` | `POST /uploads/from-url` was redirected to a non-http(s) or malformed location. Pass the final URL. | | `source_url_not_a_file` | `invalid_request` | `POST /uploads/from-url` fetched something whose type is unresolvable (pass `filename` with the real extension) or not accepted. `415`. | ## Retry rules | Error type | Retry rule | | - | - | | `rate_limited` | Sleep `Retry-After` seconds (or `retry_after_ms`); retry. Exponential backoff on repeats. | | `upstream_error` | Sleep 1s, 5s, 30s on attempts 1, 2, 3. Give up after 3. | | `internal_error` | Same as `upstream_error`. | | Everything else | Don't retry — unless the envelope carries `retryable: true`. | When the envelope carries `retryable`, it wins over the type rule: `false` means the same request can never succeed. Never silently retry `invalid_request` / `authentication` / `permission` / `not_found` / `conflict` / `idempotency_conflict` / `unprocessable` — they're deterministic. ## Rate limiting * Surfaced as `429 rate_limited` with `Retry-After` header (seconds). * Applied per API key and per endpoint (e.g. exports are individually rate-capped). * Slow down, don't hammer. * The `RateLimit-*` response headers standardized in RFC 9240 are **not shipped yet**. Don't read them. Use `Retry-After` and the error's `retry_after_ms`. ## Logging & support * **Always log `request_id`** on every error. When you email [support@moda.app](mailto:support@moda.app), include it. * Log `type` and `code`; don't log `message` as the signal (it can change without notice). * Redact the API key from any log line. ## Error handling template (TypeScript) ```ts theme={null} async function modaFetch(path: string, init?: RequestInit) { const res = await fetch(`https://api.moda.app${path}`, { ...init, headers: { ...HEADERS, ...(init?.headers ?? {}) }, }); if (res.ok) return res.json(); const body = await res.json().catch(() => null); const err = body?.error; if (!err) throw new Error(`Moda ${res.status} (no envelope)`); if (err.type === "rate_limited" || err.type === "upstream_error" || err.type === "internal_error") { const ra = Number(res.headers.get("Retry-After") ?? 0) * 1000 || err.retry_after_ms || 3000; await new Promise(r => setTimeout(r, ra)); return modaFetch(path, init); // caller should cap recursion } throw new Error( `Moda ${err.type}/${err.code}: ${err.message} (request_id=${err.request_id})`, ); } ``` ## Error handling template (Python) ```python theme={null} import time, httpx def moda_fetch(client: httpx.Client, method: str, path: str, *, attempt: int = 1, **kw): r = client.request(method, path, **kw) if r.is_success: return r.json() body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {} err = body.get("error") or {} retryable = {"rate_limited", "upstream_error", "internal_error"} if err.get("type") in retryable and attempt <= 3: ra = int(r.headers.get("Retry-After", 0)) or ((err.get("retry_after_ms") or 3000) // 1000) or 3 time.sleep(ra) return moda_fetch(client, method, path, attempt=attempt + 1, **kw) raise RuntimeError( f"Moda {err.get('type')}/{err.get('code')}: {err.get('message')} " f"(request_id={err.get('request_id')})" ) ``` ## Common wrong guesses * **Branching on HTTP status only.** Status codes collapse types (both `rate_limited` and `idempotency_conflict` can be 409-adjacent in practice). Branch on `type`. * **Parsing `message`.** Can change without notice. Use `type` and `code` for logic; `message` for display only. * **Retrying `not_found` / `permission`.** Deterministic. * **Ignoring `Retry-After` on `429`.** You'll be back to rate-limited in seconds. * **Expecting `RateLimit-Limit` / `RateLimit-Remaining` / `RateLimit-Reset` response headers.** Not shipped yet. Use `Retry-After` and `retry_after_ms`. * **Not including `request_id` in support requests.** Without it, logs are hard to find. ## Upstream * [`docs.moda.app/api#error-format`](https://docs.moda.app/api#error-format) * [`docs.moda.app/api-reference/errors`](https://docs.moda.app/api-reference/errors) — the catalog every envelope's `doc_url` points at # Idempotency Source: https://docs.moda.app/.mintlify/skills/moda-api/references/idempotency # Idempotency `POST /v1/tasks` accepts an optional `idempotency_key` in the request body. Reusing the same key returns the existing task instead of creating a duplicate. Several other writes accept the same body field, with **stricter** semantics — see [Beyond `POST /v1/tasks`](#beyond-post-v1tasks). ## When to use * **Scheduled jobs.** Cron fires at 9am Monday. Use `idempotency_key: "weekly-deck:2026-W17"`. If your worker crashes after the POST succeeds but before writing the response, the next retry returns the same task. * **Network-timeout retries.** Your HTTP client times out mid-POST. Retry with the same key — safe. * **Upstream-triggered flows.** A Slack command fires two webhooks on the same action. Use the slack message ID as the key: `idempotency_key: "slack:T01234:123456.789"`. * **Bulk fan-out.** 50 prospects × one task each. `idempotency_key: "prospect:{id}:2026-04-weekly"` keeps re-runs safe. ## How it works ``` POST /v1/tasks { "prompt": "…", "idempotency_key": "focustime-v1", ... } ``` * First call: creates the task, returns the envelope. * Second call with the same key: returns the **original** task's envelope. The task lane matches on the key alone — it does **not** compare request bodies, so a reused key with a different prompt silently replays the first task rather than starting the new one. No dedicated "I'm reusing" flag on the response — the `id` matches the original, that's how you can tell. **The key is the intent.** Because there is no body comparison and no conflict error on this endpoint, a stale key is a silent no-op, not a loud failure: derive the key from everything that makes the request distinct (week, prospect, revision), and mint a fresh one whenever you want fresh output. ## Key design * **Stable and unique per logical operation.** "weekly-deck" alone is bad (reused every week); `"weekly-deck:2026-W17"` is good. * **Hash complex inputs** if the key would otherwise be long: `sha256(prompt + brand_kit_id + format)`. Deterministic + short. * **Namespace per integration — keys are not isolated per API key.** The task lane looks a key up globally, and the hashed lanes scope records to `(team, user, operation, key)`. Two of your integrations sharing a team can collide on a bare `"weekly-deck"` and silently replay each other's result. Prefix them: `"myapp:weekly-deck:2026-W17"`. * **TTL.** Idempotency records are retained long enough to cover sensible retry windows (24h on the hashed lanes) — don't build around a specific duration. If you're retrying a week later, use a different key. ## Beyond `POST /v1/tasks` `idempotency_key` is not task-only, and the other endpoints that take it are stricter than the task lane: they ride a shared pipeline that **hashes the request payload** alongside the key. Same key + same payload replays the stored result; same key + a different payload is a real `409 idempotency_conflict`; a same-key duplicate that lands while the first call is still running gets a retryable `409` instead of a second side effect. Records expire after 24h. `POST /v1/brand-kits` is the one to know — a retried create replays the stored kit instead of minting a second one (if the kit was deleted in the meantime, the stale record is invalidated and the create re-runs fresh). The metered verbs take it too. When in doubt, check the endpoint's request schema for an `idempotency_key` field rather than assuming it has none. Records are scoped to `(team, user, operation, key)` — not to the API key — so namespace your keys per integration. **Replay protection is best-effort, not a transaction.** The store fails *open*: if Redis is unavailable or the record was evicted, the call executes without replay protection rather than 5xx-ing. A retry in that window can produce a second side effect. Treat `idempotency_key` as strong protection against the common failure (a timed-out retry), not as a guarantee of exactly-once. `POST /v1/uploads` has no `idempotency_key`, and doesn't need one: it dedupes by content hash and reports `was_duplicate: true`. ### Conflict handling (hashed lanes) ```json theme={null} { "error": { "type": "conflict", "code": "idempotency_conflict", "message": "An existing operation is associated with this idempotency_key but with a different request body.", "request_id": "019d8996-…" } } ``` Fix one of: * Use a different `idempotency_key` for the new body. * Change your code so the body is byte-identical (e.g. canonicalize array order, don't include a timestamp in the payload). ## Not wired (yet) * **`Idempotency-Key` HTTP header** (Stripe-style). Today, `idempotency_key` is a **body field**. A header-based variant is on the roadmap; when it lands, existing body-field usage continues to work. ## Webhook idempotency (separate concern) Webhook **receivers** should use the event envelope's `id` (`evt_…`) as the dedupe key. That's about guarding your handler against duplicate deliveries — a different concern from `idempotency_key` on task creation. See [`webhooks.md`](./webhooks.md). ## Worked example — weekly cron ```python theme={null} iso_week = datetime.utcnow().strftime("%Y-W%V") # e.g. "2026-W17" resp = httpx.post( "https://api.moda.app/v1/tasks", headers=HEADERS, json={ "prompt": build_weekly_prompt(), "format": {"category": "slides", "width": 1920, "height": 1080}, "number_of_slides": 10, "callback_url": "https://myapp.com/webhooks/moda", "idempotency_key": f"weekly-deck:{iso_week}", }, ) # safe to retry this whole call on network error — same key, same body ``` ## Common wrong guesses * **Using an `Idempotency-Key` HTTP header.** Not supported today. Use the body field `idempotency_key`. * **Reusing the same key across different operations.** "default" as the key for every task. You'll just keep getting back the first task you ever created with that key. * **Changing the body and reusing the key on `POST /v1/tasks`.** You get the *old* task back, not an error and not a new task — the task lane never compares bodies. Use a fresh key when the intent changed. (On the hashed lanes below, the same mistake is a loud `409 idempotency_conflict`.) * **Assuming `idempotency_key` is task-only.** `POST /v1/brand-kits` and the metered verbs take it too, with the same replay / `409` semantics. Check the endpoint's request schema. ## Upstream * [`docs.moda.app/api/tasks/startTask`](https://docs.moda.app/api/tasks/startTask) — parameter reference * [`errors.md`](./errors.md) — the full error envelope including `idempotency_conflict` # Ids Source: https://docs.moda.app/.mintlify/skills/moda-api/references/ids # Resource IDs Every Moda resource has a **prefixed wire ID** like `cvs_01HT9WK8N3M2J4A5Z6P7Q8R9TV`. The prefix disambiguates the resource type on sight and prevents cross-resource lookup mistakes. ## Prefixes | Prefix | Resource | | - | - | | `cvs_` | Canvas | | `task_` | Task (design / export / remix / brand\_kit\_extract) | | `bk_` | Brand kit | | `bki_` | Brand-kit image attachment | | `file_` | Uploaded file | | `upl_` | Legacy upload record (use `file_` going forward) | | `conv_` | Conversation (multi-turn design context) | | `evt_` | Webhook event | | `whd_` | Webhook delivery | | `ak_` | API key | | `org_` | Organization | | `team_` | Team | Encoding: Crockford base32 (no I, L, O, U to avoid visual confusion). Case-insensitive. ## The two rules ### Requests — tolerant (either form) For the resources in the table above, JSON body fields **and** path parameters both accept the prefixed form or a bare UUID string. Pass a UUID straight from your database or a tool response without re-encoding. ```bash theme={null} # BOTH WORK — body field curl -X POST https://api.moda.app/v1/remix \ -H "Authorization: Bearer moda_live_..." \ -H "Moda-Version: 2026-05-01" \ -H "Content-Type: application/json" \ -d '{"canvas_id": "cvs_01HT9WK8N3M2J4A5Z6P7Q8R9TV"}' curl -X POST https://api.moda.app/v1/remix \ -H "..." \ -d '{"canvas_id": "550e8400-e29b-41d4-a716-446655440000"}' # BOTH WORK — path parameter curl -X POST https://api.moda.app/v1/canvases/cvs_01HT9WK8N3M2J4A5Z6P7Q8R9TV/export ... curl -X POST https://api.moda.app/v1/canvases/550e8400-e29b-41d4-a716-446655440000/export ... ``` Tolerance is a convenience for integrators who already hold raw UUIDs from an older system. Always prefer prefixed form in new code. Three spots are exceptions: * **Typed form required** — drive item and folder references: the polymorphic `/v1/drive/items/{item_ref}` verbs (move, rename, delete), and the `fld_…` filter on `GET /v1/drive/folders` and `GET /v1/drive/files`. A bare UUID is ambiguous across item kinds there. * **Typed form required** — `POST /v1/webhook_deliveries/{delivery_id}/redeliver`, which wants the `whd_…` id and answers `404` for anything else. * **Bare UUID required** — the `task_id` *query* parameter on `GET /v1/canvases/{id}/export-status`, which answers `400 "task_id must be a UUID."` for a prefixed value. The `task_id` that `POST /v1/canvases/{id}/export` hands back is already in that form, so pass it through unchanged. ### Responses — prefixed for these resources The `id` fields of the resources in the table above always come back prefixed, so if you store one from a response and pass it in later, you're fine. Surfaces outside that table carry raw UUIDs in both directions: the website endpoints, the export `task_id` above, and the `GET /v1/events` activity log (its row `id`, plus the nested `resource.id` and `resource.canvas_id`). The `evt_` prefix belongs to the webhook envelope below — not to activity-log rows. ## Why this design * Prefixed IDs are self-describing. Pasting one in a log or a PR makes it immediately clear what kind of object it is. * Request tolerance avoids breaking callers who already hold bare UUIDs from an older system or an internal store. * Prefixed responses mean a stored reference is still self-describing the next time you use it. ## In responses Every `id` field belonging to the resource types in the table above comes back prefixed: ```json theme={null} { "id": "task_01HT9WK8N3M2J4A5Z6P7Q8R9TV", "kind": "design", "result": { "canvas_id": "cvs_01HT9WK8N3M2J4A5Z6P7Q8R9TV", "canvas_url": "https://moda.app/canvas/..." } } ``` Store the prefixed form for future calls. ## Webhook payloads Webhook events carry a prefixed `evt_…` id: ```json theme={null} { "id": "evt_01HT9WK8N3M2J4A5Z6P7Q8R9TV", "type": "task.succeeded", "created": "2026-04-15T12:01:00+00:00", "api_version": "2026-05-01", "data": { "id": "task_01HT9WK8N3M2J4A5Z6P7Q8R9TV", ... } } ``` Use `id` (the event ID) as an idempotency key in your webhook handler — it's stable across retries. ## Common wrong guesses * **Assuming bodies reject bare UUIDs.** They don't — requests take either form. Only the drive `item_ref` / `fld_…` refs and `POST /v1/webhook_deliveries/{delivery_id}/redeliver` require the typed form. * **Storing bare UUIDs from older responses.** They work in path params today, but storing the prefixed form (from any current response) is safer for future use. * **Parsing the prefix at the client** to dispatch on resource type. Don't — use the `kind` field on task envelopes or the response shape. Prefixes are for humans. * **Passing a prefixed `task_…` to `GET /v1/canvases/{id}/export-status`.** That query parameter is bare-UUID-only — `400 "task_id must be a UUID."`. Forward the `task_id` from the export response verbatim. * **Assuming `upl_` and `file_` are interchangeable.** `upl_` is legacy; current uploads return `file_`. Don't mix. ## Upstream [`docs.moda.app/api/authentication#resource-id-formats`](https://docs.moda.app/api/authentication#resource-id-formats) # Pagination Source: https://docs.moda.app/.mintlify/skills/moda-api/references/pagination # Pagination Every list endpoint covered by this skill uses opaque cursor pagination — with one exception: `GET /v1/canvases/search` is offset-paginated (see [Search is the offset lane](#search-is-the-offset-lane) below). Newer surfaces outside this catalog (the drive folder/file lists, the website list) are offset lanes too, with their own `{, limit, offset, has_more}` shapes. Read the endpoint's own reference before assuming the cursor contract. ## Response shape ```json theme={null} { "data": [ ... ], "next_cursor": "eyJ2IjoxLCJzIjoiMjAyNi0wNC0xNVQxMjow..." | null, "returned": 20, "has_more": true, "limit": 20, "total": 137 | null } ``` * `data` — the page of items. * `next_cursor` — opaque signed string. Pass back as `?cursor=` to get the next page. `null` means you've reached the end. * `returned` / `has_more` — derived server-side (`len(data)` and `next_cursor != null`), so a page can never silently look complete. Never infer the end from `len(data) < limit`. * `limit` — the effective page size the response was computed with. * `total` — see below: a real count on some lanes, `null` on others. ## Iteration pattern **TypeScript:** ```ts theme={null} async function paginate(path: string): Promise { const all: T[] = []; let cursor: string | null = null; while (true) { const url = new URL(`https://api.moda.app${path}`); if (cursor) url.searchParams.set("cursor", cursor); url.searchParams.set("limit", "100"); const { data, next_cursor } = await fetch(url, { headers: HEADERS }).then(r => r.json()); all.push(...data); if (!next_cursor) return all; cursor = next_cursor; } } ``` **Python:** ```python theme={null} def paginate(path: str) -> list[dict]: out = [] cursor = None with httpx.Client(base_url="https://api.moda.app", headers=HEADERS, timeout=30) as c: while True: params = {"limit": 100} if cursor: params["cursor"] = cursor resp = c.get(path, params=params).json() out.extend(resp["data"]) cursor = resp["next_cursor"] if cursor is None: return out ``` ## Limits | Endpoint | Default | Max | | - | - | - | | `/v1/canvases`, `/v1/canvases/search`, `/v1/tasks`, `/v1/brand-kits`, `/v1/organizations` | 20 | 100 | | `/v1/events`, `/v1/webhook_deliveries` | 50 | 200 | Always request as large a page as you can tolerate — fewer roundtrips, less rate pressure. ## Sort order List endpoints sort by `(created_at DESC, id DESC)` on immutable columns. This guarantees pagination correctness when rows are added or modified mid-scan — no skips, no duplicates — at the cost of "sort by updated\_at" being unavailable. Client-side sort if you need a different order. ## `total` is per-lane `total` is present in the envelope but only populated where the collection supports a cheap true count — `GET /v1/tasks`, `GET /v1/brand-kits`, and `GET /v1/organizations` return a real count after filters. It stays `null` on the lanes where counting is as expensive as the query itself: `GET /v1/canvases` (the doc-kind filter reads un-indexed JSONB), `GET /v1/events`, `GET /v1/webhook_deliveries`, and the relevance-ranked search. So: use `total` when you have it, and never *require* it. `has_more` is the authoritative "is there more" signal on every lane. For a progress bar on a `null`-total lane, the common pattern is "processed 127 so far…" without a denominator. ## Opaque cursors Cursors are HMAC-signed + base64url-encoded. Don't: * Parse or mutate the cursor value. * Attempt to construct one by hand. * Reuse a cursor from a different list endpoint. The server detects tampering and returns `400 invalid_request`. Cursors are valid across sessions but have a bounded TTL — don't store one for a week and expect it to resume correctly. For long-running iterations (> a few hours), consider re-starting from the beginning. ## Endpoints that paginate All of these return `{data, next_cursor}`: * `GET /v1/canvases` * `GET /v1/tasks` * `GET /v1/brand-kits` * `GET /v1/organizations` * `GET /v1/events` * `GET /v1/webhook_deliveries` Single-resource endpoints (`GET /v1/canvases/{id}`, `GET /v1/tasks/{id}`, `GET /v1/credits`, etc.) don't paginate. ### Search is the offset lane `GET /v1/canvases/search` is relevance-ranked, so a cursor over `(created_at, id)` would be meaningless. It pages by offset and uses its own response shape: ``` GET /v1/canvases/search?q=summer+launch&limit=50&offset=0 → { "canvases": [ ... ], "returned": 50, "limit": 50, "offset": 0, "has_more": true } ``` Items are under `canvases`, not `data`. There is no `next_cursor` — page with `offset + limit` while `has_more` is `true`. `limit` defaults to 20 and caps at 100, same as the `/canvases` cursor lane (see [Limits](#limits) — the `/events` and `/webhook_deliveries` lanes are 50/200). ```python theme={null} offset = 0 while True: resp = c.get("/canvases/search", params={"q": query, "limit": 100, "offset": offset}).json() yield from resp["canvases"] if not resp["has_more"]: break offset += 100 ``` ## Concurrency Don't parallelize pagination. Each page depends on the previous one's cursor. Parallelize the **work done per item** inside a page instead. ## Migration from offset pagination If you're carrying code from the legacy `2026-04-12` shape: ```python theme={null} # Legacy (2026-04-12): offset = 0 while True: resp = client.get("/canvases", params={"offset": offset, "limit": 50}).json() for c in resp["canvases"]: yield c if not resp["has_more"]: break offset += 50 # Canonical (2026-05-01): cursor = None while True: params = {"limit": 50} if cursor: params["cursor"] = cursor resp = client.get("/canvases", params=params).json() for c in resp["data"]: yield c cursor = resp["next_cursor"] if cursor is None: break ``` ## Common wrong guesses * **Assuming `total` is always there — or never there.** It is a real count on `/tasks`, `/brand-kits`, and `/organizations`, and `null` on `/canvases`, `/events`, `/webhook_deliveries`, and search. Branch on it; rely on `has_more`. * **Parsing / mutating cursors.** Opaque; server rejects tampered values. * **Passing `offset=` to a cursor endpoint.** Ignored (or rejected, depending on endpoint) on `2026-05-01`. Use the cursor — except on `/canvases/search`, where `offset` *is* the mechanism. * **Holding a cursor for days.** Cursors expire; restart the iteration. * **Parallel page fetches.** Each page depends on the prior cursor. * **Reading `response.canvases` / `response.tasks` / `response.brand_kits`.** The cursor lanes always put items under `data`. `GET /canvases/search` is the exception — its items are under `canvases`. * **Expecting a `next_cursor` from `/canvases/search`.** It has none. Page with `offset` while `has_more` is `true`. ## Upstream * [`docs.moda.app/api/versioning`](https://docs.moda.app/api/versioning) — migration map * Per-endpoint docs at [`docs.moda.app/api/{canvases,tasks,brand-kits,organizations}/*`](https://docs.moda.app/api) # Task envelope Source: https://docs.moda.app/.mintlify/skills/moda-api/references/task-envelope # Task envelope Every task-shaped operation — design, remix, brand-kit extraction — returns the canonical Task envelope. (Canvas export is *not* one of them; it has its own two-shape payload — see below.) Pin `Moda-Version: 2026-05-01` to get this shape. ## Full shape ```json theme={null} { "id": "task_01HT9WK8N3M2J4A5Z6P7Q8R9TV", "kind": "design", "status": "queued", "created_at": "2026-04-15T12:00:00+00:00", "started_at": null, "completed_at": null, "progress": null, "attempt": 1, "max_attempts": 3, "attempts_started": 0, "first_started_at": null, "input": { "prompt": "Create a sales deck", "format": { "category": "slides", ... } }, "result": null, "error": null, "credits": null, "links": { "self": "/v1/tasks/task_01HT9...", "events": null, "cancel": "/v1/tasks/task_01HT9.../cancel", "canvas": null }, "retry_after_ms": 3000 } ``` ## Fields | Field | Type | Notes | | - | - | - | | `id` | string | `task_`-prefixed ID | | `kind` | string | `design` / `export` / `remix` / `brand_kit_extract` — discriminator for `input` / `result` shape | | `status` | string | `queued` / `running` / `succeeded` / `failed` / `canceled` / `expired` | | `created_at` | ISO 8601 | When the task was created | | `started_at` | ISO 8601 / null | When the worker picked up the **current** attempt. Rewritten on every retry — see `first_started_at` | | `first_started_at` | ISO 8601 / null | When the worker picked up the **first** attempt. `null` means unknown (task predates this field, or was never claimed) | | `completed_at` | ISO 8601 / null | Terminal timestamp | | `progress` | object / null | `{percent, step, message}` — populated during `running` | | `attempt` | integer | Current attempt number, floored at 1. Cannot distinguish a never-claimed task from one retrying after a dead attempt — use `attempts_started` for that | | `attempts_started` | integer | Attempts **begun** (not completed). `0` for a task no worker has claimed yet; `1` while the first attempt runs *and* through its retry backoff | | `max_attempts` | integer | Usually 3 — auto-retry cap for transient failures | | `input` | object | Varies by `kind` (design: `{prompt, format, ...}`; export: `{canvas_id, format, ...}`) | | `result` | object / null | Populated on `succeeded`; varies by `kind` (design: `{canvas_id, canvas_url, conversation_id, export}`) | | `error` | object / null | `{message, retryable, attempt}` — populated on `failed`, and on a **non-terminal** task carrying a previous attempt's failure | | `credits` | object / null | `{credits_used, credits_remaining}` on `succeeded` | | `links` | object | HATEOAS-style relations: `self`, `events`, `cancel`, `canvas` | | `retry_after_ms` | integer / null | Non-null while non-terminal; typically `3000` (3s) | ## Status state machine ``` queued → running → succeeded → failed → canceled → expired (rare; long-queued tasks time out) ``` Terminal: `succeeded`, `failed`, `canceled`, `expired`. Non-terminal: `queued`, `running`. Derive `is_terminal` = `status in {"succeeded","failed","canceled","expired"}`. Derive `can_export` = `status == "succeeded" && result && result.canvas_id`. ## Distinguishing a retry from a queue wait A task whose attempt died (execution-cap kill, worker timeout, lost heartbeat) is retried automatically, and it sits in `queued` for the whole backoff. That is **not** queue contention, and it is the single most-misread thing about this envelope: teams see a 10-minute `queued` and buy parallelism they do not need. Tell them apart: | Signal | Never started (real queue wait) | Retrying after a dead attempt | | - | - | - | | `status` | `queued` | `queued` | | `attempts_started` | `0` | `>= 1` | | `first_started_at` | `null` | the first attempt's start | | `error` | `null` | the **previous** attempt's failure | ``` is_retrying = status in {"queued", "running"} and attempts_started >= 1 and error is not None ``` Notes: * **`>= 1`, not `>= 2`.** `attempts_started` is incremented when a worker *claims* the task, so a first attempt that is currently `running` already reads `1`, and it stays `1` through that attempt's backoff. Combine it with `status` — `running` + `attempts_started == 1` is an ordinary first run, `queued` + `attempts_started == 1` is a retry. * **`error` on a non-terminal task describes the previous attempt, not the current one.** Its `attempt` field says which attempt produced it. A task that is `running` again after a failure deliberately keeps the failing reason for triage — do not render it as "this attempt failed". * **Wall-clock attribution.** `created_at → first_started_at` is the true queue wait. `created_at → started_at` spans every dead attempt and its backoff too, so it overstates queueing on any retried task. * **`first_started_at: null` means unknown**, never "never started" — tasks created before this field shipped have no value for it. Read `attempts_started` for the never-started case. There is no `retrying` status. The public status taxonomy is frozen, and consumers derive `is_terminal` from it, so a new value would break existing pollers. ## Discriminator — `kind` Task shape is polymorphic on `kind`: | `kind` | `input` includes | `result` includes (on succeeded) | | - | - | - | | `design` | `prompt`, `format`, `attachments`, `brand_kit_id`, `number_of_slides`, ... | `canvas_id`, `canvas_url`, `conversation_id`, `export` | | `remix` | `canvas_id`, `prompt`, `brand_kit_id`, ... | `canvas_id`, `canvas_url`, `source_canvas_id` | | `export` | declared in the enum; no code path produces a task of this kind today | — | | `brand_kit_extract` | `url` | `brand_kit_id` | Always check `kind` before reading `result` fields. On a succeeded `design` task, `result.export` carries the finished design **already rendered to a file** — `{url, format, status, page_count}`, exported in the canvas's category-default format. Read it directly instead of issuing a separate `POST /v1/canvases/{id}/export`. It is absent when auto-export was disabled (`export_on_complete: {enabled: false}`) or did not finish within the budget. Note: `POST /v1/canvases/{id}/export` never returns a Task envelope. It returns its own payload — `{status: "completed", url, format, source}` when the render lands inside the \~20s wait budget, or `{status: "in_progress", task_id, retry_after_seconds}` when it doesn't. Poll `GET /v1/canvases/{id}/export-status?task_id=…` for the async case, not `/v1/tasks/{id}`. The `export` task kind and the `export.succeeded` / `export.failed` webhook events are declared in the public taxonomy but nothing emits them today. See [`canvases-and-exports.md`](./canvases-and-exports.md). ## Delivery patterns Pick one per task — don't stack: ### 1. Webhook (`callback_url`) — recommended for async backends Pass `callback_url` in the task body. Webhook fires on terminal state only. Requires `moda_live_…` API key auth (OAuth callers get `400`). See [`webhooks.md`](./webhooks.md). ### 2. Polling — simplest for short-lived callers ``` POST /v1/tasks → task envelope with retry_after_ms loop: wait retry_after_ms GET /v1/tasks/{id} break when status is terminal ``` Respect `retry_after_ms`. Don't poll faster. ### No sync-feel header The API does not currently implement RFC 7240 `Prefer: wait` — the header is ignored on every endpoint. Operations that are fast (brand-kit creation, remix without a prompt) are simply synchronous; everything else is webhook or polling. ## Timing expectations | Operation | Typical time | | - | - | | `POST /v1/tasks` (design from scratch) | 2–10 min | | `POST /v1/tasks` with `conversation_id` (follow-up edit) | 1–5 min | | `POST /v1/remix` **with** a prompt | 2–10 min (it's a design task under the hood) | | `POST /v1/remix` **without** a prompt (plain duplicate) | \< 1s (synchronous, no task) | | `POST /v1/brand-kits` (from URL) | 10–30s | | `POST /v1/canvases/{id}/export` | seconds (signed URL inline); slow renders return a `task_id` after \~20s and finish in the background | Set user expectations up front. Don't block callers on multi-minute operations. ## Common wrong guesses * **Polling faster than `retry_after_ms`.** Burns your rate budget for no latency benefit. * **Reading `response.canvas_id` on a canonical response.** It's `response.result.canvas_id`. The flat field is legacy (`2026-04-12`). * **Expecting `export` kind from `POST /v1/canvases/{id}/export`.** That endpoint does not return a Task envelope — its `task_id` is polled via `/canvases/{id}/export-status`. * **Reading a long `queued` as queue contention.** Check `attempts_started` first — a retry after a dead attempt looks identical to a queue wait on `status` alone. * **Treating `expired` as a failure.** It is terminal (same as the others) but the cause is queue-depth or worker-starvation, not a user-actionable error — retry the task fresh. ## Upstream * [`docs.moda.app/api/tasks/startTask`](https://docs.moda.app/api/tasks/startTask) * [`docs.moda.app/api/tasks/getTask`](https://docs.moda.app/api/tasks/getTask) * [`docs.moda.app/api/versioning`](https://docs.moda.app/api/versioning) — for the legacy → canonical migration map # Uploads Source: https://docs.moda.app/.mintlify/skills/moda-api/references/uploads # Uploads Four endpoints. All require `uploads:write`. ## Entrypoints ### `POST /v1/uploads` — multipart (files up to \~32 MiB) ```bash theme={null} curl -X POST https://api.moda.app/v1/uploads \ -H "Authorization: Bearer moda_live_..." \ -H "Moda-Version: 2026-05-01" \ -F "file=@/path/to/brief.pdf" ``` Response: ```json theme={null} { "id": "file_01HT9WK8N3M2J4A5Z6P7Q8R9TV", "url": "https://api.moda.app/api/v2/images/ref/550e8400-...?h=abc123", "filename": "brief.pdf", "mime_type": "application/pdf", "size_bytes": 245760, "was_duplicate": false } ``` Use when you have the bytes locally and the file is under \~32 MiB. Above that, use the signed-URL flow below — the gateway rejects the request before it reaches this handler. ### `POST /v1/uploads/url` + `POST /v1/uploads/register` — signed URL (large files) The bytes go straight from your client to object storage, bypassing our gateway entirely. ```bash theme={null} # 1. Mint a short-lived signed PUT URL curl -X POST https://api.moda.app/v1/uploads/url \ -H "Authorization: Bearer moda_live_..." \ -H "Moda-Version: 2026-05-01" \ -H "Content-Type: application/json" \ -d '{"filename": "deck.pptx", "mime_type": "application/vnd.openxmlformats-officedocument.presentationml.presentation"}' # → {"upload_url": "https://storage.googleapis.com/...", "storage_key": "...", "mime_type": "...", "expires_in_seconds": 600} # 2. PUT the raw bytes to upload_url with the SAME Content-Type. # No Authorization header — the signed URL itself is the capability. curl -X PUT "$UPLOAD_URL" \ -H "Content-Type: application/vnd.openxmlformats-officedocument.presentationml.presentation" \ --data-binary @deck.pptx # 3. Register it to get a FileUploadResponse curl -X POST https://api.moda.app/v1/uploads/register \ -H "Authorization: Bearer moda_live_..." \ -H "Moda-Version: 2026-05-01" \ -H "Content-Type: application/json" \ -d '{"storage_key": "...", "filename": "deck.pptx", "mime_type": "application/vnd.openxmlformats-officedocument.presentationml.presentation"}' ``` `register` returns the same `FileUploadResponse` shape as multipart, including content-hash dedupe. **Pass `mime_type` on step 3.** It's optional, but when omitted `register` re-derives the type from the basename embedded in `storage_key` — so a `filename` with no recognizable extension (perfectly legal at step 1, which takes an explicit `mime_type`) fails with `415 "Missing or unrecognizable content type"` *after* you've already paid for the whole PUT. Send the same `mime_type` you declared at step 1 and that can't happen. `filename` is optional too and defaults to the same basename. Signed URLs expire after `expires_in_seconds` (60–3600, default 600). The TTL bounds the PUT only — `register` doesn't check it. Because `register` hashes the whole blob, a 100+ MB file can take several seconds; set your client timeout accordingly. ### `POST /v1/uploads/from-url` ```bash theme={null} curl -X POST https://api.moda.app/v1/uploads/from-url \ -H "Authorization: Bearer moda_live_..." \ -H "Moda-Version: 2026-05-01" \ -H "Content-Type: application/json" \ -d '{"source_url": "https://example.com/mockup.png"}' ``` Server fetches the URL, validates MIME, stores. Returns the same `FileUploadResponse` shape. Use when the file is already hosted publicly and you don't want to proxy it through your own machine. The fetch has a 30s budget; a slow source returns `400`. SSRF-validated server-side — internal / localhost / metadata URLs are rejected with `422`. ## Supported types * Images: any `image/*` (PNG, JPEG, WebP, GIF, SVG, …) * Documents: PDF, PPTX / PPT, DOCX / DOC, XLSX / XLS * Text: CSV, plain text, Markdown, JSON * Video (upload + in-app viewing, no transcoding): MP4, WebM, MOV * Audio (upload + in-app playback, no transcoding): MP3, M4A, AAC, WAV, FLAC, OGG / OGA * Figma local-copy exports: `.fig`, `.deck` (brand-kit import) Anything else is rejected with `415 unsupported media type`. ## Size limits The gateway cap is fixed; the application cap varies by workspace plan: | Path | Effective max | Why | | - | - | - | | `POST /v1/uploads` (multipart) | **\~32 MiB** | Our API gateway caps inbound HTTP/1 request bodies. Larger requests are rejected before reaching the handler. | | `POST /v1/uploads/url` + `POST /v1/uploads/register` | **`max_file_bytes`** | Bytes go client → storage directly, so the gateway cap doesn't apply. | | `POST /v1/uploads/from-url` | **`max_file_bytes`** | The server does the fetch; nothing traverses our ingress. | `max_file_bytes` is the application cap and it applies to every path. It is **per-workspace, not per-deployment** — 250 MB is the maximum, and a free workspace is capped lower — so read it from `GET /v1/uploads/limits` and cache it per API key rather than hard-coding a number. The same response carries `max_file_bytes_is_plan_limit`: when it is `true`, the ceiling is the workspace's plan rather than the platform, so the remedy to report is an upgrade and not only a smaller file. Oversize uploads return **`413 payload too large`** — on `POST /v1/uploads/register`, the staged blob is deleted automatically. ## Deduplication Content-hash dedupe. Uploading the same bytes twice returns: ```json theme={null} { "id": "file_01HT9...", "was_duplicate": true, ... } ``` `id` / `url` / `filename` / `mime_type` / `size_bytes` point at the existing record. Safe to call repeatedly — no duplicate storage, no duplicate billing. ## Using in a task ```bash theme={null} curl -X POST https://api.moda.app/v1/tasks \ -H "Authorization: Bearer moda_live_..." \ -H "Moda-Version: 2026-05-01" \ -H "Content-Type: application/json" \ -d '{ "prompt": "Build a pitch deck from the attached brief", "format": { "category": "slides", "width": 1920, "height": 1080 }, "attachments": [ { "file_id": "file_01HT9WK8...", "role": "source", "label": "Q2 strategy brief" } ] }' ``` ### Roles | Role | Meaning | | - | - | | `source` | Extract content from this file (brief, notes, CSV) | | `reference` | Emulate this file's style (mood board, screenshot) | | `asset` | Use verbatim (logo, hero image) | | `import` | Convert a PPTX deck into editable slides on the canvas, then design against it (PPTX-only; any other file type is rejected) | Pick the right role — it determines what the agent does with the file. See the Attachments section of `moda-mcp/references/gotchas.md` for details; the attachment shape is identical between MCP and REST. ## URL-form attachment (legacy, less preferred) ```json theme={null} { "attachments": [ { "url": "https://example.com/mockup.png", "type": "image" } ] } ``` No role metadata. Still works for hosted public URLs when you want to avoid the upload roundtrip. Mix with file-id-form in the same list freely. ## Worked example ```python theme={null} import httpx, os HEADERS = {"Authorization": f"Bearer {os.environ['MODA_API_KEY']}", "Moda-Version": "2026-05-01"} with httpx.Client(base_url="https://api.moda.app/v1", headers=HEADERS, timeout=60) as c: with open("brief.pdf", "rb") as f: upload = c.post("/uploads", files={"file": ("brief.pdf", f, "application/pdf")}).json() task = c.post("/tasks", json={ "prompt": "Build a 10-slide pitch deck from the brief", "format": {"category": "slides", "width": 1920, "height": 1080}, "number_of_slides": 10, "attachments": [ {"file_id": upload["id"], "role": "source", "label": "Q2 strategy"}, ], "idempotency_key": "q2-strategy-deck-v1", }).json() ``` ## Common wrong guesses * **Posting files as JSON-encoded base64 into `POST /v1/uploads`.** Use multipart (`multipart/form-data`). * **Pushing a >32 MiB file at `POST /v1/uploads` and reading the `413` as "the file is over Moda's limit".** The app cap is `max_file_bytes` from `GET /v1/uploads/limits`, at most 250 MB; that `413` is the gateway. Switch to the signed-URL flow. * **PUT-ing to `upload_url` with a different `Content-Type` than you declared on `/uploads/url`.** The signature is bound to the content type — a mismatch fails the PUT at storage. * **Calling `POST /v1/uploads/register` before the PUT finished, or after a signed URL expired without the bytes ever landing.** Both return `422` with "No blob found at storage\_key". Note the TTL bounds the **PUT** only — `POST /v1/uploads/register` does not check it, so once the blob is staged you can register whenever. A late register is never a reason to re-upload. * **Using the proxy URL (`/api/v2/images/ref/…`) as if it were stable public content.** It includes an auth hash; it's a stable reference for use in Moda-side operations, not a CDN URL. * **Re-uploading on every run when content hasn't changed.** Dedupe handles it server-side, but you still pay a roundtrip. Cache `file_id` in your app. * **Skipping `role` in the attachment.** It drops back to a generic "reference" semantic, which is usually not what you want. Always set `role`. * **Mixing `file_id` and `url` in one attachment item.** Pick one per item. Mix items within the array is fine. ## Upstream * [`docs.moda.app/api/uploads/uploadFile`](https://docs.moda.app/api/uploads/uploadFile) * [`docs.moda.app/api/uploads/uploadFromUrl`](https://docs.moda.app/api/uploads/uploadFromUrl) * [`docs.moda.app/api-reference/large-file-uploads`](https://docs.moda.app/api-reference/large-file-uploads) — the signed-URL flow in full # Versioning Source: https://docs.moda.app/.mintlify/skills/moda-api/references/versioning # Versioning Moda's API uses a calendar-dated version string on the `Moda-Version` request header. Pinning guarantees your wire shape stays stable. ## Supported versions | Version | Role | Status | Sunsets | | - | - | - | - | | `2026-05-01` | **Canonical** (newest) | Latest response shape | — | | `2026-04-12` | **Default** (legacy) | Current default for unpinned traffic | TBD (date to be re-announced) | * **Canonical** = routes emit this shape natively. Pin this in production. * **Default** = what unpinned requests get. Advances to the next-newest supported version on sunset dates. * **Sunset** = after this date, pinning the sunset version returns `400 unsupported_version`. ## Sending the header ``` Moda-Version: 2026-05-01 ``` Pin explicitly on every request. Don't rely on the default. ## Omitting If you omit the header, the server resolves to the current **default**. Integrations keep working across version bumps until a sunset advances the default. **For production, pin.** ## Unknown version ```json theme={null} { "error": { "type": "invalid_request", "code": "unsupported_version", "message": "Moda-Version '2026-01-01' is not supported. Supported versions: 2026-04-12, 2026-05-01.", "details": { "requested": "2026-01-01", "supported": ["2026-04-12", "2026-05-01"] }, "request_id": "019d8996-…" } } ``` Read `details.supported` — that's the ground truth, and it updates automatically. ## Response header Every response carries the resolved version: ``` HTTP/1.1 200 OK Moda-Version: 2026-05-01 ``` If you omit the request header, read the response's `Moda-Version` to know which shape you got. ## Canonical (`2026-05-01`) vs legacy (`2026-04-12`) ### Task endpoints **Legacy flat shape (`2026-04-12`):** ```json theme={null} { "job_id": "task_01HT9...", "status": "completed", "canvas_id": "cvs_...", "canvas_url": "https://...", "conversation_id": null, "task": "Create a sales deck", "progress_percent": 100, "is_terminal": true, "can_export": true, "retry_after_seconds": null, ... } ``` **Canonical Task envelope (`2026-05-01`):** ```json theme={null} { "id": "task_01HT9...", "kind": "design", "status": "succeeded", "input": { "prompt": "Create a sales deck" }, "result": { "canvas_id": "cvs_...", "canvas_url": "https://..." }, "progress": null, "error": null, "credits": { "credits_used": 5, "credits_remaining": 12 }, "links": { "self": "/v1/tasks/...", "cancel": null, "canvas": "..." }, "retry_after_ms": null } ``` Migration map: | Legacy | Canonical | | - | - | | `response.job_id` | `response.id` | | `response.status == "completed"` | `response.status == "succeeded"` | | `response.status == "cancelled"` | `response.status == "canceled"` | | `response.canvas_id` | `response.result.canvas_id` | | `response.canvas_url` | `response.result.canvas_url` | | `response.conversation_id` | `response.result.conversation_id` | | `response.task` | `response.input.prompt` | | `response.progress_percent` | `response.progress.percent` | | `response.current_step` | `response.progress.step` | | `response.error` (string) | `response.error.message` (object) | | `response.is_terminal` | derived: `status in ("succeeded","failed","canceled","expired")` | | `response.can_export` | derived: `status == "succeeded" && result.canvas_id` | | `response.retry_after_seconds` | `response.retry_after_ms / 1000` | ### List endpoints: offset → cursor **Legacy:** ```json theme={null} { "canvases": [...], "total": 123, "offset": 20, "limit": 20, "has_more": true } ``` **Canonical:** ```json theme={null} { "data": [...], "next_cursor": "eyJ2..." } ``` Iterate until `next_cursor === null`. See [`pagination.md`](./pagination.md). ### Webhook events Legacy `job.*` names are retired in favor of `task.*` / `export.*`. Spelling changed: `cancelled` → `canceled` (matches the `PublicTaskStatus.CANCELED` enum). Non-terminal states (`queued`, `running`, `expired`) no longer fire webhooks. | Legacy | Canonical | | - | - | | `job.completed` | `task.succeeded` | | `job.failed` | `task.failed` | | `job.cancelled` | `task.canceled` | | `job.dead_letter` | `task.failed` with `data.error.retryable: false` | | `job.running` | removed (poll `/v1/tasks/{id}`) | | `job.queued` | removed | ## What triggers a new version Only **breaking** response-shape changes. Additive changes (new endpoints, new optional params, new response fields) ship at the current canonical version without a bump. Breaking: * Removing / renaming a response field * Removing an endpoint or path * Changing a field's type * Tightening validation * Changing status vocabulary Additive (no bump): * New endpoint / path / optional param / response field * New error `code` within an existing `type` Tolerate unknown fields in your client. ## Version-bump cadence * New canonical arrives. * Previous default stays supported for a sunset window (usually 2–3 weeks). * On the sunset date, the older version retires; default advances. * If you pinned, you upgrade on your schedule. ## Recommendations * **Pin** `Moda-Version` explicitly on every production request. * **Log the response `Moda-Version`** so you can tell which shape your traffic is actually hitting. * **When you see `400 unsupported_version`**, read `details.supported` from the error. * **Subscribe to the Moda changelog** for sunset dates. ## Common wrong guesses * **Omitting `Moda-Version` in production.** The default will advance on sunset and your response shape will silently change. * **Parsing legacy `job_id` / `canvas_id` from canonical responses.** They're nested under `id` and `result.canvas_id`. * **Spelling `cancelled` with two Ls.** Canonical spelling is `canceled` (one L). `cancelled` is a legacy artifact. * **Assuming a sunset version still works.** After the sunset date, pinning it returns `400`. ## Upstream [`docs.moda.app/api/versioning`](https://docs.moda.app/api/versioning) # Webhooks Source: https://docs.moda.app/.mintlify/skills/moda-api/references/webhooks # Webhooks When you start a task with `POST /v1/tasks` or `POST /v1/remix`, pass a `callback_url` to receive an HTTPS POST when the task reaches terminal state. Webhooks fire **terminal-only** — there is no progress stream. ## Important auth restriction `callback_url` is **API-key-auth only**. OAuth callers (MCP sessions) get: ```json theme={null} { "error": { "type": "invalid_request", "code": "unsupported_auth", "message": "callback_url is only supported for API-key authenticated callers." } } ``` Use polling from OAuth clients. ## Event types Closed set. If your handler sees anything outside this list, it's a bug to report. | Event | Fires when | | - | - | | `task.succeeded` | Design or remix task finished successfully | | `task.failed` | Task failed (transient or dead-lettered — see `data.error.retryable`) | | `task.canceled` | Task was canceled (via `POST /v1/tasks/{id}/cancel` or app UI) | | `export.succeeded` | Declared for async canvas exports — **not emitted today** | | `export.failed` | Declared for async canvas exports — **not emitted today** | Non-terminal states (`queued`, `running`, `expired`) **do not** fire webhooks today. If you need running/progress beats, poll `GET /v1/tasks/{id}`. The two `export.*` types are part of the closed taxonomy but nothing emits them: an async export (`POST /v1/canvases/{id}/export` returning `status: "in_progress"`) is followed by polling `GET /v1/canvases/{id}/export-status?task_id=…`, not by a webhook. Handle the types defensively if you like — just don't wait on them. ## Payload ```json theme={null} { "id": "evt_01HT9WK8N3M2J4A5Z6P7Q8R9TV", "type": "task.succeeded", "created": "2026-04-15T12:01:00+00:00", "api_version": "2026-05-01", "data": { "id": "task_01HT9WK8N3M2J4A5Z6P7Q8R9TV", "kind": "design", "status": "succeeded", "result": { "canvas_id": "cvs_...", "canvas_url": "https://...", "export": { "status": "completed", "url": "https://...", "format": "pptx", "page_count": 12 } }, ... /* full canonical Task envelope */ } } ``` Fields: | Field | Notes | | - | - | | `id` | `evt_…` event ID. **Stable across retries of the same event** — use as your idempotency key. | | `type` | One of the event types above. | | `created` | ISO 8601 timestamp when the event was generated. | | `api_version` | The canonical Moda-Version of the `data` payload (currently `2026-05-01`). | | `data` | Full canonical Task envelope. Same shape as `GET /v1/tasks/{id}`. | For `task.failed` / `export.failed`, inspect `data.error.retryable` to distinguish transient from dead-lettered failures. On a `task.succeeded` event for a programmatic design task, `data.result.export` carries the **auto-exported** artifact (`{status, url, format, page_count}`) — the task renders an export of its result in the canvas's category-default format when it finishes. Use this URL directly instead of issuing a separate `POST /v1/canvases/{id}/export`. The field is absent when auto-export was disabled (`export_on_complete: {enabled: false}` on the task) or did not finish within the budget. ## Signature verification Every webhook POST includes two headers: | Header | Value | | - | - | | `X-Webhook-Signature` | `v1=` — HMAC-SHA256 | | `X-Webhook-Timestamp` | Unix seconds when the webhook was sent | Signature is computed over `{timestamp}.{raw_body}` using the **webhook signing secret** that was shown once in **Settings → Developer → REST API** when you created the API key. ### Node.js ```js theme={null} import crypto from "node:crypto"; function verifyWebhook(signingSecret, rawBody, sigHeader, tsHeader) { const message = `${tsHeader}.${rawBody}`; const expected = crypto.createHmac("sha256", signingSecret).update(message).digest("hex"); const received = sigHeader.replace(/^v1=/, ""); return crypto.timingSafeEqual( Buffer.from(expected, "hex"), Buffer.from(received, "hex"), ); } ``` ### Python ```python theme={null} import hashlib, hmac def verify_webhook(signing_secret: str, raw_body: bytes, sig_header: str, ts_header: str) -> bool: message = f"{ts_header}.{raw_body.decode()}" expected = hmac.new(signing_secret.encode(), message.encode(), hashlib.sha256).hexdigest() received = sig_header.removeprefix("v1=") return hmac.compare_digest(expected, received) ``` Use `timingSafeEqual` / `hmac.compare_digest` — not raw `==` — to avoid timing attacks. ## Replay protection Reject any webhook with an `X-Webhook-Timestamp` older than **5 minutes**. A valid recent signature could otherwise be replayed indefinitely. ```python theme={null} import time if abs(time.time() - int(ts_header)) > 300: # 5 minutes return 401 ``` ## Retry behavior Moda makes up to **3 delivery attempts** total (initial + 2 retries). If your endpoint returns a non-2xx status or doesn't respond within **30 seconds**, Moda retries with a short backoff: | Attempt | When | | - | - | | 1 (initial) | on task completion | | 2 (retry) | \~1s after attempt 1 fails | | 3 (final retry) | \~5s after attempt 2 fails | After the third attempt fails, the webhook is dropped. You can still fetch the task via `GET /v1/tasks/{id}`, or replay the dropped delivery from the delivery log (`POST /v1/webhook_deliveries/{id}/redeliver`) once your endpoint is fixed. ## Deduplication The event envelope `id` (`evt_…`) is **stable across retries of the same event**. Use it as your dedupe key: ```python theme={null} # pseudocode if processed_events.contains(event["id"]): return 200 # acknowledge; already handled processed_events.add(event["id"]) handle(event) return 200 ``` Retries of the *same* event carry the same `id`. Different events (e.g. `task.succeeded` for two different tasks) have different `id`s — they're not dedupe-collisions. ## Handler best practices 1. **Return 200 fast.** Process asynchronously — enqueue the event, don't do the work inline. Moda's 30s timeout will retry if you're slow. 2. **Verify signature before trusting the payload.** Even for non-sensitive work. 3. **Check the timestamp** (>5 min old → reject). 4. **Use `evt_…` as your idempotency key.** 5. **HTTPS only.** Moda rejects non-HTTPS callback URLs up front. 6. **Log `request_id`** from the task envelope inside `data` when reporting issues. ## End-to-end handler (Python + FastAPI) ```python theme={null} from fastapi import FastAPI, Header, HTTPException, Request import os, time, hashlib, hmac app = FastAPI() SECRET = os.environ["MODA_WEBHOOK_SECRET"] processed = set() # use Redis / DB in production @app.post("/webhooks/moda") async def moda_webhook( req: Request, x_webhook_signature: str = Header(...), x_webhook_timestamp: str = Header(...), ): body = await req.body() if abs(time.time() - int(x_webhook_timestamp)) > 300: raise HTTPException(401, "stale timestamp") expected = hmac.new( SECRET.encode(), f"{x_webhook_timestamp}.{body.decode()}".encode(), hashlib.sha256, ).hexdigest() received = x_webhook_signature.removeprefix("v1=") if not hmac.compare_digest(expected, received): raise HTTPException(401, "bad signature") event = await req.json() if event["id"] in processed: return {"ok": True} processed.add(event["id"]) # enqueue async; return 200 fast enqueue_task(event) return {"ok": True} ``` See [`../recipes/webhook-receiver.md`](../recipes/webhook-receiver.md) for both Node/Express and FastAPI worked examples with enqueue + retry plumbing. ## Common wrong guesses * **Using `callback_url` from an OAuth/MCP session.** Rejected. API-key auth only. * **Expecting `task.running` / `task.queued` events.** Terminal-only today. * **Using raw `==` to compare signatures.** Timing-attack risk. Use `hmac.compare_digest` / `crypto.timingSafeEqual`. * **Not verifying timestamp age.** Replayable. Reject >5 min. * **Doing work inside the handler.** 30s timeout will re-fire retries. Enqueue, then 200. * **Forgetting the signing secret.** It's shown once with the API key. Store it in your secret manager alongside the key. * **Handling retries as new events.** Same `evt_…` id → same event. Dedupe. ## Upstream * [`docs.moda.app/api/webhooks`](https://docs.moda.app/api/webhooks) * [`authentication.md`](./authentication.md) — where the signing secret comes from # Bulk variants Source: https://docs.moda.app/.mintlify/skills/moda-mcp/recipes/bulk-variants # Bulk variants **Problem:** The user wants several versions of a design — personalized per persona, per customer, per channel, per brand. Bulk is the workflow that breaks the most "make one design" assumptions in the rest of this skill, so read this in full before fanning out. There are **three** valid shapes. Pick based on what the user already has and what they want: | User situation | Pattern | | - | - | | "Make 10 LinkedIn ads, one per persona" — N independent designs from scratch | **A — fan out `start_design_task`** | | "Make 10 versions of *this* canvas" / "rebrand this template for each of our 5 clients" — N variants of a source canvas, with or without per-variant brand swap | **B — fan out `start_design_task` with `template_canvas_id`** (preserves structure; server auto-picks content-only remix vs full rebrand) | | "Multi-panel IG carousel" — one post with multiple linked panels | **C — single `start_design_task` with `format_category="carousel"`** | Carousel (Pattern C) page count clamps to the caller's plan tier, same as slides — see [`../references/gotchas.md#format-and-dimensions`](../references/gotchas.md#format-and-dimensions). The rest of this recipe is about A and B. ## The single biggest gotcha — concurrency caps `start_design_task` and `remix_design` share a **per-organization in-flight cap** (pooled across every team in the org, not per-team): | Plan | Max concurrent tasks | | - | - | | `free` / `free_beta` | 3 | | `paid` | 10 | | `ultra` / `enterprise` | 15 | Fan out N > cap and you'll get an `AgentJobRateLimitError` partway through — surfacing as a tool error from `start_design_task`. The skill's job is to never let the user see that error. Use a **windowed launch**: keep at most `cap` tasks in flight, slot in the next prompt every time one terminates. **Get the cap from `get_moda_bootstrap`** — its `concurrency_cap` field is the exact number for the user's plan. If you haven't called `get_moda_bootstrap` yet, default to **3** (safe everywhere) and bump up after the first batch confirms headroom. ## Pattern A — fan out `start_design_task` (N independent designs) Best when each variant has fundamentally different content: per-persona ad copy, per-customer pitch decks, per-region landing pages. There is no source canvas to preserve structure from. **User:** "Create 10 LinkedIn ads for our automation tool — each tailored to a different ICP persona: CFOs, CTOs, heads of ops, ..." **Agent** (after the gate, before fanning out): > Kicking off 10 LinkedIn ads, one per persona. I'll run them in batches of 3 (concurrency cap) and post each canvas URL as soon as it's ready — you can open them while the others are still rendering. ```python theme={null} personas = ["CFOs", "CTOs", "heads of ops", ...] # the user-provided list dimensions = dict(format_category="social", format_width=1080, format_height=1080, brand_kit_id=chosen_brand_kit_id) # asked once, before the loop (see notes) window = bootstrap_response.get("concurrency_cap", 3) # use the bootstrap value; fall back to 3 if unknown def build_prompt(persona): return f""" LinkedIn ad for our automation tool, tailored to {persona}. Lead with the single pain point this persona feels most acutely and the one metric they measure success on. Bold typography, clean layout, one CTA. """ in_flight = {} # persona -> task handle done = {} # persona -> terminal status queue = list(personas) # to-do # 1. Seed the window while len(in_flight) < window and queue: p = queue.pop(0) in_flight[p] = start_design_task(prompt=build_prompt(p), **dimensions) # tell the user immediately — canvas_url is in the queued response post(f"Started {p}: {in_flight[p]['canvas_url']}") # 2. Drain + refill while in_flight: # poll the whole pool in one call — cheaper than N get_task_status calls. # This is a pre-filter only: a task absent from the "running" list is NOT # necessarily terminal — it may still be "queued" (hasn't started yet) or # briefly missing from this page. Confirm with get_task_status before # ever removing a slot; never trust absence-from-pool by itself. pool = list_tasks(status="running", limit=window * 2) pool_ids = {t["task_id"] for t in pool["tasks"]} for persona, handle in list(in_flight.items()): if handle["task_id"] in pool_ids: continue # confirmed still running # Not in the running pool — could be terminal, or still "queued". # is_terminal is the only thing allowed to free this slot. s = get_task_status(task_id=handle["task_id"]) if not s.get("is_terminal"): continue # e.g. still queued — leave the slot occupied done[persona] = s del in_flight[persona] post_done(persona, s) # deliver this one as it finishes if queue: p = queue.pop(0) in_flight[p] = start_design_task(prompt=build_prompt(p), **dimensions) post(f"Started {p}: {in_flight[p]['canvas_url']}") sleep(3) # respect retry_after_seconds from any poll ``` Notes on the loop: * **Never free a slot on absence-from-pool alone.** `list_tasks(status="running", ...)` is a cheap pre-filter, not the correctness check — a task can be missing from it while still "queued" (not yet running) rather than terminal. Only `get_task_status(...)["is_terminal"] == true` may remove a handle from `in_flight` and launch its replacement; skipping this check overruns the concurrency window the whole recipe exists to respect. * `list_tasks(status="running", ...)` is one RPC for the whole pool. Beats `get_task_status` × N per tick. * **Post each canvas URL when the task is queued**, not when it finishes. The user can open it immediately — they'll see the agent's progress in the canvas itself. * **Deliver each result as it terminates.** Bulk feels much faster when 1/10 done shows up in 90s than when all 10 land together at 8 min. * `post_done(persona, s)` surfaces `s["error"]` if the task failed. Don't let one bad persona block the rest. ### What goes in the prompt vs the parameters * **Per-persona detail belongs in the prompt** — rewrite the pain point, metric, and CTA for each. Don't just template `{persona}` into a generic sentence. * **Dimensions and `format_category` stay constant** across the batch. They're parameters. * **One brand kit for all** unless the user says otherwise. Settle it once before the loop — ask the user which kit (one of theirs via `list_brand_kits`, a new one, or none; new designs without a choice are refused with `brand_kit_choice_required`) — then pass that same `brand_kit_id` (or `skip_brand_kit=true`) on every call. Don't fetch the kit per task. ## Pattern B — fan out `start_design_task` with `template_canvas_id` (N variants of a source canvas) Best when the user has an existing canvas they're happy with and wants variations *of that design* — same structure, different copy, different brand. The server copies the source, applies the resolved brand kit on the copy, then runs the agent against the copy. The original is never touched. Skill selection is automatic from brand-kit comparison: * Same brand kit as the source → content-only remix (preserve design, swap content) * Different `brand_kit_id` → full rebrand (rework colors, fonts, copy, imagery) * `skip_brand_kit=True` → no forced skill; the curator decides **User:** "I love this product flyer — make me 5 versions, one for each of these resellers: \[list]. Same layout, swap the logo and the regional pricing." ```python theme={null} source_id = "cvs_…" # the flyer canvas the user pointed at resellers = [...] # 5 items, each with optional brand_kit_id for per-client rebrand window = 3 queue = list(resellers) in_flight = {} def build_prompt(reseller): return f""" Customize this flyer for {reseller['name']}: - replace the headline price with {reseller['price']} - update the contact strip with {reseller['phone']} / {reseller['email']} """ while len(in_flight) < window and queue: r = queue.pop(0) in_flight[r["name"]] = start_design_task( template_canvas_id=source_id, prompt=build_prompt(r), brand_kit_id=r.get("brand_kit_id"), # per-client brand if rebranding; omit for same-brand fill canvas_name=f"Flyer — {r['name']}", # wait defaults to False on start_design_task — handle returned immediately ) post(f"Started {r['name']}: {in_flight[r['name']]['canvas_url']}") # Same drain + refill loop as Pattern A ``` Why `template_canvas_id` over `start_design_task(canvas_id=source_id, ...)`: * **`canvas_id` edits the original.** Five resellers, one canvas — the last one wins. The user loses their template. * **`template_canvas_id` duplicates first.** Original stays clean; you get N independent copies. * **Layout / structure carry forward automatically.** You only specify what changes in the prompt. * **Per-variant brand swap is first-class.** Pass a different `brand_kit_id` per call to produce the same design rebranded for each client. **Note:** `template_canvas_id` is mutually exclusive with both `canvas_id` and `conversation_id` — passing either combination raises a tool error. See [`../references/gotchas.md#conversations-vs-canvases-vs-remixes`](../references/gotchas.md#conversations-vs-canvases-vs-remixes) for the full matrix. ### When to use `remix_design` instead `remix_design(canvas_id=…)` without a prompt is a **synchronous plain duplicate** — useful when the user just wants a copy they'll edit themselves. With a prompt, it's an older async path that pre-dates `template_canvas_id`; prefer `template_canvas_id` for new bulk flows (cleaner brand-kit handling, automatic skill selection, no `wait` default asymmetry). ## Recovery: a task in the batch fails `get_task_status` returns `{status: "failed", error: "…"}` for that task. Common cases: * **Rate limit** (`AgentJobRateLimitError` text in `error`) — your window is too wide. Drop it by one, retry that persona/reseller. * **Billing** (out of credits) — stop the whole batch. Tell the user; the remaining queued items would all fail the same way. * **Validation** — bad prompt or parameters for that one task. Skip it, continue with the rest. * **Upstream model error** — retry that one task once. If it fails again, skip. Don't silently retry on `failed` unless you specifically know the error is transient. Surface the persona/reseller that failed so the user can decide. ## Aborting a bulk run mid-flight If the user changes their mind ("never mind, kill them") or you spot a systemic issue (every task failing the same way), call `cancel_task(task_id)` on each in-flight handle. Already-terminal tasks are no-ops. ## See also * [`../references/gotchas.md`](../references/gotchas.md) — `wait` asymmetry, concurrency caps, format defaults, carousel page-count tier clamp, `not_ready` retry, and the rest of the silent-fail set # Create new design Source: https://docs.moda.app/.mintlify/skills/moda-mcp/recipes/create-new-design # Create a new design **When to use:** The user wants something built from scratch — no source canvas, no template. "Make me a deck", "create a LinkedIn post", "generate a one-pager". ## Tool call ```python theme={null} start_design_task( prompt="…", format_category="slides", # required for non-slide intents format_width=1920, # explicit dimensions for predictable output format_height=1080, brand_kit_id="bk_…", # the kit the USER chose — see "Which brand kit?" below ) ``` ## Decisions before the call | Question | How to answer | | - | - | | What is the user making? | Set `format_category` explicitly: `slides`, `social`, `carousel`, `pdf`, `diagram`, `ui`, `animation`, `prints`, `web-ads`, `other`. Omit it and you get a generic `other` canvas at 1080×1080 with no format skill, so pass the real format. | | How many slides / panels? | State it in the prompt text ("10-slide deck"). No `number_of_slides` MCP parameter. For carousels use `carousel_page_count` (clamps to your plan tier, same as slides). | | Which brand kit? | No `session.brand_kit_id`: ask the user and **wait for the answer** before this call, whatever `brand_kit_count` is — offer their kits (`list_brand_kits` shows them), a new kit (`create_brand_kit(url=…)` if they want one), or none. Don't pick for them; neither the team default nor a team's only kit is an answer. Pass their pick as `brand_kit_id`, or `skip_brand_kit=true` if they want no brand. A kit (or "no brand") they already named (chat, project instructions, memory) counts — pass it. Skipping this is refused with `brand_kit_choice_required`, which lists the kits and creates nothing. | | Are there reference materials? | Upload via `upload_file(source_url=…)` and pass `{file_id, role: "source"\|"reference"\|"asset"\|"import"}` in `attachments`. (`import` is PPTX-only — it loads the deck as editable slides into a new canvas **at the deck's own page size**, so the `format_width`/`format_height` above do not apply: send only `format_category="slides"` with it, or no format at all. Any other format field alongside an `import` is a 422, not a silent fallback.) For existing canvases as inspiration, use `reference_canvas_ids`. | ## Returns Task handle in milliseconds — `task_id`, `canvas_id`, `canvas_url`, `conversation_id`, `status: "queued"`. Poll `get_task_status(task_id)` at `retry_after_seconds` until `is_terminal == true`. The succeeded task already carries the finished design **as a rendered file** at `result.export` — `{url, format, status, page_count}`, exported in the canvas's category-default format. Hand that `url` to the user directly. Only call `export_canvas(canvas_id=…, format=…)` when they need a *different* format or a specific page. ## See also * [`../references/gotchas.md#format-and-dimensions`](../references/gotchas.md#format-and-dimensions) — `format_category` defaults, carousel page-count tier clamp, slide-count placement * [`edit-existing-canvas.md`](./edit-existing-canvas.md) — when the user has an existing canvas to modify * [`fill-template.md`](./fill-template.md) — when there's a source canvas to copy + customize # Edit existing canvas Source: https://docs.moda.app/.mintlify/skills/moda-mcp/recipes/edit-existing-canvas # Edit an existing canvas **When to use:** The user wants to modify a canvas they already have, in place. "Add a footer to my deck", "change the headline on slide 2", "fix the date in the resume". The original canvas is mutated. ## Tool call ```python theme={null} start_design_task( canvas_id="cvs_…", prompt="…", # format_category, dimensions, brand_kit are inferred from the existing canvas ) ``` ## Destructive — call this out to the user `canvas_id` mutates the source canvas. Five edits → five revisions of the same canvas. If the user wants variations of the canvas while keeping the original clean, use [`fill-template.md`](./fill-template.md) or [`rebrand-template.md`](./rebrand-template.md) instead. ## Mutually exclusive `canvas_id`, `template_canvas_id`, and `conversation_id` cannot be combined. * `canvas_id` + `template_canvas_id` → tool error. * `template_canvas_id` + `conversation_id` → tool error. * `canvas_id` + `conversation_id` → no error, but `canvas_id` is **silently ignored**. The agent uses the conversation's canvas. ## Iterating in conversation For follow-up tweaks ("now make the title bigger", "add a third bullet") on the same canvas, pass `conversation_id` from the previous response instead of `canvas_id`. The agent keeps full context of prior turns. ```python theme={null} # turn 2: tweak slide 1 start_design_task( prompt="Make the title on slide 1 about 30% larger.", conversation_id=prior_response["conversation_id"], ) ``` ## See also * [`create-new-design.md`](./create-new-design.md) — start from scratch instead * [`fill-template.md`](./fill-template.md) — produce a new canvas that mirrors the source structure * [`../references/gotchas.md#conversations-vs-canvases-vs-remixes`](../references/gotchas.md#conversations-vs-canvases-vs-remixes) — full mutual-exclusion matrix # Fill template Source: https://docs.moda.app/.mintlify/skills/moda-mcp/recipes/fill-template # Fill a template (content remix, same brand) **When to use:** The user has a source canvas they like — usually a designed template — and wants a new canvas that **keeps the structure and styling** but swaps in new content. "Make this for our Q3 launch", "fill this template with our customer story". The original canvas is preserved. ## Tool call ```python theme={null} start_design_task( template_canvas_id="cvs_…", # the source canvas to copy prompt="Fill this template for Acme's Q3 launch. Replace the headline with…", # brand_kit_id omitted → the source canvas's brand kit applies on the copy. # That's what triggers the "within-team-remix" skill: content swap, not rebrand. ) ``` ## What the server does The server: 1. Copies the source canvas into the caller's team (original untouched). 2. Applies the resolved brand kit to the copy. When it **matches** the source's brand kit (or is omitted with no session preference, so the source's kit is preserved), the agent runs the `within-team-remix` skill — content-only changes. 3. Returns a task handle for the new canvas. Poll `get_task_status` as usual. ## Source canvas access The source must be readable by the caller's team. `template_canvas_id` accepts **any** canvas the team can read — it doesn't need to be flagged as a template type. ## Mutually exclusive `template_canvas_id` is mutually exclusive with both `canvas_id` and `conversation_id`. Passing either combination raises a tool error. ## Prompt notes The agent reads the prompt as a content-edit brief over the existing layout. Be specific about what to replace (headline, body, image, data) and what to keep. If the prompt asks for a rebrand ("change everything to dark mode") you actually want [`rebrand-template.md`](./rebrand-template.md) — pass a different `brand_kit_id`. The selector is the **brand kit, not the prompt wording**. Omitting `brand_kit_id` (or passing the source's) is what picks the content-only path; adding "keep the existing colors" to the prompt buys nothing. Conversely, writing "rebrand this" into the prompt does *not* trigger a rebrand when the kit matches — pass a different `brand_kit_id` ([`rebrand-template.md`](./rebrand-template.md)). ## See also * [`find-a-template.md`](./find-a-template.md) — how to find a template and the three-rule contract for its built-in instructions * [`rebrand-template.md`](./rebrand-template.md) — same workflow but pass a different `brand_kit_id` to drive a full rebrand * [`bulk-variants.md`](./bulk-variants.md) — Pattern B uses `template_canvas_id` to fan out N variants * [`../references/gotchas.md#conversations-vs-canvases-vs-remixes`](../references/gotchas.md#conversations-vs-canvases-vs-remixes) — when to fill a template vs edit in place vs iterate in conversation # Find a template Source: https://docs.moda.app/.mintlify/skills/moda-mcp/recipes/find-a-template # Find a template (and the rules it carries) **When to use:** Before filling or rebranding a template ([`fill-template.md`](./fill-template.md), [`rebrand-template.md`](./rebrand-template.md)), or whenever the user says "template", "theme", or "use one of our decks as a starting point" and you don't already have a `canvas_id` in hand. ## Templates vs themes | `template_type` | What it is | Format | | - | - | - | | `template` | A finished design meant to be copied and refilled with new content — a deck, a social post, a one-pager, anything. | Any format | | `theme` | A slides-only canvas supplying reusable page layouts, attached to a brand kit's `default_theme_canvas_id` and auto-applied to fresh slide decks made under that kit. | Always `slides` | If a user says "template" loosely and means a deck or a post, they mean `template` — `theme` is the narrower, slides-only, brand-kit-attached concept. Don't reach for it unless the user is specifically talking about layouts a brand kit applies automatically. ## Finding one Two lanes, same filters — pick by who the results are for: ```python theme={null} # The user should see and pick — renders the visual gallery list_my_canvases(query="pitch deck", template_type="template", limit=20) # You just need a template_canvas_id for the next call — JSON only, no gallery search_canvases(query="pitch deck", template_type="template", limit=10) ``` * Drop `query` from `list_my_canvases` and `template_type` alone browses the team's curated templates/themes **by recency** — useful when the user just wants to see what's available, with no search term yet. * An empty result means the team curated none. **Say so** — don't presciently offer an ordinary canvas as if it were a template. * Any readable canvas works as `start_design_task`'s `template_canvas_id` — the `template_type` filter only narrows discovery down to the ones the team deliberately curated for this purpose. ## The built-in instructions — aware, don't restate The design agent **already receives** a template's author-written instructions automatically once you pass it as `template_canvas_id` — they travel onto the remix copy and are hydrated into the agent's turn prompt server-side. This gives three rules for the `prompt` you write: 1. **Never copy a template's instructions into `prompt`.** They travel automatically. A paraphrase ("never modify the title slide" → "keep it roughly as-is") creates a weaker, drifting duplicate in the more heavily-weighted user turn. 2. **Never write a prompt that asks for something the template forbids.** Read the row's `guidance` (below) before drafting. 3. **On a genuine conflict, ask the user — don't pick a side.** Locked nodes/pages are a hard constraint; everything else is author-intent vs user-request with **no defined winner at runtime**. Do not invent or publish a precedence rule the runtime doesn't implement. Worked example — the user asks for something the template's guidance forbids: > This template says "Never modify the title slide," but you asked for a new hero there. Want me to leave it alone, or start from a different template? The one exception: if the user explicitly overrides after being asked, state the override plainly in the prompt (e.g. "the user asked to replace the title slide despite the template's note — do it"). That's the only case the prompt should mention a template rule at all. ## Reading `guidance` on a search/list row A canvas with author-pinned instructions carries a `guidance` object: ```json theme={null} {"agent_instructions": "…", "agent_instructions_truncated": true, "pinned_note_count": 4} ``` `pinned_note_count > 0` means there's additional per-element guidance (pinned notes on specific nodes/pages) you can't see from this row — you don't need to fetch it yourself, the agent will read and follow it once it runs against the copy. Just know it's there: don't assume a template with `pinned_note_count: 0` is unconstrained if `agent_instructions` is also present, and don't assume a template is safe to freely rewrite just because `guidance` is absent from the row (a canvas with no authored instructions has no `guidance` key at all — that's the "no constraints" case, not an omission). ## See also * [`fill-template.md`](./fill-template.md) — content-only remix, same brand * [`rebrand-template.md`](./rebrand-template.md) — full rebrand on copy, different brand kit * [`../references/gotchas.md#templates-and-themes`](../references/gotchas.md#templates-and-themes) — the compressed reference version of this page # Rebrand template Source: https://docs.moda.app/.mintlify/skills/moda-mcp/recipes/rebrand-template # Rebrand a template (full rebrand on copy) **When to use:** The user has a source canvas they like and wants a new canvas with a **different brand applied** — different colors, different fonts, different logos. Common for agencies producing the same layout for multiple clients. The original canvas is preserved. ## Tool call ```python theme={null} start_design_task( template_canvas_id="cvs_…", # the source design to remix brand_kit_id="bk_…", # the new brand kit — different from the source's prompt="Rebuild this deck as Acme's Series A pitch — swap the metrics on slides 4-6 for Acme's numbers and rewrite the customer quotes.", ) ``` ## What the server does The server: 1. Copies the source canvas into the caller's team (original untouched). 2. Applies the new `brand_kit_id` to the copy. 3. Because the resolved kit **differs from the source's**, the agent runs the `template-remix` skill — full rebrand (palette, typography, hero imagery), not just content swap — and it does not need the prompt to ask for it. 4. Returns a task handle. Poll `get_task_status` as usual. ## Don't ask for the rebrand in the prompt The rebrand is implicit and automatic. Passing a `brand_kit_id` that differs from the source canvas's kit **is** the rebrand request — the server force-bundles the `template-remix` skill, which instructs the agent to read your prompt as describing only the content theme and to swap colors, fonts, logos, and hero imagery regardless of what the prompt says. Write the prompt as a **content brief only**: * Good: `"Rebuild this deck as Acme's Series A pitch — swap the metrics on slides 4-6 for Acme's numbers and rewrite the customer quotes."` * Bad: `"Rebrand for Acme. Update colors, fonts, and imagery to the new brand kit."` The bad version isn't merely redundant. Restating styling in the prompt fights the resolved brand kit ([`../references/gotchas.md#brand-kits`](../references/gotchas.md#brand-kits)), and it re-opens the content-only reading of the prompt that the server-side skill exists to close. The one thing worth putting in the prompt is a *deviation* the user asked for ("keep the dark background even though the kit is light"). ## Picking the new `brand_kit_id` * If `get_moda_bootstrap` returned `brand_kit_count > 1`, you may already have the right id in hand from a recent `find_brand_kits` call or session preference. Use it. * If the user named the target brand, resolve it with `find_brand_kits(query=…)` (JSON-only). If they haven't said which kit, show `list_brand_kits` and ask — don't pick the target brand for them. ## Mutually exclusive `template_canvas_id` is mutually exclusive with both `canvas_id` and `conversation_id`. ## Bulk variant — different brand per output For "produce N rebranded variants, one per client", iterate `start_design_task` calls with the same `template_canvas_id` and a different `brand_kit_id` each call. Pattern B of [`bulk-variants.md`](./bulk-variants.md) covers the windowed-launch shape. ## See also * [`find-a-template.md`](./find-a-template.md) — how to find a template and the three-rule contract for its built-in instructions * [`fill-template.md`](./fill-template.md) — same workflow but keep the source's brand (content-only remix) * [`bulk-variants.md`](./bulk-variants.md) — fan out rebrands across multiple brand kits * [`../references/gotchas.md#brand-kits`](../references/gotchas.md#brand-kits) — brand-kit resolution order, `find_` vs `list_` distinction # Gotchas Source: https://docs.moda.app/.mintlify/skills/moda-mcp/references/gotchas # Gotchas The MCP surface has several behaviors that won't show up in tool signatures. This page is the one-stop reference for the silent-fail / surprising-behavior set. ## Format and dimensions **Set `format_category` explicitly on `start_design_task`.** If you omit it, a fresh canvas (which has no dimensions to infer a format from) is created as a generic `other` canvas at 1080×1080 with no format skill — so a deck, post, or document gets a generic layout. Pass one of: | User wants | `format_category` | Also pass | | - | - | - | | Pitch deck, presentation | `slides` | typical `format_width=1920`, `format_height=1080` | | Single Instagram / LinkedIn / Twitter / banner | `social` | platform-specific `format_width`/`format_height` | | Instagram or LinkedIn **carousel** post | `carousel` | `carousel_dimensions` (`square`/`linkedin`/`portrait`) + optional `carousel_page_count` | | PDF report, resume, one-pager | `pdf` | | | Flowchart, org chart, process diagram | `diagram` | | | UI mockup, screen, wireframe | `ui` | `format_width`/`format_height` | | Animated video, motion graphic | `animation` | `format_width`/`format_height` | | Poster, flyer, business card, brochure | `prints` | `format_width`/`format_height` | | Display ad, banner ad (IAB sizes) | `web-ads` | `format_width`/`format_height` | | Infographic, anything else | `other` | `format_width`/`format_height` | This is the full category enum — the same 10 values as `moda_mcp/server.py`'s `start_design_task` `format_category` docstring. **Slide count goes in the prompt text**, not a parameter. Say "10-slide deck" in the prompt. The REST API has `number_of_slides`; the MCP server does not expose it. **Carousel page count clamps to your plan tier**, the same limit slides use (free=10, paid=30, ultra/enterprise=100) — there's no separate, lower carousel-specific cap. Pass `carousel_page_count` explicitly or omit it for a default target. **`model_tier="pro_max"`** is silently coerced to `pro`. Pass `pro` directly. ## Task lifecycle **`start_design_task` defaults to `wait=False`** — returns a task handle (`task_id`, `canvas_id`, `canvas_url`, `conversation_id`, `status: "queued"`) in milliseconds. Poll `get_task_status(task_id)` at `retry_after_seconds` (\~3s) until `is_terminal == true`. Call `export_canvas` only when `can_export == true`. **`remix_design` defaults to `wait=True`** — opposite of `start_design_task`. With a prompt, it blocks until the agent finishes. For bulk fan-out, **pass `wait=False` explicitly** or each call serializes. **Terminal statuses**: `completed`, `failed`, `cancelled`, `dead_letter`, `canvas_deleted` (source canvas was deleted mid-run), `insufficient_credits` (billing block). Don't pattern-match this list yourself — just check the `is_terminal` field on the task/response; it's derived from the full terminal set and stays correct even if this set grows. **Cancellation**: `cancel_task(task_id)`. No-op on already-terminal tasks. Cancelling a blocking MCP call publishes the cancel signal internally — billing stops with the job. **Failed tasks are deterministic**. Don't silently retry on `{status: "failed"}` — surface the `error` to the user. The exception is upstream model errors, which are sometimes transient (retry once). ## Conversations vs canvases vs remixes | User intent | Use | | - | - | | Iterate on the same design ("make the headline bigger") | `start_design_task(prompt=…, conversation_id=…)` — agent has full prior context | | Edit an existing canvas in place ("add a footer to my deck") | `start_design_task(prompt=…, canvas_id=…)` — destructive, modifies the canvas | | Fork a canvas with variations, especially across brand kits ("make a version of this for each client") | `start_design_task(prompt=…, template_canvas_id=…, brand_kit_id=…)` — duplicates first; server auto-picks content-only remix vs full rebrand from brand-kit comparison; original preserved | | Duplicate now, optional agent pass | `remix_design(canvas_id=…)` — single call, synchronous by default; pass `prompt` to also queue a design task on the copy | **Mutual-exclusion matrix on `start_design_task`:** | Combo | Behavior | | - | - | | `canvas_id` + `template_canvas_id` | Tool error | | `template_canvas_id` + `conversation_id` | Tool error | | `canvas_id` + `conversation_id` | No error — `canvas_id` is silently ignored; the agent uses the conversation's canvas | The asymmetry is intentional: `conversation_id` always wins over `canvas_id` (older quirk, predates `template_canvas_id`), but `template_canvas_id` is strict because it changes the operation shape (source-copy-then-run vs in-place edit / resume). ## Templates and themes | `template_type` | What it is | Format | | - | - | - | | `template` | A finished design meant to be copied and refilled with new content. | Any format | | `theme` | A slides-only canvas of reusable page layouts, attached via a brand kit's `default_theme_canvas_id`. | Always `slides` | **Discovery filters on `list_my_canvases` / `search_canvases`:** `template_type` ('template' or 'theme') filters to only that kind; `exclude_templates=true` returns only regular canvases (mutually exclusive with `template_type`); `category` narrows further by format. `template_type='theme'` plus a non-`slides` `category` is a valid, knowably-empty query, not an error. On `list_my_canvases`, `query` is optional — omit it (or pass an empty one) and `template_type` alone browses the team's curated set by recency. An empty result means the team curated none — say so, don't present an ordinary canvas as a template. Any readable canvas still works as `start_design_task`'s `template_canvas_id`; the filters only narrow *discovery*, not what's eligible to remix. See [`../recipes/find-a-template.md`](../recipes/find-a-template.md). **`list_my_canvases` when the user should see the canvases; `search_canvases` when only you need the id.** Both take the same `query` + filters and return the same rows, but only `list_my_canvases` renders the gallery iframe — call it (optionally pre-filtered with `query`) when the user asked to see, browse, or pick a canvas, and `search_canvases` when you're resolving a `canvas_id` / `template_canvas_id` for your own next call. Same split as `list_brand_kits` vs `find_brand_kits` below. **The `guidance` field:** a row carries `{"agent_instructions": "…", "agent_instructions_truncated": true, "pinned_note_count": 4}` when the canvas's author pinned agent instructions or locked pages — emitted for any canvas with authored instructions, not just templates. Truncated at 500 chars. **The three-rule contract, aware-don't-restate:** a `template_canvas_id` remix's author-pinned instructions and locks travel onto the copy and reach the design agent automatically. So (1) never copy them into `prompt` — a paraphrase there creates a weaker, drifting duplicate; (2) never write a prompt that asks for something they forbid; (3) on a genuine conflict, ask the user rather than picking a side — locked nodes/pages are a hard constraint, but everything else is author-intent vs user-request with no defined runtime winner. ## Brand kits **`list_brand_kits` to show the user a choice; `find_brand_kits` for your own lookups.** Both return the same data, but `list_brand_kits` renders a visual showcase iframe on **every** call (per the MCP Apps spec, iframe rendering is decided at tool-listing time and can't be suppressed per-call) — that is the picker to show when the user must choose a kit. When you're resolving the id of a kit the user already named, use `find_brand_kits` — it's JSON-only and doesn't steal screen real estate. Both take an optional `query` that filters by kit name (title or company name), so you can go straight to `find_brand_kits(query="Acme")` instead of fetching every kit and matching client-side. **New designs need the user's brand choice.** For `start_design_task` with no `canvas_id` / `conversation_id` / `template_canvas_id`, a brand choice is an explicit `brand_kit_id`, `skip_brand_kit=true`, or a session pin. Without one it is refused with `brand_kit_choice_required` before anything is created — **whatever the kit count, even with a team default or a single kit**. Ask the user: one of their kits (show `list_brand_kits`), a new kit (`create_brand_kit`, if they want one), or none (`skip_brand_kit=true`). Wait for the answer, then retry. A kit named in the project instructions or memory counts as the choice. **Resolution order once a choice exists (and for edits / remixes):** 1. Explicit `brand_kit_id` parameter (highest priority) 2. Session preference (`set_session_brand_kit`, or the showcase iframe's "Use for this session" button) 3. Edits and remixes: the source canvas's own kit, then the team default brand kit 4. None (only when `skip_brand_kit=true` is set) **Don't restate brand colors / fonts / logos in the prompt** when a kit applies — it fights the kit. **The brand kit — not the prompt — selects rebrand vs content-swap.** On `start_design_task(template_canvas_id=…)`, a `brand_kit_id` that differs from the source's makes the server force-bundle the full-rebrand skill; a matching (or omitted) kit makes it content-only. The prompt does not need to ask for the rebrand and should not — write it as a content brief. **`set_context` clears the session brand kit.** Kits are team-scoped; a kit pinned on Team A is meaningless on Team B. **`set_session_brand_kit` is session-only.** It does NOT touch the team default. To change the team default, use `set_default_brand_kit` — destructive, only call on explicit user request. **Ask the user when the team has multiple kits** and `get_moda_bootstrap` shows no session preference. Silently falling back to the default isn't always what they want. **`import_brand_kit_from_fig` is async and NOT task-registry-backed.** Unlike `start_design_task`/`remix_design`, it does not appear in `get_task_status` or `list_tasks` — it returns a `job_id` immediately and you poll the companion `get_fig_import_status(job_id)` tool instead (same Redis-backed job the web app's progress UI reads, so a job started here is visible there and vice versa). The user must have exported the file from Figma via File → Save local copy… first, then uploaded it via `create_upload_url` → `register_uploaded_file` (`.fig` is an allowed upload MIME type) to get the `file_id`. Omitting `brand_kit_id` creates a new kit; passing one merges additively (re-importing the same file adds nothing — colors/fonts are deduped against what's already there). There is no feature flag to check — the tool is always available even though the `.fig` option is gated in the web UI. **First kit per team becomes default automatically.** To promote a different kit later as the *team* default, use `set_default_brand_kit(brand_kit_id)`. ## Attachments **Two shapes:** * File-id form (preferred): `{file_id, role, label?}` — carries `role` ∈ `source` / `reference` / `asset` / `import` that changes agent behavior * URL form (legacy, public URLs only): `{url, name?, type?}` — drops role metadata **Roles change behavior:** * `source` — extract content from this file (use its text/data — e.g. a brief PDF, meeting notes) * `reference` — emulate this file's style (don't copy content — e.g. a screenshot of a design you like) * `asset` — drop the file in verbatim (e.g. a logo, hero image) — currently a hint rather than a hard guarantee (behavior still evolving per ENG-2549) * `import` — PPTX-only: converts a PowerPoint attachment into editable canvas slides. It always creates a *new* slides canvas, so it can't be combined with `canvas_id`, `conversation_id`, or `template_canvas_id`, needs the file-id form (not the URL form), allows at most one `import` attachment, and requires `format_category` to be `slides` or omitted. The deck also sets its own page size, so every OTHER format field is rejected too — `format_width`, `format_height`, `carousel_dimensions`, `carousel_page_count`: omit them on an import (the table above is for FRESH canvases). Violating any of those is a `422 invalid_attachment_role`, not a silent fallback. Passing a logo as `reference` makes the agent emulate its style instead of placing it. Passing a brief as `reference` makes the agent mimic its formatting instead of using its content. **Don't confuse this with the brand-kit-image role enum.** `add_brand_kit_image(role=…)` uses a different (overlapping but distinct) set: `logo` / `reference` / `asset`. `logo` belongs to brand-kit images only; `source` belongs to design-task attachments only. **Two upload paths:** * `upload_file(source_url=…)` — one call, when the file is already at a public URL. Content-hash deduplicated. * `create_upload_url` → PUT bytes to the returned `upload_url` → `register_uploaded_file(storage_key, …)` — three steps, when the file is local with no public URL. **The `create_upload_url` PUT goes to `mcp.moda.app`.** The `upload_url` it returns is on the Moda MCP host itself (`https://mcp.moda.app/uploads/proxy?token=…`) — not a Google Cloud Storage URL. That's deliberate: it's the same host the MCP connector already talks to, so sandboxed clients with a network egress allow-list don't need a separate rule. If a hardened client *does* block the out-of-band PUT, the one host to allow is `mcp.moda.app` — never all of `storage.googleapis.com`. For existing Moda canvases as inspiration, don't upload a screenshot — pass `reference_canvas_ids=[cvs_…]` directly. The agent sees the structure natively. ## Concurrency caps (bulk fan-out) Per-organization in-flight cap on `start_design_task` + `remix_design` (shared across every team in the org — a two-team org on `paid` has one pool of 10 slots between both teams, not 10 each): | Plan | Max concurrent tasks | | - | - | | `free` / `free_beta` | 3 | | `paid` | 10 | | `ultra` / `enterprise` | 15 | Exceeding the cap surfaces as a tool error on the call that puts you over. Use a windowed launch — keep at most `cap` tasks in flight; slot in the next as each terminates. Default the window to 3 when the plan is unknown. See [`../recipes/bulk-variants.md`](../recipes/bulk-variants.md) for the pattern. ## Exports **A finished design task already includes its export — don't re-export.** A completed `start_design_task` / `remix_design` carries `result.export` (`{url, format, status, page_count}`) — the design rendered to a file in the canvas's category-default format. Read that. Calling `export_canvas` for the same just-finished canvas re-does work the task already did; only call it for a *different* format or page, or for a canvas that wasn't just produced by a task. **`export_canvas` returns `{status: "not_ready", reason, retry_after_seconds}`** while a design task is still running on the canvas. **Not an error** — retry after `retry_after_seconds`. Reasons: `active_design_job` (most common), `job_status_unavailable` (transient). **Large multi-page PDFs/PPTX** can exceed the \~20s sync wait budget and return `{status: "in_progress", task_id}`. Poll `get_export_status(task_id)` for the URL. Export task records are kept \~1 hour. **Signed export URLs expire after 7 days.** **Image vs document defaults**: PDF / PPTX default to all pages. PNG / JPEG with `page_number` omitted on a multi-page canvas bundle **all pages into a `.zip`** (not just page 1) — pass `page_number` explicitly to get a single raw image. ## Session context (multi-org users) Session context (org + team) is sticky for 24h across reconnections. * Single-org user: nothing to do; primary workspace applies. * Multi-org user: call `get_context()` at session start; if unset, ask which org/team. `set_context(org_name, team_name)` takes **names** (case-insensitive), not UUIDs. All workspace-scoped tools (`list_brand_kits`, `start_design_task`, `remix_design`, `upload_file`) read from session context. Per-call overrides: pass `org_id` / `team_id` for one-call overrides without changing the session default. ## Design-to-code (separate workflow) `get_moda_canvas(url=…)` returns semantic pseudo-HTML (``, ` ## Design Tokens - Colors: #111827, #2563eb, #6b7280, #d1d5db, #f3f4f6, #ffffff - Font Inter: weights [400, 700] roles [body, heading] - Corner radii: 8px, 16px ``` The semantic tag names (`Card`, `Button`, `TextInput`, `Heading`) tell the agent **what** each element is, not just what it looks like. This produces better code than raw coordinates or screenshots alone. ## Transport modes The MCP server supports two transport modes: | Transport | Auth | Use case | | - | - | - | | `stdio` | None | Local IDE integrations (Cursor, Claude Code) | | `streamable-http` | OAuth 2.1 | Hosted endpoint at `mcp.moda.app` | The hosted server at `mcp.moda.app` is the easiest way to get started. See [Setup](/mcp/setup) for configuration details. ## Available tools ### Design creation | Tool | Description | Auth required | | - | - | - | | [`start_design_task`](/mcp/tools#start_design_task) | Create or edit a design from a prompt | Yes | | [`get_task_status`](/mcp/tools#get_task_status) | Check progress of a design task | Yes | | [`list_tasks`](/mcp/tools#list_tasks) | List recent design tasks | Yes | | [`remix_design`](/mcp/tools#remix_design) | Duplicate canvas + optional AI edits | Yes | ### Brand kits | Tool | Description | Auth required | | - | - | - | | [`list_brand_kits`](/mcp/tools#list_brand_kits) | List brand kits for a team | Yes | | [`create_brand_kit`](/mcp/tools#create_brand_kit) | Create brand kit from website URL | Yes | | [`update_brand_kit`](/mcp/tools#update_brand_kit) | Update brand kit colors, fonts, etc. | Yes | ### Canvas management | Tool | Description | Auth required | | - | - | - | | [`list_my_canvases`](/mcp/tools#list_my_canvases) | Browse your canvases | Yes | | [`search_canvases`](/mcp/tools#search_canvases) | Search canvases by name | Yes | | [`list_organizations`](/mcp/tools#list_organizations) | List your orgs and teams | Yes | ### Design to code | Tool | Description | Auth required | | - | - | - | | [`get_moda_canvas`](/mcp/tools#get_moda_canvas) | Fetch semantic pseudo-HTML and design tokens | Public links: No, Private: Yes | | [`get_moda_canvas_tokens`](/mcp/tools#get_moda_canvas_tokens) | Extract design tokens only (colors, fonts, radii) | Public links: No, Private: Yes | | [`list_moda_canvas_pages`](/mcp/tools#list_moda_canvas_pages) | List pages with dimensions and node counts | Public links: No, Private: Yes | | [`export_canvas`](/mcp/tools#export_canvas) | Export as PNG, JPEG, PDF, PPTX, MP4, or GIF | Yes | The tables above highlight the most-used tools. The MCP server also provides `get_moda_bootstrap` for mandatory session orientation, `set_context` / `get_context` / `set_session_brand_kit` for session management, `find_brand_kits` for agent-side kit lookups (the JSON sibling of `list_brand_kits`), and `upload_file` for attaching files to design tasks. See the [full tools reference](/mcp/tools) for all 20+ tools. ## Get the most out of the MCP For AI agents — Claude, Cursor, claude.ai, and others — the Moda **agent skill** teaches the agent how to drive these tools effectively without you re-explaining every conversation. It covers the `get_moda_bootstrap` first-call handshake, the canonical design-task patterns (create / edit / fill template / rebrand / bulk), and the non-obvious behaviors tool signatures alone can't communicate. > [card] [Install the agent skill](/mcp/agent-skill) > > Install paths for Claude Code, Cursor, claude.ai, and the Agent SDK — including a zip download for non-technical users. ## Next steps * [Setup](/mcp/setup) — Install and configure the MCP server * [Agent Skill](/mcp/agent-skill) — Drop our skill into your AI agent for best results * [Creating Designs](/mcp/create-designs) — Prompts and tips for creating designs with Claude * [Authentication](/mcp/authentication) — Understand the OAuth flow for the remote server * [Tools Reference](/mcp/tools) — Detailed reference for each tool * [Design-to-Code](/mcp/design-to-code) — Best practices for turning designs into code # Setup Source: https://docs.moda.app/mcp/setup Connect Moda to Claude Desktop, claude.ai, Claude Code, Claude mobile, Cursor, or VS Code. > [!WARNING] > > **Legacy.** This section documents the original Moda MCP server at `mcp.moda.app/mcp`, built around > `start_design_task` and `get_moda_canvas`. It is superseded by [Moda for Agents](/agents) — the `moda` CLI wherever > your agent has a shell, and the [Moda connector](/agents/mcp-connector) for claude.ai and other chat hosts. The > connector replaces this server, so the tools below retire with it. These pages stay published for existing > integrations; start new ones on [Moda for Agents](/agents). The Moda MCP server at `mcp.moda.app/mcp` requires no local installation. Authentication is handled via OAuth — you sign in through your browser on first use. This page focuses on the most common **interactive** setups — you sign in through your browser once, then Claude / Cursor / VS Code manage tokens for you. > [!NOTE] > > **Running Moda MCP in a scheduled job, managed agent, or CI pipeline?** Use API-key auth instead of OAuth — no browser > required. See the [Authentication page → Setting up API-key auth](/mcp/authentication#setting-up-api-key-auth) for > per-client setup with `Authorization: Bearer` headers. ## Connect your editor > [tab] Claude Desktop > > Open Claude Desktop, click **Customize** in the sidebar, then the **+** button > **Add custom connector**. For the **Name**, input `Moda`, and use the MCP server URL below and click **Add**: > > ``` > https://mcp.moda.app/mcp > ``` > > Click **Connect** after adding and you'll be prompted to sign into Moda and authorize your account. > [tab] Claude.ai (browser) > > Go to **Customize** in your sidebar ([claude.ai/customize](https://claude.ai/customize)) and click the **+** button > **Add custom connector**. For the **Name**, input `Moda`, and use the MCP server URL below and click **Add**: > > ``` > https://mcp.moda.app/mcp > ``` > > Click **Connect** after adding and you'll be prompted to sign into Moda and authorize your account. > > **Team and Enterprise plans:** An admin must first add the Moda connector in **Admin Settings > Connectors**. After that, individual members can connect from their personal **Customize** sidebar. > [tab] Claude Code > > Run this command in your terminal: > > ```bash theme={null} > claude mcp add --transport http moda https://mcp.moda.app/mcp > ``` > > Verify the connection: > > ```bash theme={null} > claude /mcp > ``` > > You should see `moda` listed as a connected server. When you first use an MCP tool, Claude Code will open your browser for sign-in. > > To remove the server later: > > ```bash theme={null} > claude mcp remove moda > ``` > [tab] Claude Mobile > > Connectors set up on claude.ai sync to the Claude mobile app automatically. > > 1. Go to [claude.ai/settings](https://claude.ai/settings) on your computer > 2. Add the Moda connector (see the **Claude.ai (browser)** tab) > 3. Open the Claude app on your phone — Moda will be available > > This lets you create designs from your phone by chatting with Claude. > [tab] Cursor > > Open **Cursor Settings > MCP** and add a new server, or add to `~/.cursor/mcp.json`: > > ```json theme={null} > { > "mcpServers": { > "moda": { > "type": "streamable-http", > "url": "https://mcp.moda.app/mcp" > } > } > } > ``` > > You can also use a project-level config at `.cursor/mcp.json` in your project root. > > Cursor handles the OAuth flow automatically when you first connect. > [tab] VS Code > > Add to your VS Code settings (`settings.json`): > > ```json theme={null} > { > "mcp": { > "servers": { > "moda": { > "type": "streamable-http", > "url": "https://mcp.moda.app/mcp" > } > } > } > } > ``` ## Verifying the connection After setting up the server, test it by asking the AI agent to describe a Moda design: ``` What's in this Moda design? https://moda.app/s/your-share-token ``` The agent should call the `get_moda_canvas` tool and return a description of the canvas contents. ## Troubleshooting ### Server not connecting * **Claude Desktop**: Check that Moda appears under **Connectors** (click the **+** button in the chat box). If not, go to **Settings > Connectors** and re-add it. Try restarting the app. * **Claude.ai**: Check that the connector appears in [claude.ai/settings](https://claude.ai/settings) under **Connectors**. Try removing and re-adding it. * **Claude Code**: Run `claude /mcp` to verify the server is listed. Try `claude mcp remove moda` and re-add it. * **Claude Mobile**: Connectors sync from claude.ai. Make sure the connector is set up in [claude.ai/settings](https://claude.ai/settings) under **Connectors** first, then restart the mobile app. * **Cursor**: Check that the MCP server shows as "connected" in Cursor Settings > MCP. Try restarting the MCP server from the settings panel. * **VS Code**: Ensure the MCP configuration is in your user or workspace `settings.json`. Restart VS Code after adding the config. # Tools Reference Source: https://docs.moda.app/mcp/tools Complete reference for all Moda MCP tools — parameters, return types, and usage examples. > [!WARNING] > > **Legacy.** This section documents the original Moda MCP server at `mcp.moda.app/mcp`, built around > `start_design_task` and `get_moda_canvas`. It is superseded by [Moda for Agents](/agents) — the `moda` CLI wherever > your agent has a shell, and the [Moda connector](/agents/mcp-connector) for claude.ai and other chat hosts. The > connector replaces this server, so the tools below retire with it. These pages stay published for existing > integrations; start new ones on [Moda for Agents](/agents). The Moda MCP server provides 20+ tools for working with canvas designs. These tools are called automatically by your AI coding agent when it needs design data or wants to create and manage designs. | Tool | Description | Auth required | | - | - | - | | [`get_moda_bootstrap`](#get_moda_bootstrap) | Fetch Moda session bootstrap before any canvas work (call first) | Yes | | [`set_context`](#set_context) | Set your active organization and team | Yes | | [`get_context`](#get_context) | Show your current session context | Yes | | [`set_session_brand_kit`](#set_session_brand_kit) | Pin a brand kit for this session | Yes | | [`get_moda_canvas`](#get_moda_canvas) | Fetch semantic pseudo-HTML and design tokens | Public links: No | | [`get_moda_canvas_tokens`](#get_moda_canvas_tokens) | Extract design tokens only | Public links: No | | [`list_moda_canvas_pages`](#list_moda_canvas_pages) | List pages with dimensions and node counts | Public links: No | | [`export_canvas`](#export_canvas) | Export as PNG, JPEG, PDF, PPTX, MP4, or GIF | Yes | | [`get_export_status`](#get_export_status) | Poll an in-progress export | Yes | | [`list_my_canvases`](#list_my_canvases) | Browse your canvases | Yes | | [`search_canvases`](#search_canvases) | Search canvases by name | Yes | | [`list_organizations`](#list_organizations) | List your orgs and teams | Yes | | [`find_brand_kits`](#find_brand_kits) | JSON-only brand-kit lookup (agent-side, no iframe) | Yes | | [`list_brand_kits`](#list_brand_kits) | List brand kits — renders visual showcase iframe | Yes | | [`create_brand_kit`](#create_brand_kit) | Create brand kit from website URL | Yes | | [`update_brand_kit`](#update_brand_kit) | Update brand kit colors, fonts, etc. | Yes | | [`set_default_brand_kit`](#set_default_brand_kit) | Mark a brand kit as the **team's** default (destructive) | Yes | | [`list_brand_kit_images`](#list_brand_kit_images) | List logos and reference images for a kit | Yes | | [`remove_brand_kit_image`](#remove_brand_kit_image) | Detach an image from a brand kit | Yes | | [`upload_file`](#upload_file) | Upload a file from URL for attachments | Yes | | [`start_design_task`](#start_design_task) | Start an AI design task | Yes | | [`get_task_status`](#get_task_status) | Get task status and progress | Yes | | [`list_tasks`](#list_tasks) | List recent design tasks | Yes | | [`remix_design`](#remix_design) | Duplicate canvas + optional AI edits | Yes | | [`list_my_websites`](#list_my_websites) | Browse websites in your team | Yes | | [`get_website`](#get_website) | Read HTML, title, share state, published URL | Yes | | [`create_website_from_upload`](#create_website_from_upload) | Create a website from an HTML upload | Yes | | [`update_website_from_upload`](#update_website_from_upload) | Replace HTML and/or title of an existing website | Yes | ## Session context When you first connect, Moda uses your default organization and team. If you belong to multiple organizations, you can switch with `set_context`: 1. Call `list_organizations` to see your orgs and teams. 2. Call `set_context` with the org name (and optionally team name). 3. All subsequent tool calls use that workspace automatically. Your context persists for 24 hours across reconnections. Tools like `list_brand_kits`, `create_brand_kit`, `start_design_task`, and `remix_design` all read from your session context automatically. You can also pass `org_id` or `team_id` explicitly to override the session context for a single call. ### URL formats All tools that accept a `url` parameter support these formats: | Format | Example | | - | - | | Share link | `https://moda.app/s/abc123-token` | | Private canvas URL | `https://moda.app/canvas/550e8400-e29b-41d4-a716-446655440000` | | Raw share token | `abc123-token` | | Legacy domain | `https://app.moda.so/s/abc123-token` | Private canvas URLs require [authentication](/mcp/authentication) via the remote server. *** ## set\_context Sets your preferred organization and team for the current session. Once set, all subsequent tools that operate within a workspace (brand kits, design tasks, remixes) will use these defaults automatically. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `org_name` | `string` | Yes | Name of the organization to use (case-insensitive). Use `list_organizations` to see options. | | `team_name` | `string` | No | Name of the team within the org (case-insensitive). Defaults to the org's default team. | ### Returns A confirmation string: ``` Context set to organization 'Acme Corp' and team 'Design Team'. All subsequent operations will use this workspace. ``` ### Example usage ``` # Set org (uses default team) set_context(org_name="Acme Corp") # Set org and specific team set_context(org_name="Acme Corp", team_name="Marketing") ``` ### Notes * Call `list_organizations` first to see available organization and team names * Context persists for 24 hours across reconnections * You can call `set_context` again at any time to switch workspaces *** ## get\_context Shows your current session context -- which organization and team are active for workspace-scoped tools. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. ### Parameters This tool takes no parameters. ### Returns A string describing your current context: ``` Organization: Acme Corp | Team: Design Team ``` If no context is set: ``` No session context set. Call set_context to choose your organization and team. ``` *** ## get\_moda\_bootstrap MANDATORY FIRST CALL, every new conversation, before creating, editing, reading, remixing, or exporting any canvas — even if the agent already knows the user's identity: this returns far more than identity (the Moda skill pointer, active user, active workspace, and entitlements that affect tool-call decisions). The response also lets agents skip downstream lookups when defaults are unambiguous. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. ### Parameters This tool takes no parameters. ### Returns ```json theme={null} { "user": { "id": "550e8400-e29b-41d4-a716-446655440000", "name": "Jane Doe", "email": "jane@acme.com" }, "session": { "org_id": "660e8400-e29b-41d4-a716-446655440000", "org_name": "Acme Corp", "team_id": "770e8400-e29b-41d4-a716-446655440000", "team_name": "Design Team", "brand_kit_id": null }, "org_count": 1, "team_default_brand_kit": { "id": "880e8400-e29b-41d4-a716-446655440000", "title": "Acme Corp" }, "brand_kit_count": 1, "plan": "paid", "concurrency_cap": 10 } ``` | Field | Type | Description | | - | - | - | | `user.id` | `string` | The Moda user UUID. | | `user.name` | `string` | Display name. | | `user.email` | `string` | Email address. | | `session.org_id` | `string \| null` | Active org for this session, or null if unset. | | `session.team_id` | `string \| null` | Active team for this session. | | `session.brand_kit_id` | `string \| null` | Session-pinned brand kit, if any. Set via the showcase iframe button or `set_session_brand_kit`. | | `org_count` | `integer` | Total orgs the user belongs to. If 1, no multi-org disambiguation is needed. | | `team_default_brand_kit` | `object \| null` | The team default's id + title, if a default exists. | | `brand_kit_count` | `integer` | Brand kits in the active team. If 1, the agent can use that kit without further listing. | | `plan` | `string` | Billing plan: `free`, `free_beta`, `paid`, `ultra`, or `enterprise`. | | `concurrency_cap` | `integer` | Max concurrent design tasks for this plan. Use as the upper bound for bulk fan-out. | ### Notes * Reads from existing session context — no side effects. * A good first call on any new conversation: `org_count`, `brand_kit_count`, and `concurrency_cap` collectively eliminate the need for several downstream tool calls. * The `plan` value is the same enum returned by the billing service; `concurrency_cap` is pre-resolved so callers don't need to maintain their own mapping. *** ## set\_session\_brand\_kit Pin the brand kit the user chose for the current session **without** changing the team default. Subsequent calls to `start_design_task` / `remix_design` that omit `brand_kit_id` will resolve to this kit, and it counts as the user's brand choice for new designs. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. This is what the brand-kit showcase iframe's **Use for this session** button calls. For changing the team default (destructive, affects every team member), use [`set_default_brand_kit`](#set_default_brand_kit) instead. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `brand_kit_id` | `string \| null` | No | Brand kit UUID (or `bk_…` wire form). Pass null/empty to clear the session pin. | ### Returns A confirmation string: ``` Session brand kit set to . Subsequent design tasks will apply it unless overridden. ``` Or when cleared: ``` Session brand kit cleared. Edits keep each canvas's own kit; a new design needs the user's brand choice again. ``` ### Notes * Switching workspaces via [`set_context`](#set_context) clears the session brand kit (kits are team-scoped). * Resolution order for `start_design_task` / `remix_design`: explicit `brand_kit_id` → session preference → (edits and remixes) the canvas's own kit, then the team default → none (if `skip_brand_kit=true`). A new design with no choice is gated instead — see [`start_design_task`](#start_design_task). * The kit must belong to the active team; trying to pin a kit from a different team raises a tool error. *** ## get\_moda\_canvas The primary tool for design-to-code workflows. Fetches a Moda canvas and returns semantic pseudo-HTML with CSS properties and design tokens that AI agents can translate to any frontend framework. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `url` | `string` | Yes | Moda share URL (`https://moda.app/s/...`), private canvas URL (`https://moda.app/canvas/...`), or raw share token | | `page_number` | `integer \| null` | No | 1-indexed page number. Omit to get all pages. | ### Returns A string containing semantic pseudo-HTML with CSS properties, followed by a design tokens summary. ```html theme={null} # Moda Design Export — Canvas Title # Source: https://moda.app/s/abc123 ## Page: Login Screen (1440x900) [page 1]
Welcome back Sign in to your account
## Design Tokens - Colors: #111827, #2563eb, #6b7280, #d1d5db, #f3f4f6, #ffffff - Font Inter: weights [400, 700] roles [body, heading] - Corner radii: 8px, 16px ``` ### Semantic tags The transformer assigns semantic tag names based on visual properties and layer names: | Tag | When used | | - | - | | `Heading` | Text with font-size >= 24px or font-weight >= 600 | | `Text` | Default text elements | | `Button` | Rectangle with text, dark fill, and button-like dimensions | | `TextInput` | Rectangle with light fill, thin border, no text | | `Image` | Element with an image fill | | `Avatar` | Small circular element with an image fill | | `Card` | Group with a background rectangle and content | | `Row` | Container with `flex-direction: row` | | `Column` | Container with `flex-direction: column` | | `Divider` | Line element | | `Nav`, `Hero`, `Footer` | Matched from layer names | Layer names in Moda take priority over visual heuristics. See [Naming Layers](/mcp/naming-layers) for best practices. ### Example usage ``` # Fetch all pages get_moda_canvas(url="https://moda.app/s/abc123") # Fetch a specific page get_moda_canvas(url="https://moda.app/s/abc123", page_number=2) # Fetch a private canvas (requires authentication) get_moda_canvas(url="https://moda.app/canvas/550e8400-e29b-41d4-a716-446655440000") ``` ### Notes * The output is intentionally HTML-like so agents can map it directly to React, Vue, or HTML components * Design tokens are appended as a summary at the end of the output * For multi-page canvases, omitting `page_number` returns all pages in a single response * Hidden layers are excluded from the output * Rich text extracts the first style span's properties; mixed-style paragraphs use the first style encountered *** ## get\_moda\_canvas\_tokens Returns only the design tokens from a canvas — colors, fonts, variables, and corner radii — as structured JSON. Use this when you need to generate theme configuration files without the full semantic layout. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `url` | `string` | Yes | Moda share URL, private canvas URL, or raw share token | | `page_number` | `integer \| null` | No | 1-indexed page number. Omit for all pages. | ### Returns ```json theme={null} { "variables": { "primary": "#2563eb", "secondary": "#6b7280", "background": "#f3f4f6" }, "colors": ["#111827", "#2563eb", "#6b7280", "#d1d5db", "#f3f4f6", "#ffffff"], "fonts": [ { "family": "Inter", "weights": [400, 700], "roles": ["body", "heading"] } ], "radii": ["8px", "16px"], "dimensions": { "width": 1440, "height": 900 } } ``` | Field | Type | Description | | - | - | - | | `variables` | `object` | Named design variables defined in the canvas (colors, numbers, strings) | | `colors` | `string[]` | All unique colors used in the canvas | | `fonts` | `object[]` | Font families with weights and inferred roles | | `radii` | `string[]` | All unique corner radii used | | `dimensions` | `object` | Canvas page dimensions (width and height) | ### Example usage ``` # Extract tokens for theme generation get_moda_canvas_tokens(url="https://moda.app/s/abc123") # Extract tokens from a specific page get_moda_canvas_tokens(url="https://moda.app/s/abc123", page_number=1) ``` ### Notes * Variables defined in the Moda canvas (via the variables panel) appear in the `variables` field with their default values * Colors are deduplicated and sorted * Font roles (`body`, `heading`) are inferred from usage context (font size and weight) *** ## list\_moda\_canvas\_pages Returns metadata about each page in a canvas, including page names, dimensions, and the number of design elements. Use this to understand the structure of multi-page canvases before fetching specific pages. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `url` | `string` | Yes | Moda share URL, private canvas URL, or raw share token | ### Returns ```json theme={null} { "canvas_name": "Marketing Website", "total_pages": 3, "pages": [ { "page_number": 1, "id": "p_a", "name": "Hero Section", "width": 1440, "height": 900, "node_count": 12 }, { "page_number": 2, "id": "p_b", "name": "Features", "width": 1440, "height": 1200, "node_count": 24 } ], "id_note": "IDs like n1/p_a/img1 are session-scoped short refs..." } ``` | Field | Type | Description | | - | - | - | | `canvas_name` | `string` | Name of the canvas | | `total_pages` | `integer` | Total number of pages | | `pages[].page_number` | `integer` | 1-indexed page number | | `pages[].id` | `string` | The page's addressable id — omitted only for a page-less canvas | | `pages[].name` | `string` | Page name as set in Moda | | `pages[].width` | `number` | Page width in pixels | | `pages[].height` | `number` | Page height in pixels | | `pages[].node_count` | `integer` | Number of design elements on the page | | `id_note` | `string` | Present only when the ids are short refs; states their lifetime | ### Notes * Page numbers are 1-indexed * **`page_number` vs `id`.** The tools on this server (`get_moda_canvas`, `get_moda_canvas_tokens`, `export_canvas`) take `page_number`. `pages[].id` is for the page-scoped authoring endpoints, and unlike an ordinal it survives a page being deleted or reordered * `id` is either a durable real page id (`page-1786730909610-172273165`) or a session-scoped short ref (`p_a`). When `id_note` is present they are short refs — re-list to refresh rather than storing one * The `node_count` includes all visible elements on the page (shapes, text, images, groups) * Hidden elements are excluded from the count *** ## export\_canvas Export a Moda canvas as an image or document file. Pass exactly one of `canvas_id` or `url`. ### Parameters | Parameter | Type | Required | Default | Description | | - | - | - | - | - | | `canvas_id` | `string` | No | — | Canvas UUID to export directly. Preferred after `start_design_task` returns a new canvas. | | `url` | `string` | No | — | Moda share URL, private canvas URL, or raw share token. Use this for share-link or design-to-code workflows. | | `format` | `string` | No | `"png"` | Export format: `png`, `jpeg`, `pdf`, `pptx`, `mp4`, or `gif` | | `scope` | `string` | No | `"page"` | What the export renders: `page` (one page, addressed by `page_number`), `sequence` (mp4 only — every visible page's animation stitched into ONE video, in canvas order, transitions included; takes no `page_number`, requires a multi-page animation canvas), or `main_edit` (mp4 only — the canvas's persisted Main Edit timeline; page-less, fine on a single-page canvas, rejected with `no_animation` when no edit is persisted). | | `fps` | `integer \| null` | No | `null` | Animation formats only — capture frame rate: mp4 `24`/`30`/`60` (default 30), gif `10`/`12`/`15`/`24` (default 12). Integer rates only. The frame budget is rate-independent, so a higher fps shortens the longest exportable timeline (150 s of mp4 at 60 fps); over-budget requests are rejected with the live bound. | | `page_number` | `integer \| null` | No | `null` | 1-indexed page number. Omit to export all pages — PDF/PPTX bundle every page natively, while multi-page PNG/JPEG are returned as a `.zip` of per-page files named after the pages (`01-Cover@2x.png`, `02-Page-2@2x.png`, …) since a single image container can't hold multiple pages. Single-page canvases still return a raw PNG/JPEG. The `format` field in the response reflects what was actually delivered (`zip` in the bundled case). MP4/GIF export exactly one page: required on a multi-page canvas, defaulted to 1 on a single-page one. | | `pixel_ratio` | `integer \| null` | No | `null` | Render scale 1–4 for PNG, JPEG, PDF, MP4, and GIF (MP4/GIF default 1). Ignored for PPTX. | | `flatten` | `boolean` | No | `true` | PDF only — produce a raster-only PDF with no searchable text layer. | | `task_id` | `string \| null` | No | `null` | Optional task identifier to scope the export's cache key. When provided, the rendered file is cached as a stable snapshot for that task — useful for design-task progress UIs that should keep showing the original task output even after the canvas is edited. When omitted (typical LLM use), the cache busts on any canvas-data change so direct re-exports always reflect the current state. | | `wait` | `boolean` | No | `true` | When `true` (default), block up to \~20s for the export to finish before returning an in-progress handle. When `false`, return `status='in_progress'` with a `task_id` immediately — call `get_export_status(task_id)` to retrieve the URL once the background work completes. Cache hits return synchronously regardless. | ### Format guide | Format | Best for | | - | - | | `png` | Design-to-code workflows — lossless image, ideal for visual reference | | `jpeg` | Smaller file size when lossless quality isn't needed | | `pdf` | Multi-page documents, printing, sharing | | `pptx` | PowerPoint presentations, slide decks | | `mp4` | Video of one page's animation timeline, with its video-fill audio | | `gif` | Animated image of one page's animation timeline | `mp4` and `gif` render a single page's animation timeline by default (see `scope` for the stitched sequence and Main Edit forms). The page must actually have animation — a still page is rejected with a `no_animation` error. Each format is bounded per file, whichever half binds first: mp4 by 18,000 encoded frames and 600 s (600 s at the default 30 fps, 300 s at 60 fps), gif by 9,000 frames and 300 s (300 s at its 10–24 fps rates). A longer timeline is rejected at submit time with the concrete ceiling. For multi-page PNG/JPEG without `page_number`, the response carries `format: "zip"` and the URL serves a `.zip` of per-page raster files. The requested raster format is preserved inside the archive, and each entry is named `-@x` (`01-Cover@2x.png`, `02-Page-2@2x.png`, …) — an unnamed page uses its `Page N` label. ### Returns On success: ```json theme={null} { "status": "completed", "url": "https://assets-cdn.moda.app/exports/abc123.png", "format": "png" } ``` When the canvas has multiple pages and `page_number` was omitted, a PNG/JPEG export bundles into a zip: ```json theme={null} { "status": "completed", "url": "https://assets-cdn.moda.app/exports/abc123.zip", "format": "zip", "total_pages": 8 } ``` When the export hasn't finished within the synchronous wait budget (large multi-page canvases, cold renders), the call returns an in-progress handle. Call `get_export_status(task_id)` to fetch the URL once it's ready — the same `task_id` keeps returning the in-progress shape until terminal: ```json theme={null} { "status": "in_progress", "task_id": "550e8400-e29b-41d4-a716-446655440000", "canvas_id": "660e8400-e29b-41d4-a716-446655440000", "canvas_url": "https://moda.app/canvas/660e8400-e29b-41d4-a716-446655440000", "format": "pdf", "total_pages": 23, "retry_after_seconds": 5 } ``` If a design task is still active for the target canvas: ```json theme={null} { "status": "not_ready", "reason": "active_design_job", "retry_after_seconds": 3, "canvas_id": "550e8400-e29b-41d4-a716-446655440000", "canvas_url": "https://moda.app/canvas/550e8400-e29b-41d4-a716-446655440000", "task_id": "990e8400-e29b-41d4-a716-446655440000" } ``` `canvas_id`, `canvas_url`, and `task_id` are only included for authenticated private-canvas exports (i.e., when using `canvas_id` or a private URL). Share-link exports omit these fields to avoid leaking internal identifiers. | Field | Type | Description | | - | - | - | | `status` | `string` | `"completed"`, `"in_progress"`, or `"not_ready"` (active design job blocks export) | | `url` | `string` | Signed URL to the exported file (only when `status='completed'`) | | `format` | `string` | The format that was used for the export | | `reason` | `string` | Retryable not-ready reason: `active_design_job` or `job_status_unavailable` | | `retry_after_seconds` | `integer` | Suggested delay before retrying when `status` is `"not_ready"` or `"in_progress"` | | `task_id` | `string` | Export task ID when `status='in_progress'`; pass to `get_export_status` to poll. Also surfaces the active design task ID when `status='not_ready'`. | | `canvas_id` | `string` | Canvas UUID for the export target (private exports only) | | `canvas_url` | `string` | Direct Moda link to the canvas (private exports only) | | `total_pages` | `integer` | Total page count for the canvas (echoed for client convenience) | ### Example usage Provide exactly one of `canvas_id` or `url` per call: ``` # Export as PNG for design-to-code (default) export_canvas(url="https://moda.app/s/abc123") # Export directly from a canvas_id returned by start_design_task export_canvas(canvas_id="550e8400-e29b-41d4-a716-446655440000", format="pdf") # Export a specific page as JPEG export_canvas(url="https://moda.app/s/abc123", format="jpeg", page_number=2) # Export all pages as a PDF export_canvas(url="https://moda.app/s/abc123", format="pdf") # Export as a PowerPoint file export_canvas(url="https://moda.app/s/abc123", format="pptx") ``` ### Notes * Pass exactly one of `canvas_id` or `url` * For design-generation workflows, prefer `canvas_id` from `start_design_task` / `get_task_status` * Export-before-ready and temporary readiness-check failures are normal retryable MCP states, not tool failures * The signed URL expires after 7 days * In production, the URL is served from the signed `assets-cdn.moda.app` CDN; raw `storage.googleapis.com` links are a fallback and not the canonical host * Page exports are cached in Redis for 24 hours per `(canvas, page, delivered format, pixel_ratio, flatten)` combination. *Delivered*, not requested: a multi-page PNG or JPEG request is bundled into a `.zip`, so those two resolve to the same cache slot. With `task_id` omitted the cache key includes the canvas's scene version, so any content edit auto-invalidates; a `task_id`-scoped export is keyed on the task instead and stays valid across edits (see the `task_id` parameter above). Re-exporting an unchanged page returns in milliseconds. * For document formats (`pdf`, `pptx`), all pages are included by default unless `page_number` is specified * For PNG/JPEG: pass a specific `page_number` to get a single image; omit it to get every page — single-page canvases return a raw image, multi-page canvases return a `.zip` of page-named files like `01-Cover@2x.png` (`format: "zip"` in the response) * When a design task auto-exports via `export_on_complete`, the artifact lives at `result.export` on the task and is keyed identically to a manual `export_canvas` call. A follow-up `export_canvas` for the same canvas with no edits hits the cache instead of re-rendering. * Screenshots are rendered server-side using a headless browser *** ## get\_export\_status Poll the status of an asynchronous export started by `export_canvas`. Use when `export_canvas` returned `status='in_progress'` (large multi-page exports that exceed the synchronous wait budget). ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `task_id` | `string` | Yes | Export task ID returned by `export_canvas` when `status='in_progress'` — bare UUID or prefixed wire form. | ### Returns While running: ```json theme={null} { "status": "running", "is_terminal": false, "task_id": "550e8400-e29b-41d4-a716-446655440000", "canvas_id": "660e8400-e29b-41d4-a716-446655440000", "canvas_url": "https://moda.app/canvas/660e8400-e29b-41d4-a716-446655440000", "format": "pdf", "total_pages": 23, "retry_after_seconds": 5 } ``` On completion: ```json theme={null} { "status": "completed", "is_terminal": true, "task_id": "550e8400-e29b-41d4-a716-446655440000", "canvas_id": "660e8400-e29b-41d4-a716-446655440000", "canvas_url": "https://moda.app/canvas/660e8400-e29b-41d4-a716-446655440000", "format": "pdf", "url": "https://assets-cdn.moda.app/exports/abc123.pdf", "total_pages": 23 } ``` On failure: ```json theme={null} { "status": "failed", "is_terminal": true, "task_id": "550e8400-e29b-41d4-a716-446655440000", "error": "Failed to export document: ...", "format": "pdf" } ``` | Field | Type | Description | | - | - | - | | `status` | `string` | `queued`, `running`, `completed`, or `failed`. | | `is_terminal` | `boolean` | `true` once the task has reached `completed` or `failed`. | | `task_id` | `string` | The export task ID being polled. | | `url` | `string` | Signed download URL once `status='completed'`. | | `error` | `string` | Failure detail when `status='failed'`. | | `retry_after_seconds` | `integer` | Suggested poll cadence while `is_terminal` is `false`. | ### Notes * Export task records are kept for \~1 hour. After that the task ID is treated as unknown and the call returns a tool error. * Call `get_export_status` instead of repeatedly calling `export_canvas` while a known task is running — `export_canvas` may return the same in-progress handle, but `get_export_status` is the canonical poll path. *** ## list\_my\_canvases Returns a paginated list — or, with a `query`, a paginated keyword search — of canvases accessible to the authenticated user. Use this to browse available canvases when you don't have a specific URL, and whenever the user should see or pick one. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. ### Parameters | Parameter | Type | Required | Default | Description | | - | - | - | - | - | | `query` | `string` | No | `null` | Keyword to match against canvas names (fuzzy) and content (full-text). Omit to browse by recency; combines with the other filters | | `limit` | `integer` | No | `6` | Number of canvases to return (max 100) | | `offset` | `integer` | No | `0` | Number of canvases to skip for pagination | ### Returns ```json theme={null} { "canvases": [ { "id": "550e8400-e29b-41d4-a716-446655440000", "name": "Marketing Website", "url": "https://moda.app/canvas/550e8400-e29b-41d4-a716-446655440000", "updated_at": "2025-03-15T10:30:00Z" } ], "total": 42, "limit": 20, "offset": 0 } ``` | Field | Type | Description | | - | - | - | | `canvases[].id` | `string` | Canvas UUID | | `canvases[].name` | `string` | Canvas name | | `canvases[].url` | `string` | Direct canvas URL | | `canvases[].updated_at` | `string` | Last update timestamp (ISO 8601) | | `total` | `integer` | Total number of canvases | | `limit` | `integer` | Page size | | `offset` | `integer` | Current offset | ### Notes * Canvases are returned in order of most recently updated; with a `query`, results are ranked by relevance and then recency * Pairs with the Canvas Gallery [interactive app](/mcp/interactive-apps), which renders the results as a thumbnail grid and calls this tool again from its search box and "Show more" button * Prefer this tool over `search_canvases` whenever the user should see or pick a canvas — pass `query` to hand them a pre-filtered gallery * The `url` field can be passed directly to other tools like `get_moda_canvas` * The maximum `limit` is 100 per request *** ## search\_canvases Searches your canvases by name or content and returns matching results as plain JSON. Use this when *you* need to resolve a canvas ID for a follow-up call and don't have the exact URL. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. ### Parameters | Parameter | Type | Required | Default | Description | | - | - | - | - | - | | `query` | `string` | Yes | — | Search query to match against canvas names and content | | `limit` | `integer` | No | `20` | Maximum number of results to return (max 100) | ### Returns ```json theme={null} [ { "id": "550e8400-e29b-41d4-a716-446655440000", "name": "Marketing Website v2", "url": "https://moda.app/canvas/550e8400-e29b-41d4-a716-446655440000" } ] ``` | Field | Type | Description | | - | - | - | | `[].id` | `string` | Canvas UUID | | `[].name` | `string` | Canvas name | | `[].url` | `string` | Direct canvas URL | ### Notes * The search matches against canvas names and content * Results are ranked by relevance * Renders **no** interactive app — it's the JSON-only counterpart to `list_my_canvases`, which takes the same `query` and renders the Canvas Gallery. Use that one when the user should see the results * The returned `url` can be passed directly to other tools like `get_moda_canvas` * The maximum `limit` is 100 per request *** ## list\_organizations Returns a list of organizations and teams you belong to. Use this to discover available workspaces, then call `set_context` to choose which one to use. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. ### Parameters This tool takes no parameters. ### Returns ```json theme={null} [ { "id": "550e8400-e29b-41d4-a716-446655440000", "name": "Acme Corp", "role": "admin", "teams": [ { "id": "660e8400-e29b-41d4-a716-446655440000", "name": "Design Team", "is_default": true }, { "id": "770e8400-e29b-41d4-a716-446655440000", "name": "Marketing", "is_default": false } ] } ] ``` | Field | Type | Description | | - | - | - | | `[].id` | `string` | Organization UUID | | `[].name` | `string` | Organization name | | `[].role` | `string` | Your role in the organization (admin or member) | | `[].teams` | `array` | Teams you have access to within this org | | `[].teams[].id` | `string` | Team UUID | | `[].teams[].name` | `string` | Team name | | `[].teams[].is_default` | `boolean` | Whether this is the org's default team | ### Notes * Use org and team names with `set_context` to choose your active workspace * IDs are included but typically don't need to be shown to users — use names in conversation instead * Organizations are sorted alphabetically by name * Only teams you have access to are included *** ## find\_brand\_kits JSON-only sibling of [`list_brand_kits`](#list_brand_kits). Same data, same parameters — the difference is presentation. `find_brand_kits` does **not** render the visual brand-kit showcase iframe, so it's appropriate when the agent is just looking up a `brand_kit_id` to pass to another tool (e.g. `start_design_task`). > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. Per the [MCP Apps spec](https://blog.modelcontextprotocol.io/posts/2026-01-26-mcp-apps/), iframe rendering is decided at tool-listing time from a tool's `_meta.ui.resourceUri`. There is no per-call way to suppress rendering. So Moda exposes two tools sharing the same backing data: * `find_brand_kits` — JSON-only. Use for the agent's own lookups, e.g. resolving a kit the user already named. * `list_brand_kits` — renders the visual showcase. Use when the user asked to see their kits, or must choose one for a new design. ### Parameters Identical to [`list_brand_kits`](#list_brand_kits): `query`, `org_id`, `team_id`, `verbose`, `limit`, `offset`. ### Returns Identical to [`list_brand_kits`](#list_brand_kits). *** ## list\_brand\_kits Returns brand kits for a team. **Renders the visual brand-kit showcase iframe on every call** (on app-aware hosts like claude.ai and Claude Desktop). Brand kits contain colors, fonts, logos, and brand guidelines that were extracted from company websites. Uses your session context (set via `set_context`) or defaults to your primary workspace. It is the picker the agent shows when the user must choose a kit for a new design (see [`start_design_task`](#start_design_task)). For agent-side lookups where the iframe would take over screen space the user didn't ask for, prefer [`find_brand_kits`](#find_brand_kits) — same data, no UI. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `query` | `string` | No | Case-insensitive name filter — matches the kit's title or its company name (substring). Omit to list every kit on the team. | | `org_id` | `string` | No | Organization UUID. Overrides session context for this call. | | `team_id` | `string` | No | Team UUID. Overrides session context for this call. | | `verbose` | `boolean` | No | Default `true`. Include full kit detail (colors, fonts, logos, brand values). Pass `false` for an id/title-only projection. | | `limit` | `integer` | No | Default `10`. Caps the response so teams with many kits don't overflow the host's tool-result context window. Use `offset` to paginate. | | `offset` | `integer` | No | Default `0`. Pagination offset; check `has_more` in the response to know when to stop. | If neither `org_id` nor `team_id` is provided, uses your [session context](#session-context) or defaults to your primary workspace. ### Returns ```json theme={null} { "brand_kits": [ { "id": "880e8400-e29b-41d4-a716-446655440000", "title": "Acme Corp", "is_default": true, "created_at": "2025-03-15T10:30:00", "updated_at": "2025-03-16T14:20:00", "company_name": "Acme Corp", "company_url": "https://acme.com", "company_description": "Modern design tools for teams", "tagline": "Design at scale", "brand_values": ["innovation", "simplicity"], "brand_aesthetic": ["modern", "minimal"], "brand_tone_of_voice": ["professional", "friendly"], "default_color_mode": "light", "default_theme_canvas_id": "cvs_01HT9WK8N3M2J4A5Z6P7Q8R9TV", "colors": [ { "id": "clr_01HT9WK8N3M2J4A5Z6P7Q8R9TV", "color": "#2563eb", "label": "Primary", "mode": "light" }, { "id": "clr_01HT9WK8N3M2J4A5Z6P7Q8R9TW", "color": "#111827", "label": "Text", "mode": null } ], "fonts": [{ "family": "Inter", "label": "Body", "weight": 400, "supported": true }], "logos": [ { "group_name": "Primary Logo", "images": [{ "name": "logo-dark.svg", "url": "https://..." }] } ] } ], "team_id": "660e8400-e29b-41d4-a716-446655440000", "total": 12, "offset": 0, "limit": 10, "has_more": true } ``` | Field | Type | Description | | - | - | - | | `[].id` | `string` | Brand kit UUID | | `[].title` | `string` | Display name for the brand kit | | `[].is_default` | `boolean` | Whether this kit is the team's default (the fallback for edits of a canvas with no kit) | | `[].default_color_mode` | `string` | Preferred color mode when both light and dark palettes are present. Matches `colors[].mode` — typically `"light"` or `"dark"`, or `null` when no mode distinction exists. | | `[].default_theme_canvas_id` | `string` | Prefixed `cvs_…` ID of the kit's saved default slides theme canvas, or `null`. Set/clear it via `update_brand_kit`. | | `[].colors` | `array` | Ordered brand color palette (lower index = higher primacy) | | `[].colors[].id` | `string` | Unique identifier for this color entry | | `[].colors[].color` | `string` | Hex color value (e.g. `"#2563eb"`) | | `[].colors[].label` | `string` | Semantic role label (e.g. `"Primary"`, `"Text"`) | | `[].colors[].mode` | `string` | Color palette mode: `"light"`, `"dark"`, or `null` when the color isn't mode-specific | | `[].fonts` | `array` | Brand typography entries | | `[].logos` | `array` | Logo image groups | When `verbose=false`, each kit drops the `colors`, `fonts`, `logos`, `brand_values`, `brand_aesthetic`, `brand_tone_of_voice`, `company_url`, and `company_description` fields — useful when you only need ids/titles to pick a kit by name. `brand_aesthetic` is a deprecated keyword array describing the brand's visual style. The brand's visual aesthetic is otherwise captured internally and is not exposed through this API. ### Notes * Uses your session context to determine the workspace. Call `set_context` to switch organizations or teams. * Default-kit-first, then created-at descending. Stable across paginated calls when no edits intervene. * The `is_default` kit does not settle a new design — `start_design_task` asks for the user's choice (`brand_kit_choice_required`), however many kits the team has. * Cache: signed export URLs and signed CDN logo URLs are valid for 24h; a chat refresh that re-renders the showcase iframe within that window hits a Redis cache instead of re-signing. *** ## create\_brand\_kit Creates a brand kit by extracting brand information from a company website. Provide a URL or domain and Moda will extract colors, fonts, logos, and brand guidelines automatically. Uses your session context (set via `set_context`) or defaults to your primary workspace. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `url` | `string` | Yes | Website URL or domain (e.g., `stripe.com` or `https://stripe.com`) | | `org_id` | `string` | No | Organization UUID. Overrides session context for this call. | | `team_id` | `string` | No | Team UUID. Overrides session context for this call. | ### Returns Returns the created brand kit in the same format as `list_brand_kits` entries. ```json theme={null} { "id": "880e8400-e29b-41d4-a716-446655440000", "title": "Stripe", "is_default": false, "company_name": "Stripe", "company_url": "https://stripe.com", "company_description": "Financial infrastructure for the internet", "default_color_mode": null, "colors": [ { "id": "clr_01HT9WK8N3M2J4A5Z6P7Q8R9TV", "color": "#635bff", "label": "Primary", "mode": null }, { "id": "clr_01HT9WK8N3M2J4A5Z6P7Q8R9TW", "color": "#0a2540", "label": "Dark", "mode": null } ], "fonts": [{ "family": "Inter", "label": "Body", "weight": 400, "supported": true }], "logos": [] } ``` ### Notes * Extraction typically takes 10–30 seconds depending on the website * Uses Firecrawl to scrape the website and extract brand data * If the brand has been extracted before, a cached result is used for faster response * The first brand kit created for a team is automatically set as the default *** ## update\_brand\_kit Updates an existing brand kit. Pass only the fields you want to change — all other fields remain unchanged. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `brand_kit_id` | `string` | Yes | ID of the brand kit to update | | `title` | `string` | No | Display title for the brand kit | | `colors` | `array` | No | Array of `{ color, label?, id?, mode? }` objects (replaces all colors). `color` is required (hex string). `id` is assigned automatically if omitted. | | `fonts` | `array` | No | Array of `{ family, label, weight }` objects | | `company_name` | `string` | No | Company name | | `company_description` | `string` | No | Company description | | `tagline` | `string` | No | Brand tagline | | `brand_values` | `string[]` | No | List of brand values | | `brand_aesthetic` | `string[]` | No | **Deprecated** list of aesthetic descriptors. The free-text `aesthetic` is derived during brand-kit population and is not settable here. | | `brand_tone_of_voice` | `string[]` | No | List of tone descriptors | | `default_theme_canvas_id` | `string` | No | Canvas ID (`cvs_…` or bare UUID) of a `template_type='theme'` canvas on the same team to set as the kit's default theme | | `clear_default_theme_canvas_id` | `boolean` | No | Set `true` to clear the saved default theme. Mutually exclusive with `default_theme_canvas_id` | Setting `default_theme_canvas_id` to a non-theme canvas — or one on a different team — fails with `invalid_theme_canvas`. ### Returns Returns the updated brand kit in the same format as `list_brand_kits` entries. ### Notes * Pass only the fields you want to change — omitted fields are not modified * When updating `colors` or `fonts`, the entire array is replaced (not merged) * You must have access to the team that owns the brand kit *** ## set\_default\_brand\_kit Marks a brand kit as the team's default and clears the default flag on the previously-default kit. The default fills in when an edited canvas has no kit of its own; it does not stand in for the user's choice on a new design. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. > [!WARNING] > > **Destructive — affects every team member.** This tool clears the default flag on whichever kit was previously default. > Only call it when the user explicitly asks to change their **team** default brand kit. For session-only changes > (no team-wide impact), use [`set_session_brand_kit`](#set_session_brand_kit) instead — that's what the Brand Kit > Showcase iframe's "Use for this session" button now calls. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `brand_kit_id` | `string` | Yes | Brand kit UUID — bare UUID or prefixed `bk_` wire form is accepted | ### Returns Returns the team's brand kits in the same shape as `list_brand_kits`, with the new default first. Use this to rerender any UI that depends on default-kit state without an additional round-trip. ### Example usage ``` # Promote a kit to default after the user explicitly asks set_default_brand_kit(brand_kit_id="880e8400-e29b-41d4-a716-446655440000") ``` ### Notes * Idempotent: setting the already-default kit is a no-op * Only the user's currently-active team is affected * Pairs with the Brand Kit Showcase [interactive app](/mcp/interactive-apps), which calls this tool from its "Set as default" button *** ## list\_brand\_kit\_images Returns every image attached to a brand kit — both logos and design references — in newest-insertion order. Useful when reconciling an existing brand kit before adding new images, since blindly calling `add_brand_kit_image` would create duplicates. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `brand_kit_id` | `string` | Yes | Brand kit UUID — bare UUID or prefixed `bk_` wire form is accepted | ### Returns ```json theme={null} { "brand_kit_id": "bk_abc123", "images": [ { "id": "bki_550e8400e29b41d4a716446655440000", "role": "logo", "file_id": "file_660e8400e29b41d4a716446655440000", "url": "https://assets-cdn.moda.app/brand-kits/.../logo-dark.svg", "name": "logo-dark.svg", "group_id": "770e8400-e29b-41d4-a716-446655440000", "group_name": "Primary Logo" }, { "id": "bki_aa0e8400e29b41d4a716446655440000", "role": "reference", "file_id": "file_bb0e8400e29b41d4a716446655440000", "url": "https://assets-cdn.moda.app/brand-kits/.../homepage-hero.png", "name": "homepage-hero.png", "group_id": "cc0e8400-e29b-41d4-a716-446655440000", "group_name": "Website screenshots" } ] } ``` | Field | Type | Description | | - | - | - | | `brand_kit_id` | `string` | Echoed back for round-tripping | | `images[].id` | `string` | Image-row ID (prefixed `bki_`) — pass to `remove_brand_kit_image` | | `images[].role` | `string` | `"logo"` or `"reference"` | | `images[].file_id` | `string` | Underlying file ID (prefixed `file_`) | | `images[].url` | `string` | Direct URL to the image (CDN-served) | | `images[].name` | `string` | Original filename, if known | | `images[].group_id` | `string` | UUID of the containing logo group / reference group | | `images[].group_name` | `string` | Display name of the group (e.g., `"Primary Logo"`, `"Photography"`) | ### Example usage ``` list_brand_kit_images(brand_kit_id="880e8400-e29b-41d4-a716-446655440000") ``` ### Notes * Pairs with the Brand Kit Image Gallery [interactive app](/mcp/interactive-apps), which renders the images grouped by role * The image `url` is served from the signed CDN; treat it as opaque *** ## remove\_brand\_kit\_image Detaches an image from a brand kit by its `bki_` ID. Returns the freshly re-listed images so callers can rerender from authoritative state. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. > [!WARNING] > > **Destructive.** Only call this when the user explicitly asks to remove a specific image, or in response to a user > action (e.g., the per-card Remove button in the Brand Kit Image Gallery iframe). The underlying file remains in > storage; only the brand-kit reference is removed. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `brand_kit_id` | `string` | Yes | Brand kit UUID — bare UUID or prefixed `bk_` wire form is accepted | | `image_id` | `string` | Yes | Brand-kit image-row ID — bare UUID or prefixed `bki_` wire form | ### Returns Returns the same payload shape as `list_brand_kit_images` after the removal completes, so the caller can rerender directly from the response. ### Example usage ``` remove_brand_kit_image( brand_kit_id="880e8400-e29b-41d4-a716-446655440000", image_id="bki_550e8400e29b41d4a716446655440000", ) ``` ### Notes * The underlying file is **not** deleted from storage — only the brand-kit reference is removed * Pairs with the Brand Kit Image Gallery [interactive app](/mcp/interactive-apps), which calls this tool from each card's Remove button * Not idempotent: calling twice with the same `image_id` raises a not-found error on the second call *** ## upload\_file Uploads a file from a URL to Moda's storage. Returns a stable proxy URL that can be used as an attachment in `start_design_task`. Supports images, PDFs, Office documents (PowerPoint, Word, and Excel spreadsheets), CSV, plain-text/Markdown, and web-playable video (MP4, WebM, MOV). > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `source_url` | `string` | Yes | Public URL of the file to download and store | | `filename` | `string` | No | Filename to use. Inferred from URL if omitted. | | `org_id` | `string` | No | Organization UUID. Overrides session context for this call. | | `team_id` | `string` | No | Team UUID. Overrides session context for this call. | ### Returns ```json theme={null} { "id": "550e8400-e29b-41d4-a716-446655440000", "url": "https://api.moda.app/api/v2/images/ref/550e8400-e29b-41d4-a716-446655440000?h=abc123", "filename": "design-reference.png", "mime_type": "image/png", "size_bytes": 245760, "was_duplicate": false, "message": "File uploaded successfully. Use the 'url' field as an attachment URL in start_design_task." } ``` | Field | Type | Description | | - | - | - | | `id` | `string` | Unique file identifier (UUID) | | `url` | `string` | Stable proxy URL for the uploaded file | | `filename` | `string` | Filename of the uploaded file | | `mime_type` | `string` | MIME type of the file | | `size_bytes` | `integer` | File size in bytes | | `was_duplicate` | `boolean` | True if an identical file already existed | | `message` | `string` | Human-readable confirmation message | ### Example usage ``` # Upload an image for use as a design reference upload_file(source_url="https://example.com/mockup.png") # Upload with a custom filename upload_file(source_url="https://example.com/file.pdf", filename="brand-guidelines.pdf") ``` ### Notes * The returned `url` can be passed directly as an attachment URL in `start_design_task` * Files are deduplicated by content hash — uploading the same file twice returns the existing record * Supported types include images (PNG, JPEG, WebP, etc.), PDFs, Office documents (PowerPoint `.pptx`/`.ppt`, Word `.docx`/`.doc`, Excel `.xlsx`/`.xls`), CSV, plain text/Markdown, and web-playable video (MP4, WebM, MOV) *** ## start\_design\_task Starts an AI design task using Moda's design agent. The agent creates or edits a canvas based on your prompt. Provide a `canvas_id` to edit an existing canvas, or omit it to create a new one. By default this tool returns **immediately** in milliseconds with a task handle (`{task_id, canvas_id, canvas_url, status: 'queued'}`). On hosts that support [interactive apps](/mcp/interactive-apps) (claude.ai web, Claude Desktop), the paired Design Task Progress iframe shows live progress and rendered pages, so you don't need to block on completion. On non-interactive hosts, poll `get_task_status(task_id)` to track progress and detect completion. Pass `wait=True` to opt back into synchronous behavior — useful only for non-interactive consumers that need a single blocking call. Uses your session context (set via `set_context`) or defaults to your primary workspace. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. ### Parameters | Parameter | Type | Required | Default | Description | | - | - | - | - | - | | `prompt` | `string` | Yes | — | Design instructions for the AI agent | | `canvas_id` | `string` | No | — | Canvas to edit. Omit to create a new canvas. Ignored when resuming a conversation. | | `canvas_name` | `string` | No | — | Name for the new canvas (only used when `canvas_id` is omitted) | | `brand_kit_id` | `string` | No | — | Brand kit to apply. For a new design, pass the kit the user chose (or `skip_brand_kit=true`) — omitting it is refused with `brand_kit_choice_required`, whatever the kit count. Edits keep the canvas's own kit. | | `org_id` | `string` | No | — | Organization UUID. Overrides session context for this call. | | `team_id` | `string` | No | — | Team UUID. Overrides session context for this call. | | `conversation_id` | `string` | No | — | UUID of a previous conversation to resume. The agent will have full context of all prior interactions. Returned in every response — pass it back to continue. | | `attachments` | `array` | No | — | List of reference files. Each item is **either** a URL-shape object `{url, name?, type?}` (type ∈ `"image"` / `"pdf"` / `"pptx"` / `"url"`) **or** a file-id-shape object `{file_id, role, label?}` where `file_id` is returned by `upload_file` and `role` ∈ `"source"` (extract content) / `"reference"` (emulate style) / `"asset"` (use directly in outputs) / `"import"` (PPTX-only — load the deck onto the canvas as editable slides, then design against it; any other file type is rejected — and because the deck sets its own page size, an `import` is rejected alongside any format field other than `format_category="slides"`). Prefer the file-id form for uploaded files — it surfaces role metadata to the agent. | | `reference_canvas_ids` | `string[]` | No | — | List of canvas UUIDs to use as design inspiration. The agent can see these designs and reference their style, layout, or content. | | `format_category` | `string` | No | — | Format category — **recommended** for new designs. One of `"slides"` (presentations), `"social"` (social posts), `"carousel"` (multi-slide social), `"pdf"` (documents/reports), `"diagram"` (flowcharts/diagrams), `"ui"` (UI mockups), `"animation"` (motion graphics), `"prints"` (posters/flyers/cards), `"web-ads"` (display ads), or `"other"`. Without it, a fresh canvas resolves to `"other"` at 1080×1080 — not the format you intended. | | `format_width` | `integer` | No | — | Canvas width in pixels. Common: 1920x1080 (slides), 1080x1080 (social square), 1080x1920 (social story). Rejected alongside an `import` attachment — the deck sets its own page size. | | `format_height` | `integer` | No | — | Canvas height in pixels. Rejected alongside an `import` attachment — the deck sets its own page size. | | `model_tier` | `string` | No | — | AI model tier: `"pro"` (best for complex tasks), `"pro-fast"` (Pro quality with faster output and higher credit usage), `"standard"`, or `"lite"` (fastest). Defaults to automatic selection. | | `wait` | `boolean` | No | `false` | When `false` (default), return immediately with a task handle so callers can render the live-progress iframe or poll `get_task_status`. When `true`, block until the agent finishes and return the complete design — only needed for synchronous, non-interactive consumers. | | `export_on_complete` | `object` | No | — | Auto-export preferences applied when the task finishes — the rendered file is attached to `result.export` and the cache is warmed so a follow-up `export_canvas` for the same canvas hits it instantly. Shape: `{enabled?: boolean = true, format?: "png" \| "jpeg" \| "pdf" \| "pptx", pixel_ratio?: 1..4}`. Omit to use the canvas category default (`slides`→PPTX, `pdf`→PDF, others→PNG); an `animation` canvas defaults to video, which the auto-export pipeline does not render — request a still format here to get an auto-export of one. Pass `{enabled: false}` to skip the auto-export. Multi-page PNG/JPEG bundles into a `.zip` of per-page files; `result.export.format` is `"zip"` in that case. | ### Returns ```json theme={null} { "task_id": "990e8400-e29b-41d4-a716-446655440000", "canvas_id": "550e8400-e29b-41d4-a716-446655440000", "canvas_url": "https://moda.app/canvas/550e8400-e29b-41d4-a716-446655440000", "conversation_id": "bb0e8400-e29b-41d4-a716-446655440000", "theme_canvas_id": null, "status": "queued", "message": "Design task started. Use get_task_status to check progress.", "retry_after_seconds": 3 } ``` `theme_canvas_id` reports the brand kit's slides theme that was auto-applied to the new canvas — the canvas whose page layouts the agent themes from. It's populated only when you create a **fresh slides deck** (`format_category="slides"`, no `canvas_id`) with a brand kit that has a saved default theme; it's `null` for non-slides designs, edits of existing canvases, and brand kits without a saved theme. Once `get_task_status` reports `status: "completed"`, the same envelope additionally carries `result.export` with the auto-exported artifact: ```json theme={null} { "result": { "canvas_id": "550e8400-e29b-41d4-a716-446655440000", "canvas_url": "https://moda.app/canvas/550e8400-e29b-41d4-a716-446655440000", "export": { "url": "https://assets-cdn.moda.app/exports/abc123.pptx", "format": "pptx", "status": "completed", "page_count": 8 } } } ``` | Field | Type | Description | | - | - | - | | `result.export.url` | `string` | Signed download URL for the rendered file (expires after 7 days). | | `result.export.format` | `string` | Delivered format — `png`, `jpeg`, `pdf`, `pptx`, or `zip` (multi-page PNG/JPEG bundle). | | `result.export.status` | `string` | `completed` when the file is ready; `failed` if the auto-export couldn't render (the design task still succeeded). | | `result.export.page_count` | `integer` | Total pages in the canvas — useful for sizing UIs ahead of downloading. | ### Example usage ``` # Create a new design (returns a conversation_id) start_design_task(prompt="Create a modern SaaS landing page with a hero section, features grid, and pricing table") # Resume the conversation to make changes (agent remembers previous context) start_design_task(prompt="Change the color scheme to use blues and grays", conversation_id="bb0e8400...") # Edit an existing canvas start_design_task(prompt="Add a footer section", canvas_id="550e8400...") # Create slides with specific dimensions start_design_task(prompt="Create a pitch deck", format_category="slides", format_width=1920, format_height=1080) # Create a PDF document (report, resume, etc.) start_design_task(prompt="Create a project report", format_category="pdf") # Provide reference images as attachments — file-id form (recommended) # Upload first, then reference the returned file_id with a role: uploaded = upload_file(source_url="https://example.com/reference.png") start_design_task( prompt="Recreate this design in our brand style", attachments=[{"file_id": uploaded["id"], "role": "reference", "label": "brand-style ref"}], brand_kit_id="880e8400..." ) # Or the legacy URL form — still accepted for hosted public URLs: start_design_task( prompt="Recreate this design in our brand style", attachments=[{"url": "https://example.com/reference.png", "type": "image"}], brand_kit_id="880e8400..." ) # Mix shapes in one call — a source brief plus a reference image: start_design_task( prompt="Build a pitch deck from the brief; match the reference style", attachments=[ {"file_id": "file_01HT9W…", "role": "source", "label": "Q2 strategy brief"}, {"file_id": "file_01HT9X…", "role": "reference"}, ], ) # Use existing canvases as design inspiration start_design_task( prompt="Create a similar landing page", reference_canvas_ids=["550e8400...", "660e8400..."] ) # Canonical MCP flow: start -> poll -> read result.export (no second render) task = start_design_task(prompt="Create a sales deck", format_category="slides") status = get_task_status(task_id=task["task_id"]) while not status["can_export"] and not status["is_terminal"]: # Wait status["retry_after_seconds"] seconds, then poll again. status = get_task_status(task_id=task["task_id"]) # When the task auto-exports successfully, the rendered file rides in # status["result"]["export"] — read it directly instead of calling # export_canvas (the cache would hit, but result.export saves a round trip). if status["can_export"]: export_info = status["result"]["export"] print(export_info["url"], export_info["format"]) # e.g. ".../abc.pptx", "pptx" # Opt out of the auto-export when you don't need it: start_design_task(prompt="Iterate on the layout", canvas_id="550e8400...", export_on_complete={"enabled": False}) # Or override the format/scale (e.g. PDF instead of the slides category default): start_design_task(prompt="Build a deck", format_category="slides", export_on_complete={"format": "pdf", "pixel_ratio": 3}) ``` ### Notes * The default `wait=False` returns a task handle in milliseconds. Pass `wait=True` only when you specifically want a single blocking call. * On iframe-aware hosts (claude.ai web, Claude Desktop), the paired Design Task Progress app polls and renders pages on its own — see [Interactive Apps](/mcp/interactive-apps). * Use `retry_after_seconds` as the default delay before the first `get_task_status(task_id)` call * Keep polling until `can_export == true` or `is_terminal == true` * `can_export` describes the canvas, not the outcome: it becomes `true` for any terminal task whose canvas has renderable pages, even if the task itself failed * A new design (no `canvas_id`, `conversation_id`, or `template_canvas_id`) needs a brand choice — `brand_kit_id`, `skip_brand_kit=true`, or a session pin. Without one it is refused with `brand_kit_choice_required` — whatever the kit count, even with a team default — listing the kits so the agent can ask the user: one of them, a new kit, or none. Edits keep the canvas's own kit * If no `canvas_id` is provided, a new canvas is created with the name from `canvas_name` or "Untitled" * Every response includes a `conversation_id`. Pass it back in subsequent calls so the agent has context of all previous interactions. * When resuming a conversation, the `canvas_id` parameter is ignored — the agent automatically operates on the conversation's canvas * Use `upload_file` to upload local files first, then pass the returned `file_id` in an `attachments` item with a `role` (`source` / `reference` / `asset` / `import`). `import` is PPTX-only — it loads the deck onto the canvas as editable slides. The older URL form is still accepted but drops role metadata. * Reference canvas IDs let the agent see and draw inspiration from existing designs without modifying them * Always pass `format_category` when creating new designs — without it, a fresh canvas is created as a generic `"other"` canvas at 1080×1080 with no format skill, so a deck/post/document gets a generic layout * The auto-export attached to `result.export` is keyed identically to a follow-up `export_canvas(canvas_id=...)`, so calling `export_canvas` afterward with default args hits the cache instead of re-rendering. Pin `export_on_complete.format` and `export_on_complete.pixel_ratio` when you need a non-default artifact — the cache match depends on the exact `(format, pixel_ratio)` pair. *** ## get\_task\_status Returns the status and progress of a specific design task. Use this to check on tasks started with `start_design_task` or `remix_design`. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `task_id` | `string` | Yes | ID of the task to check | ### Returns ```json theme={null} { "task_id": "990e8400-e29b-41d4-a716-446655440000", "canvas_id": "550e8400-e29b-41d4-a716-446655440000", "canvas_url": "https://moda.app/canvas/550e8400-e29b-41d4-a716-446655440000", "conversation_id": "bb0e8400-e29b-41d4-a716-446655440000", "theme_canvas_id": null, "status": "running", "prompt": "Create a modern SaaS landing page...", "progress_percent": 45, "current_step": "Generating hero section", "is_terminal": false, "can_export": false, "retry_after_seconds": 3, "operations_streamed": 12, "created_at": "2025-03-15T10:30:00", "started_at": "2025-03-15T10:30:02", "completed_at": null, "error": null } ``` | Field | Type | Description | | - | - | - | | `task_id` | `string` | Task UUID | | `canvas_id` | `string` | Canvas being edited | | `canvas_url` | `string` | Direct link to the canvas | | `conversation_id` | `string` | Conversation UUID. Pass to `start_design_task` to resume the conversation. | | `theme_canvas_id` | `string` | Brand-kit slides theme attached to the canvas, or `null` when unthemed. | | `status` | `string` | `queued`, `running`, `cancelling`, `completed`, `failed`, `cancelled`, `dead_letter`, `canvas_deleted`, or `insufficient_credits` | | `prompt` | `string` | The original prompt, in full | | `progress_percent` | `integer` | Estimated progress (0-100), if available | | `current_step` | `string` | Description of what the agent is currently doing | | `is_terminal` | `boolean` | `true` when the task is finished and polling can stop | | `can_export` | `boolean` | `true` when the task is terminal and the canvas has exportable content, so `export_canvas` can be called — set even for failed or dead-lettered tasks | | `retry_after_seconds` | `integer` | Suggested delay before polling again when the task is still in progress | | `operations_streamed` | `integer` | Number of canvas operations applied so far | | `created_at` | `string` | Job creation timestamp (ISO 8601) | | `started_at` | `string` | When the agent started working (ISO 8601) | | `completed_at` | `string` | When the task finished (ISO 8601), or `null` | | `error` | `string` | Error message if the task failed, or `null` | ### Notes * Use this after `start_design_task` to poll for progress * Poll again after `retry_after_seconds` while `is_terminal == false` * On `status="completed"`, the response carries a `result.export` block (`{url, format, status, page_count}`) with the auto-exported design — read it directly instead of calling `export_canvas` for the same canvas. If the auto-export was disabled via `export_on_complete: {enabled: false}`, or skipped because the resolved format is a video (an `animation` canvas with no explicit `export_on_complete.format`), `result.export` is absent. * Failed or cancelled tasks are terminal and still set `can_export` when the canvas has renderable pages — if `can_export` is `true`, export the design rather than regenerating it * The `prompt` field carries the user's original prompt in full (the task-progress iframe surfaces it verbatim) *** ## list\_tasks Returns a list of recent design tasks. Use this to see what design tasks have been run recently, optionally filtered by canvas or status. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. ### Parameters | Parameter | Type | Required | Default | Description | | - | - | - | - | - | | `canvas_id` | `string` | No | — | Filter tasks to a specific canvas | | `status` | `string` | No | — | Filter by status (`queued`, `running`, `cancelling`, `completed`, `failed`, `cancelled`, `dead_letter`, `canvas_deleted`, `insufficient_credits`) | | `limit` | `integer` | No | `10` | Number of tasks to return (max 50) | ### Returns ```json theme={null} { "tasks": [ { "task_id": "990e8400-e29b-41d4-a716-446655440000", "canvas_id": "550e8400-e29b-41d4-a716-446655440000", "canvas_url": "https://moda.app/canvas/550e8400-e29b-41d4-a716-446655440000", "conversation_id": "bb0e8400-e29b-41d4-a716-446655440000", "theme_canvas_id": null, "status": "completed", "prompt": "Create a modern SaaS landing page...", "progress_percent": 100, "current_step": null, "operations_streamed": 42, "created_at": "2025-03-15T10:30:00", "started_at": "2025-03-15T10:30:02", "completed_at": "2025-03-15T10:32:15", "error": null } ] } ``` ### Notes * Tasks are returned in order of most recently created * The maximum `limit` is 50 per request * Only tasks for canvases you have access to are returned *** ## remix\_design Duplicates an existing canvas and optionally starts a design task on the copy. Use this to create variations of existing designs without modifying the original. When a prompt is provided, the call blocks by default (`wait=true`, unlike `start_design_task`) until the agent finishes and returns the completed remix — pass `wait=false` to get a task handle immediately and poll `get_task_status` the same way as `start_design_task`. Uses your session context (set via `set_context`) or defaults to your primary workspace. > [!NOTE] > > This tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. It is not > available when using the local `stdio` server. ### Parameters | Parameter | Type | Required | Default | Description | | - | - | - | - | - | | `canvas_id` | `string` | Yes | — | Canvas to duplicate | | `prompt` | `string` | No | — | Design instructions to apply to the copy. Omit for a plain duplicate. | | `new_name` | `string` | No | — | Name for the new canvas. Defaults to `"Remix of "`. | | `wait` | `boolean` | No | `true` | When `true` (default) and a `prompt` is supplied, block until the agent finishes and return the completed remix. Pass `false` to get a task handle immediately. | | `brand_kit_id` | `string` | No | — | Brand kit to apply (only used when `prompt` is provided) | | `org_id` | `string` | No | — | Organization UUID. Overrides session context for this call. | | `team_id` | `string` | No | — | Team UUID. Overrides session context for this call. | ### Returns Without a prompt (plain duplicate): ```json theme={null} { "canvas_id": "aa0e8400-e29b-41d4-a716-446655440000", "canvas_url": "https://moda.app/canvas/aa0e8400-e29b-41d4-a716-446655440000", "canvas_name": "Remix of Marketing Website", "source_canvas_id": "550e8400-e29b-41d4-a716-446655440000", "message": "Canvas duplicated successfully." } ``` With a prompt and `wait=false` (duplicate + backgrounded design task): ```json theme={null} { "canvas_id": "aa0e8400-e29b-41d4-a716-446655440000", "canvas_url": "https://moda.app/canvas/aa0e8400-e29b-41d4-a716-446655440000", "canvas_name": "Remix of Marketing Website", "source_canvas_id": "550e8400-e29b-41d4-a716-446655440000", "task_id": "990e8400-e29b-41d4-a716-446655440000", "task_status": "queued", "message": "Design task started. Use get_task_status to check progress.", "retry_after_seconds": 3 } ``` ### Example usage ``` # Plain duplicate remix_design(canvas_id="550e8400...") # Duplicate and restyle remix_design(canvas_id="550e8400...", prompt="Change the color scheme to dark mode") # Duplicate with new branding remix_design(canvas_id="550e8400...", prompt="Apply our new brand", brand_kit_id="880e8400...") ``` ### Notes * The original canvas is never modified — all changes are applied to the copy * When a `prompt` is provided, a design task is started on the duplicate; with the default `wait=true` the call blocks until the task finishes — pass `wait=false` to return immediately with a task handle * Poll `get_task_status(task_id)` until `can_export == true` or the task reaches a terminal failure state, same as `start_design_task` *** ## Websites Moda websites are HTML projects you can draft and manage, then publish from the Moda editor to a public `*.moda.page` URL. These MCP tools let your agent draft, inspect, and update websites in Moda — available to every authenticated MCP user. Publishing the resulting draft is opt-in: `create_website_from_upload` and `update_website_from_upload` both accept a `publish` flag that defaults to `false`. Publishing runs through Moda's server-side publish gate (content screening plus publish-rate, live-site, and new-account quotas); when the gate blocks a publish the draft is still saved and the response comes back with `published_url: null`. The user can publish from the editor once any blocking gate condition clears — the editor runs through the same gate. HTML payloads are uploaded out-of-band (presigned URL → PUT bytes → call the tool with the returned `storage_key`) so large HTML documents — especially ones with inlined base64 images — don't have to pass through MCP tool args. Inline `data:` images are extracted to Moda Files automatically so the published artifact stays small. > [!NOTE] > > Every website tool requires [authentication](/mcp/authentication) via the remote MCP server at `mcp.moda.app`. The > local `stdio` server does not expose them. *** ## list\_my\_websites Lists the websites visible to the caller in the active team, newest-updated first. Scoped to the team in your session context — call `set_context` first if you belong to multiple teams. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `limit` | `integer` | No | Page size (default 20, clamped to 100 server-side). | | `offset` | `integer` | No | Pagination offset, 0-indexed. | ### Returns ```json theme={null} { "websites": [ { "id": "bb0e8400-e29b-41d4-a716-446655440000", "title": "Launch Announcement", "url": "https://launch-announcement.moda.page", "share_state": "public", "comments_enabled": true, "recent_comments_count": 3, "updated_at": "2026-05-26T17:42:11Z" } ], "total": 1, "limit": 20, "offset": 0, "has_more": false } ``` `url` is `null` for unpublished drafts. *** ## get\_website Fetches the full agent-facing projection of one website — the source HTML for the home page, title, share state, comments toggle, editor URL, and (if published) the live `*.moda.page` URL. Use this before calling `update_website_from_upload` so the agent has the current source as a base. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `website_id` | `string` | Yes | ID of the website to fetch. | ### Returns ```json theme={null} { "website_id": "bb0e8400-e29b-41d4-a716-446655440000", "title": "Launch Announcement", "html": "…", "editor_url": "https://moda.app/website/bb0e8400-e29b-41d4-a716-446655440000?source=agent", "published_url": "https://launch-announcement.moda.page", "url": "https://launch-announcement.moda.page", "share_state": "public", "comments_enabled": true, "recent_comments_summary": [] } ``` `published_url` and `url` are both `null` for unpublished drafts. `url` is a deprecated alias kept for backward compatibility — prefer `published_url` in new code. *** ## create\_website\_from\_upload Creates a new Moda website from an HTML file. The HTML is uploaded out-of-band first so large documents (especially ones with inlined base64 images) don't have to pass through MCP args. **Required upload sequence:** 1. `create_upload_url(filename="site.html", mime_type="text/html")` → returns `{upload_url, storage_key}`. 2. PUT the HTML bytes to `upload_url` with header `Content-Type: text/html`. 3. Call `create_website_from_upload(storage_key=…)` with the `storage_key` from step 1. Server-side, Moda extracts every inline `data:image/…` URI to a CDN-hosted Moda File, rewrites the HTML to reference the proxy URL, then creates the website row. Sites default to `category='html-document'`, `share_state='unlisted'`, and `comments_enabled=true`. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `storage_key` | `string` | Yes | The `storage_key` from `create_upload_url`, after you PUT the HTML bytes to its `upload_url`. Not the `upload_url` itself, not a filename. | | `title` | `string` | No | Display title. Omit to let Moda auto-generate a title from the page content. | | `publish` | `boolean` | No | When `true`, also publish to a slugified `*.moda.page` URL. Defaults to `false` (draft only). Subject to the server-side publish gate (content screening and publish quotas); if the gate blocks the publish the draft is still saved and `published_url` comes back `null`. | | `category` | `string` | No | Website category. Defaults to `html-document` for uploaded HTML documents. Valid values are `html-document`, `landing-page`, `email`, and `other`. | ### Returns ```json theme={null} { "website_id": "bb0e8400-e29b-41d4-a716-446655440000", "editor_url": "https://moda.app/website/bb0e8400-e29b-41d4-a716-446655440000?source=agent", "published_url": "https://launch-announcement.moda.page", "share_state": "unlisted", "comments_enabled": true, "extracted_image_count": 4, "skipped_inline_asset_count": 0 } ``` * `editor_url` is always present — give this link to the user. The `?source=agent` marker is a presentation hint the app consumes when the link opens; pass the URL through unchanged. * `published_url` is the live `*.moda.page` URL when `publish=true` succeeded; `null` for drafts. Do **not** fabricate a `*.moda.page` URL from the `website_id`. *** ## update\_website\_from\_upload Replace the HTML and/or title of an existing website. The website\_id is preserved, existing comments stay anchored via a reconciliation pass over the new DOM, and inline `data:` images in the uploaded HTML are extracted to Moda Files (same pipeline as `create_website_from_upload`). Same upload sequence as `create_website_from_upload` — omit `storage_key` to keep the current HTML and only rename via `title`. ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `website_id` | `string` | Yes | The website's ID. | | `storage_key` | `string` | No | `storage_key` from `create_upload_url` after you PUT the new HTML bytes. Omit to keep the current HTML and only change the title. | | `title` | `string` | No | New display title. Omit to keep the current title. | | `publish` | `boolean` | No | When `true`, republish so the live URL reflects the new content. Defaults to `false` (draft update). Subject to the same server-side publish gate as `create_website_from_upload`. | Supply at least one of `storage_key` or `title` — a call with neither is rejected. ### Returns ```json theme={null} { "website_id": "bb0e8400-e29b-41d4-a716-446655440000", "editor_url": "https://moda.app/website/bb0e8400-e29b-41d4-a716-446655440000?source=agent", "published_url": "https://launch-announcement.moda.page", "updated_at": "2026-05-26T17:42:11Z", "extracted_image_count": 4, "skipped_inline_asset_count": 0 } ``` `published_url` is `null` when `publish=false` — the live URL keeps serving the previously-published version until the user republishes from the editor.