Skip to content

About

Drive Gaffer with AI over the Model Context Protocol — 87 tools to build, query and render Gaffer scenes from Claude Code and any MCP client.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

gaffer_mcp

English · 中文

Drive Gaffer with AI (Claude Code or any MCP client) over the Model Context Protocol. Two modes:

Mode Tool GUI? Use case
Headless script run_script No One instruction → one script → delivered .gfr / rendered image
Drive live GUI the other 86 Yes Build and wire node graphs, query scenes and images, EditScope non-destructive edits, expressions and keyframes, dispatch renders, screenshots — all live and Ctrl+Z undoable

The 86 GUI tools are distilled from Gaffer's own test suite and verified against Gaffer 1.6.5.1.

This repo is a standard Gaffer extension — pure Python plus startup scripts, zero dependencies. It loads automatically via GAFFER_EXTENSION_PATHS. No rez, no studio pipeline.

Tools are plugin-based: one tool = one function + one decorator, schema and implementation in one place. Add a tool by dropping a .py file into tools/ (shipped) or ~/.gaffer_mcp/tools/ (personal) — no server edits, no bridge edits, no Gaffer restart.

Layout

gaffer_MCP/                    ← this directory is a Gaffer extension root
├── launch.sh                  ← one-shot launcher: sets GAFFER_EXTENSION_PATHS, then runs Gaffer
├── python/
│   ├── gaffer_mcp_api.py       ← authoring API: @tool decorator / P params / Context
│   ├── gaffer_mcp_util.py      ← Gaffer-side helpers (find nodes, read/write plugs, summaries…)
│   ├── gaffer_mcp_loader.py    ← discovers and hot-reloads tool files
│   └── gaffer_mcp_gui.py       ← GUI-side bridge (local TCP, UI thread + UndoScope dispatch)
├── tools/                      ← shipped tools (each file = one group)
│   ├── 00_session.py           ← get_status / list_scripts / select_script / new / open / save
│   ├── 10_nodes.py             ← add_node / list_node_types / rename / delete / apply_preset
│   ├── 20_graph.py             ← get_graph / get_node
│   ├── 30_plugs.py             ← set/get_plug_value / connect / disconnect
│   ├── 32_dynamic_plugs.py     ← add_plug / remove_plug / list_plug_types
│   ├── 34_spreadsheet.py       ← Spreadsheet rows / columns / cells
│   ├── 40_scene.py             ← evaluate_scene
│   ├── 42_scene_query.py       ← hierarchy / matching paths / sets / globals / geometry / history
│   ├── 44_edit_scope.py        ← EditScope non-destructive edits
│   ├── 46_shader.py            ← load_shader / get_shader_network
│   ├── 48_image.py             ← evaluate_image / image_stats / sample_pixel
│   ├── 50_box.py               ← Box / promote plugs / export .grf / Reference
│   ├── 52_script.py            ← serialise / duplicate / batch delete / undo / selection
│   ├── 54_metadata.py          ← metadata / colour / annotation / bookmarks / position / read-only
│   ├── 56_time.py              ← frames / context variables / Expression / keyframes
│   ├── 58_dispatch.py          ← list_task_nodes / dispatch_task
│   ├── 60_ui.py                ← screenshot / editors / scene selection / auto-layout
│   └── 90_python.py            ← run_python (escape hatch, kept last on purpose)
├── startup/gui/gaffer_mcp.py   ← startup shim: starts the bridge at GUI launch
└── server/
    ├── gaffer_mcp.py           ← MCP stdio server (pure stdlib, no Gaffer import)
    ├── headless.py             ← headless run_script tool (spawns `gaffer env python`)
    └── tools_seed.json         ← offline fallback tool list (served when Gaffer is closed)

How it works

MCP client (Claude Code)
   │  stdio (JSON-RPC over stdin/stdout)
   ▼
server/gaffer_mcp.py          ← pure stdio server, starts instantly, no hardcoded tool list
   │  TCP 127.0.0.1:<port> (token-auth; connection info in ~/.gaffer_mcp/connection.json)
   ▼
python/gaffer_mcp_gui.py      ← runs inside the Gaffer GUI process
   │  GafferUI.EventLoop.executeOnUIThread + Gaffer.UndoScope
   ▼
