PatchWork Docs v0.9.21
GitHub Open PatchWork

PatchWork Technical Documentation

PatchWork is a high-performance visual node-based workflow automation platform for AI-powered image, video, and audio generation. It bridges human creators and autonomous AI agents via the Model Context Protocol (MCP).

Zero-dependency & Pure Vanilla Architecture: PatchWork frontend runs entirely on Vanilla JavaScript (ES6+) and LiteGraph.js with no bundler, no node_modules in the browser, and pure Premiere-style timeline maths for non-linear video editing.
Combined Node Architecture
Every generation node (nanobanana/Combined) is an all-in-one container: prompt inputs, parameters, candidate review gallery, and an approval gate. Downstream execution is strictly gated until candidate approval.
Premiere-Style TimelineEngine
A pure mathematical non-linear editing engine handling clamped & ripple trims, magnetic gaps, snapping, multi-track placement, and linked-audio reconciliation with frame-accurate WebCodecs export.
Full MCP Integration
50 tools exposing every surface to AI agents over standard stdio JSON-RPC 2.0: offline .nbflow authoring, live canvas steering, accounts storage, video timeline, assets, and in-app chat.
Cloudflare Edge & R2 Storage
WebSocket collaboration relay on Cloudflare Durable Objects, zero-egress asset storage on Cloudflare R2, and optimistic concurrency versioning with collision-proof UUIDs.

Quickstart & MCP Setup

The PatchWork MCP server is packaged in tools/patchwork-mcp.mjs. It requires Node.js ≥ 21 (which includes native global WebSocket support) and zero extra npm dependencies.

┌─ offline ──▶ .nbflow files on disk        (no browser, no key needed)
agent ──MCP──┤
             ├─ headless ─▶ accounts API worker         (browser closed, requires account token)
             └─ live ─────▶ collab relay ──▶ browser    (canvas, storage, assets, video editor)
            

Claude Code Configuration

The repository ships a pre-configured .mcp.json file at the project root. Claude Code automatically reads it:

.mcp.json (Project Root)
{
  "mcpServers": {
    "patchwork": {
      "command": "node",
      "args": ["tools/patchwork-mcp.mjs"],
      "env": {
        "PATCHWORK_AGENT_KEY": "YOUR_KEY_HERE"
      }
    }
  }
}

To register it globally across any folder via Claude Code CLI:

Terminal
claude mcp add patchwork -- node /path/to/Patchwork/tools/patchwork-mcp.mjs

Cursor & Windsurf Setup

Add the following to your Cursor or Windsurf MCP settings file (~/.cursor/mcp.json or Workspace settings):

Cursor / Windsurf mcp.json
{
  "mcpServers": {
    "patchwork": {
      "command": "node",
      "args": ["C:/Users/Privat/Documents/Claude Code/Patchwork/tools/patchwork-mcp.mjs"],
      "env": {
        "PATCHWORK_AGENT_KEY": "ABC123.s_xxxxxxxx"
      }
    }
  }
}

Authentication & Security

PatchWork provides two distinct authentication tiers based on operational requirements:

Auth Type Environment Variable / Location Scope & Capabilities
Agent Access Key PATCHWORK_AGENT_KEY or tools/.agent-key Live Canvas & Host Control: Grants access to the running browser window, allows queuing generations (spends credits), inspecting candidate images/videos, approving gates, and reading active timelines.
Account Session PATCHWORK_ACCOUNT_TOKEN or tools/.account-token Headless Cloud Storage: Allows creating, reading, editing, and listing stored cloud projects directly against the accounts worker with the browser completely shut.
No Auth (Offline) None needed Local File Operations: Full authoring, validation, inspection, and take reporting for .nbflow JSON files on disk.
Security Boundary: Treat the PATCHWORK_AGENT_KEY like a password. Anyone possessing it can command your open PatchWork canvas to run generations and incur API billing. You can revoke and re-roll the key anytime in Settings → Agent Access.

Workflow Engine Specification

PatchWork workflows enforce strict execution invariants defined in WORKFLOW-SPEC.md. Agents creating or executing graphs must respect these rules:

Rule 1: Generation nodes are GATES
Generating outputs creates takes (candidates). setOutputData is NEVER called automatically during generation. The node halts downstream execution until the user (or an agent via patchwork_approve) explicitly clicks Send.
Rule 2: Send triggers the WorkflowScheduler
Clicking Send approves the take, sets the output slot, and triggers scheduler.notify(nodeId). The scheduler scans downstream nodes and triggers those whose inputs are fully satisfied.
Rule 3: Completed nodes are NEVER re-run
Nodes that already hold valid output data are skipped by the scheduler cascade. Only unfulfilled downstream nodes (gap-fill) are executed.
Rule 4: Send NEVER triggers upstream
Approval cascades flow purely downstream. An approval at node 3 will never re-execute node 1 or 2 under any circumstance.

Offline .nbflow Tools

Direct inspection, batch editing, and pre-spend validation of .nbflow files without needing a running browser or network connection.

nbflow_inspect
Offline
Returns a compact, token-efficient structural digest of a .nbflow file on disk (nodes, prompts, models, wiring connections, and output take counts). Base64 images and large blobs are stripped.
Example Input
{ "file": "workflows/cinematic-story.nbflow" }
nbflow_apply
Offline
Executes batch mutations on a .nbflow file. Automatically lays out nodes using PatchWork's layered organizer (never send manual X/Y coordinates). Ops include: add_node, connect, set, remove_node, remove_link, add_tab.
Example Input
{
  "file": "story.nbflow",
  "name": "Portrait Scene",
  "ops": [
    { "op": "add_node", "type": "Generation", "title": "Hero Shot", "properties": { "masterPrompt": "Cinematic portrait, golden hour", "outputCount": 4 } },
    { "op": "add_node", "type": "Video", "title": "Hero Motion", "properties": { "masterPrompt": "Gentle wind in hair, slow zoom" } },
    { "op": "connect", "from": 1, "to": 2 }
  ]
}
nbflow_validate
Offline
Pre-Spend Validation Gate: Verifies graph schema consistency, link integrity, reference validity, and ensures every generation node will execute properly before any money is spent. Returns ok: false if errors exist.
Example Input
{ "file": "story.nbflow" }
nbflow_takes
Offline
Returns a complete inventory of generated takes across all nodes, structured in timeline narrative order. Identifies empty beats that still require generation.
nbflow_run / nbflow_run_start / nbflow_run_status / nbflow_run_cancel
OfflineBilling API
Direct execution of workflow files via backend generation APIs. nbflow_run blocks until completion, while nbflow_run_start launches detached background runs with supervisor survival.

Live Canvas Control

Control the active or background project in the user's running browser session.

patchwork_read
Live Canvas
Returns a compact structural digest of the graph running on the user's canvas (or any background project specified by project id/name).
Example Input
{ "project": "Commercial_V1" }
patchwork_edit
Live Canvas
Applies batch modifications in real time. If applied to the canvas, nodes update smoothly before the user's eyes. If applied to a background project, updates are persisted safely through cloud storage.
patchwork_run & patchwork_queue
Live CanvasSpends Credits
patchwork_run enqueues a generation request (same as clicking the Play button). Returns a runRequestId immediately. patchwork_queue manages pacing (max concurrent runs, reordering, status inspection, cancellation).
Queue Run Example
{
  "project": "Cyberpunk_Teaser",
  "tab": "Scene 1",
  "mode": "gap-fill"
}
patchwork_candidates & patchwork_approve
Live Canvas
The core tools of the autonomous operator loop: patchwork_candidates downloads and extracts an approval gate's take images/videos to disk for agent evaluation. Once the agent selects the best candidate, patchwork_approve marks the candidate and triggers downstream nodes.
Approve Candidate Example
{
  "project": "Cyberpunk_Teaser",
  "nodeId": 14,
  "candidateIndex": 2
}
patchwork_gen_status / patchwork_select / patchwork_regenerate / patchwork_status
Live Canvas
Poll generation progress per node, preview specific candidates on screen, reject entire batches to regenerate with modified prompts, and check relay connectivity.

Projects Storage API

Direct access to project storage with background execution and optimistic concurrency guards.

Tool Purpose Headless Capable
patchwork_projects Lists all projects on the account with IDs, names, folders, and generation progress. Yes
patchwork_project_create Creates a project from ops or pushes a .nbflow directly to cloud storage. Yes
patchwork_project_inspect Reads a structural digest of any stored project without opening it on screen. Yes
patchwork_project_edit Edits stored projects in place with expected_version optimistic concurrency protection. Yes
patchwork_project_manage Renames, describes, duplicates, deletes, or organizes projects into folders. Yes
patchwork_project_open Swaps the user's active canvas view to load and attach the specified project. Live Only
patchwork_project_unload Frees memory on the host by unloading inactive background projects. Live Only

Video Editor & Scene Builder

Full control over the non-linear timeline and multi-scene narrative sequence.

patchwork_editor_read & patchwork_editor_edit
Live Canvas
patchwork_editor_read inspects the active timeline tracks, clips, volume levels, text overlays, and keyframes. patchwork_editor_edit executes atomic timeline edits (moves, clamped trims, text insertion, clip replacements) bundled as a single undoable step.
patchwork_scene_read & patchwork_scene_edit
Live Canvas
Manage multi-scene narrative reels: read scene sequences, reorder scenes, assign generation takes directly to timeline beats, and switch active scenes.

App Surfaces

Query model catalogues, asset repositories, workspace teams, and server-side cloud rendering.

patchwork_models
Queries the live MODEL_REGISTRY for supported video/image models (Gemini Imagen 3, Veo 3.1, BytePlus SeedDream, Kling 2.0, RunPod LTX), including allowable aspect ratios, durations, and resolutions.
patchwork_assets
Interacts with the user's IndexedDB asset store: lists uploaded reference images, sound effects, voice recordings, and video clips by asset ID.
patchwork_render
Submits long-form server-side video rendering jobs, polls progress, and retrieves final rendered MP4 cloud URLs.
patchwork_workspaces
Inspects shared workspace teams, lists member roles, and toggles between Personal and Team workspace scopes.

In-App Claude Chat Channel

PatchWork includes an integrated chat panel (View → Claude Chat). Messages sent by the user in this panel are forwarded directly into your Claude Code session over the MCP claude/channel protocol.

Launch Claude Code with Chat Channel
PATCHWORK_CHANNEL=1 claude --dangerously-load-development-channels server:patchwork
patchwork_chat_reply
Chat Channel
Sends markdown responses directly back into the in-app chat panel. Text printed to the terminal does not reach the panel; only calls to this tool appear in the UI.
Example Input
{
  "chatId": "panel",
  "text": "Take 2 has sharper lighting and matches the reference style better. Sending it downstream now."
}

Autonomous Generation Operator Loop

How an autonomous agent drives end-to-end production runs:

Step Action MCP Tool
1. Build / Queue Draft or edit workflow graph, then queue execution. patchwork_editpatchwork_run
2. Wait for Gates Poll queue until status indicates generation completed at review gates. patchwork_queue get {id}
3. Inspect Candidates Extract generated take images to disk and visually analyze them. patchwork_candidates {nodeId}
4. Approve & Send Approve best take, which sends data and auto-triggers downstream nodes. patchwork_approve {nodeId, candidateIndex}
5. Repeat Loop continues until all gates are approved and timeline is complete.

Refusal & Error Code Reference

Error Code Meaning Recovery Strategy
HOST_OFFLINE Operation requires an active browser canvas, but PatchWork is closed. Ask user to launch PatchWork in browser, or use headless-capable tools.
PROJECT_BUSY Project is currently executing a generation cascade. Wait for patchwork_queue to finish, or cancel the active run.
AMBIGUOUS_PROJECT The project name prefix matched multiple projects. Pass the full project name or the crypto UUID.
PROJECT_NOT_FOUND No project with this ID or name exists on the account. List available projects with patchwork_projects.
409 Conflict Version mismatch during background edit. Re-read project with patchwork_project_inspect and reapply edits.