tools/*.py + ~/.gaffer_mcp/tools/*.py   ← tool implementations (@tool registered)
   ▼
Gaffer node graph (live, Ctrl+Z undoable)
  • The server never imports Gaffer, so MCP sessions start instantly and can't crash the client.
  • The bridge dispatches on the UI thread; undo=True tools run inside an UndoScope so artists can Ctrl+Z.
  • The tool list comes from the bridge (internal op __list_tools), cached in ~/.gaffer_mcp/tools_cache.json. When Gaffer is closed it falls back to the cache, then server/tools_seed.json, so the client still sees the tools and calling one returns a clear "start Gaffer" error.
  • Argument validation happens once in bind(); handlers receive converted keyword arguments with consistent, AI-friendly errors.
  • All writes stay under $HOME / /tmp — the Gaffer install is never touched.

Quick start

1. Load the extension into Gaffer

Add this repo to GAFFER_EXTENSION_PATHS. Gaffer adds <repo>/python to sys.path and runs <repo>/startup/gui/gaffer_mcp.py at GUI startup, which starts the bridge.

One-shot (recommended):

./launch.sh

Or manually:

export GAFFER_EXTENSION_PATHS="/path/to/gaffer_MCP${GAFFER_EXTENSION_PATHS:+:$GAFFER_EXTENSION_PATHS}"
gaffer

You should see:

[gaffer_mcp] loaded 86 tool(s) from 18 file(s)
[gaffer_mcp] bridge listening on 127.0.0.1:<port>

2. Register the MCP server with Claude Code

Copy the repo's .mcp.json into your project (or into ~/.claude.json):

{
  "mcpServers": {
    "gaffer": {
      "type": "stdio",
      "command": "python3",
      "args": ["./server/gaffer_mcp.py"]
    }
  }
}

The relative path resolves against the repo root; use an absolute path if it doesn't. server/gaffer_mcp.py is pure stdlib — plain python3, no Gaffer environment needed.

3. Use it

Start the Gaffer GUI first (the bridge comes up with it), then start or reconnect the MCP session. If no GUI is running, tools return a "no running Gaffer GUI" message.

Environment variables

Variable Purpose
GAFFER_EXTENSION_PATHS Standard Gaffer extension search path — add this repo to load it
GAFFER_MCP_PORT Bridge port (default 24745; falls back to a random port if taken)
GAFFER_MCP_TOOL_PATHS Extra tool directories, colon-separated
GAFFER_MCP_STATE_DIR Where the connection file / tool cache / personal tools live (default ~/.gaffer_mcp). Set on both the server and Gaffer sides, or they won't find each other
GAFFER_MCP_TOOLS_RECHECK_INTERVAL Minimum seconds between tool-set refresh checks (default 10)
GAFFER_MCP_GAFFER Gaffer launcher used by headless run_script (default gaffer, resolved from PATH)
GAFFER_MCP_OUT_DIR Headless output directory (default ~/.gaffer_mcp/headless_out)
GAFFER_MCP_NOISE_RE Regex for stdout lines to filter out in headless mode (default: none)

Headless mode (run_script)

No GUI needed. One instruction → one script → delivered files.

The unit of work is a script, not an API call: one script = one task = one transaction. Nothing half-applied survives a failure, and a .gfr is a Python script, so "write a .gfr" and "write a script" are the same act.

The script itself is a deliverable too — archived next to its outputs at <outputDir>/scripts/<timestamp>_<label>_<hash>.py, as the readable record of what was done.

Requires the Gaffer launcher on PATH (or set GAFFER_MCP_GAFFER):

export GAFFER_MCP_GAFFER="/path/to/gaffer/bin/gaffer"

Two ways to call it:

# MCP tool (for clients)
run_script(code="...", label="sphere")

# CLI (same code path; works even before the MCP tool is mounted)
python3 server/headless.py task.py --label sphere
python3 server/headless.py <archived script> --label rerun

Scripts can import Gaffer / GafferScene / GafferImage / GafferArnold / IECore / imath directly and read the output directory from GAFFER_MCP_OUT. Don't add an if __name__ == "__main__": guard.

⚠️ hasTrouble — headless Gaffer keeps running after a single plug error and writes results using default values. A KeyError from a mistyped plug name still produces an image, just with defaults. The result flags any Traceback/ERROR via hasTrouble; review it even when exitCode=0 and files were produced.

Tools (86)

Session & scripts

Tool Does
get_status session status & connection info
list_scripts / select_script / new_script / open_script / save_script script management
serialise_nodes / execute_serialisation graph ↔ Gaffer Python code; the latter builds whole subgraphs
duplicate_nodes / delete_nodes duplicate (keeping internal connections) / batch delete (auto-reconnect neighbours)
undo / redo the same undo queue as the GUI
select_nodes / get_selection node selection & focus (focus decides what the Viewer shows)

Nodes & plugs

Tool Does
add_node create a node (full type name like GafferScene::Plane), with optional initial plug values / position
list_node_types list creatable node types under a module
get_graph / get_node read graph structure & node detail
rename_node / delete_node / apply_preset rename / delete / apply a preset
set_plug_value / get_plug_value read/write plug values (incl. vector-data plugs like PathFilter.paths)
connect / disconnect connect / disconnect (ArrayPlug picks the next free slot)
add_plug / remove_plug / list_plug_types create plugs at runtime: user params, CompoundDataPlug members (attributes/variables/tweaks)

Spreadsheet

Tool Does
spreadsheet_info columns / rows / cells / selector / enabledRowNames
spreadsheet_add_column / spreadsheet_add_row / spreadsheet_set_cell / spreadsheet_remove_row add / edit / remove

Works on any RowsPlug (shared nodes can promote rows onto a Box — pass node=Box, plug=rows).

Scene

Tool Does
evaluate_scene evaluate one location (bound/transform/childNames/attributes/object)
scene_hierarchy recursive hierarchy tree (like HierarchyView), with depth/count limits
scene_matching_paths expand filter nodes / wildcards / set expressions into real paths
scene_sets set names & members
scene_globals render options & AOV outputs
scene_object geometry detail: topology counts, primitive variables, camera params
scene_history trace which node made a location's attribute/object/transform
scene_find_by_attribute find all locations carrying an attribute (lights, standins, volumes…)

EditScope (non-destructive edits)

Tool Does
edit_scope_setup set up and connect to an upstream scene plug (required after add_node)
edit_scope_transform / edit_scope_prune / edit_scope_visibility move / prune / hide
edit_scope_attribute / edit_scope_set_membership tweak attributes / set membership

Shaders & images

Tool Does
load_shader create a shader node and loadShader (a bare add_node shader is empty)
get_shader_network read a location's material/light network: shaders, params, connections
evaluate_image / image_stats / sample_pixel image info / region statistics / pixel sampling

Box, Reference, metadata

Tool Does
box_nodes / promote_plug / unpromote_plug / list_promoted_plugs box a subgraph, promote exposed params
export_reference / load_reference export a .grf / reference a .grf (shared node libraries)
set_metadata / get_metadata read/write arbitrary metadata
set_node_color / set_annotation / get_annotations node colour & notes
set_bookmark / list_bookmarks bookmarks & numeric bookmarks
set_node_position / get_node_positions / set_read_only graph positions / read-only protection

Time, expressions, animation, dispatch

Tool Does
get_time / set_time current frame, frame range, fps
set_context_variable / list_context_variables / remove_context_variable script context variables (${shot} etc.)
set_expression / get_expression Expression nodes (python / OSL)
set_keyframe / get_animation / remove_keyframe keyframes
list_task_nodes / dispatch_task list & dispatch task nodes (render / write / PythonCommand)

GUI

Tool Does
screenshot capture a window or editor panel as PNG — let the AI see what the artist sees
list_editors editor panels in the current layout (for screenshot)
set_scene_selection / get_scene_selection Viewer/HierarchyView scene-path selection & expansion
layout_nodes auto-layout the Graph Editor and persist positions

Escape hatch

Tool Does
run_python run arbitrary Python on the UI thread (prefer the structured tools)

Adding your own tools

Drop a file in ~/.gaffer_mcp/tools/my_tools.py (personal) or tools/ (shipped):

from gaffer_mcp_api import tool, P, util, ToolError
import Gaffer


@tool(
    "graph_summary",
    "Summarize the current graph. Returns {nodeCount, types}.",
    params = {
        "prefix": P.str("only count nodes whose name starts with this", default=""),
    },
)
def graphSummary(ctx, prefix):
    nodes = [n for n in ctx.script.children(Gaffer.Node) if n.getName().startswith(prefix)]
    return {"nodeCount": len(nodes), "types": sorted({n.typeName() for n in nodes})}

Takes effect on save: the bridge detects the mtime change and asks the client to refresh the tool list (notifications/tools/list_changed). No Gaffer restart, no server edit.

Decorator params

Param Purpose
params {name: P.<type>(...)}, passed to the function as kwargs with defaults applied
undo=True wrap the call in Gaffer.UndoScope(script) — set on every graph-mutating tool
dirty=True mark the script modified on success
maxResultChars advertise a bigger result budget for tools that return a lot

Param types

P.str / P.int / P.float / P.bool / P.enum(desc, [...]) / P.list(desc, items="number") / P.dict / P.any, all supporting required=True, default=, minimum= / maximum=.

Handler context

  • ctx.script / ctx.scripts / ctx.application
  • ctx.node("Sphere"), ctx.node("Box.Sphere"), ctx.plug(node, "transform.translate") — raise a ToolError with the available names when not found
  • ctx.undo() (context manager), ctx.markDirty()
  • util.* helpers (see python/gaffer_mcp_util.py)
  • raise ToolError("message", code="my_code") to fail cleanly — any exception becomes an MCP tool error without killing the Gaffer session

Load order (later wins on name collision): tools/*.py → $GAFFER_MCP_TOOL_PATHS → ~/.gaffer_mcp/tools/*.py. Filenames starting with _ or . are skipped.

License

MIT © WangSnowchen

About

Drive Gaffer with AI over the Model Context Protocol — 87 tools to build, query and render Gaffer scenes from Claude Code and any MCP client.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages