davinci-resolve-lua-mcp
CLAUDE.md4 starsChanged 2 months agoMITView on GitHub
Guidance for Claude Code in this repository. davinci-resolve-lua-mcp is an MCP server, shipped as an MCPB bundle for Claude Desktop, that controls the free edition of DaVinci Resolve 21.1 on macOS and, since 0.2.0 and experimentally, on Windows. Free 21.1 has no Python and no external scripting, and Blackmagic's own MCP server is Studio-only. The one door left is a Lua script launched from Workspace > Scripts inside Resolve: it receives the live resolve object and runs as a long-lived…
- Installs packages
- Commits and pushes
In this repositoryOne other file it gives its agents.
- create-readmeSkill
The file
We split this CLAUDE.md into the rules it gives an agent
12 rules. About 0 are common, 5 are distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- could be automatic: a setting could enforce it
- Distinctive: line 29
Not negotiable without the user's say-so.
- Distinctive: line 35
No network listeners of any kind.
- Very specific: line 36
Never modify anything under /Applications or /Library (Windows: C:\Program Files, %PROGRAMDATA%) without asking.
- Very specific: line 42
When the user must click something in Resolve or Claude Desktop, stop and ask.
- Very specific: line 44
Never launch the loop via fusion:Execute or a startup .scriptlib (either holds Fusion's shared script executor for the session).
- Very specific: line 51
Every tool declares title and annotations (read-only tools readOnlyHint.
- Very specific: line 55
Every string embedded in a Lua chunk goes through luaString() in src/lua.ts.
- Very specific: line 64
Run make test before a commit.
- Distinctive: line 76
Read and write memory files with the Read/Write tools only.
- Very specific: line 352
Before writing any Lua, read the shipped docs: the .pyi for every signature, argument order, return shape and enum.
- Distinctive: line 487
After every edit, read the diagnostics block.
- Distinctive: line 517
Never send mutating Lua to a real project.
≈ “Common” is an estimate: at least 1 in 5 of the 29,248 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
Guidance for Claude Code in this repository.
What this is
davinci-resolve-lua-mcp is an MCP server, shipped as an MCPB bundle for Claude Desktop, that
controls the free edition of DaVinci Resolve 21.1 on macOS and, since 0.2.0 and experimentally, on
Windows. Free 21.1 has no Python and no external scripting, and Blackmagic's own MCP server is
Studio-only. The one door left is a Lua script launched from Workspace > Scripts inside Resolve:
it receives the live resolve object and runs as a long-lived in-app bridge that executes Lua for
the server. Requests are a file the bridge reads with loadfile; responses go back through
fusion:SetPrefs + fusion:SavePrefs(), which the server reads from Fusion.prefs on disk. The
server is TypeScript on the v2 SDK (@modelcontextprotocol/server), bundled by esbuild into one CJS
file that Claude Desktop runs with its own Node. Version 0.1.0 was the first public release; 0.2.0
added the Windows port blind (no Windows machine): every Windows fact in this file is
documented-not-measured until the checklist in docs/windows.md has been run by a contributor.
README.md is the user documentation (install, start and stop, the 15-tool table with the run_lua
guide, the settings and RLB_* variables, troubleshooting, security, uninstall, the make targets);
do not repeat it here. CONTRIBUTING.md is the contributor guide (branch flow, the gate, the
release steps, the developer loop). SECURITY.md is the reporting policy; PRIVACY.md is the
privacy policy the extension directory requires (linked by the manifest's privacy_policies and
the README's Privacy Policy section; none of the three ships in the bundle). The planning documents
were removed before release, so this file and the code comments are the design record.
Rules
Not negotiable without the user's say-so.
- Architecture-level changes (the request file, the prefs response channel, the trust boundary, what runs inside Resolve, the runtime, the distribution format) are presented to the user as a tradeoff first. Implementation-level improvements can be adopted directly, with a note in a comment or here.
- stdout is the MCP transport:
console.errorand the file log only, neverconsole.loginsrc/. - No network listeners of any kind. Files in, prefs out.
- Never modify anything under
/Applicationsor/Library(Windows:C:\Program Files,%PROGRAMDATA%) without asking; Blackmagic's docs folder is read-only. The server writes only its state dir and the user Utility folder (its two Lua files) and never creates Resolve's folders. - Destructive tools take
confirm: bool = falseand refuse when false. Development never runs destructive Resolve operations except on objects the tests created; smoke runs and mutating Lua go only to a scratch project the user names, never to a real edit. - When the user must click something in Resolve or Claude Desktop, stop and ask; never assume it
happened.
make installandmake dev-register(it edits the real Claude config) only on request. - Never launch the loop via
fusion:Executeor a startup.scriptlib(either holds Fusion's shared script executor for the session). Scripts-menu launch only. - The bridge never writes prefs while idle (only per request, plus one
RLBSessionat start and one on clean stop), never deletes files, never callsos.exit, never blocks longer than one request, and stays one dependency-free file under 600 lines. - Responses are capped and list tools paginate (
offset+limit): everySavePrefsrewrites a ~22 KB file that Resolve loads at startup. - Every tool declares
titleandannotations(read-only toolsreadOnlyHint;run_luaanddelete_markersdestructiveHint; allopenWorldHint: false). Descriptions describe; cross-tool guidance lives in the serverinstructionsstring. Handlers never throw: every failure is anisErrorresult that names the next step. - Every string embedded in a Lua chunk goes through
luaString()insrc/lua.ts. Inputs are untrusted: zod enums, bounded ints, alimiton list tools.src/never spawns a process (the grep gate coverssrc/only; scripts and tests may spawn). - The manifest
tools[]equalstools/list, and the versions inpackage.json,manifest.jsonandSERVER_VERSION(src/server.ts) agree; one test enforces both. - v2 TypeScript SDK only (
McpServer,registerToolwithzod/v4,serveStdio;InMemoryTransportClientin tests); never the legacy@modelcontextprotocol/sdk1.x, never Python.
- Where Blackmagic's docs are silent (the host's libraries,
bmd.*,fusion:*Prefs, the sandbox), say so and rely on the measurements under "Resolve: measured facts". - Run
make testbefore a commit; commit after each unit of work with a clear message. - Nothing is pushed to
maindirectly: every change is a pull request from a short-lived branch, squash-merged once the three CI checks pass (a ruleset enforces it, with no bypass; the PR body is the commit message). A version bump is its own release PR, and the tag goes on that PR's merge commit, never on whatevermainmoved to since.
Environment traps
- A user-level PreToolUse hook blocks any Bash command whose text contains the literal
node_modules, even inside filters or heredocs. Build the string at run time (NM="node_""modules") or use Write/Edit; never retry the same command. - Another hook rejects any Bash command that names the memory directory or contains the word itself. Read and write memory files with the Read/Write tools only.
- Source nvm before Node tooling:
. ~/.nvm/nvm.sh. Thecompdef:153: _comps: assignment to invalid subscript rangeline is harmless zsh noise. The Makefile sources nvm itself unlessCIis set. - Foreground
sleepis blocked in the Bash tool. A long-running observer goes vianohup zsh script.sh args >/dev/null 2>&1 &thendisown, writes its pid to a file, and is killed explicitly at the end. - In the Bash tool (zsh),
${pipestatus[1]}is the exit code of a pipeline's first command.
Architecture (protocol v1)
Claude Desktop --stdio--> MCPB "DaVinci Resolve Lua MCP" = node ${__dirname}/server/index.js
| writes <state_dir>/next.lua (tmp + rename): return {v, id, session, op, ts, code=[==[...]==]}
| polls <prefs_dir>/*/Fusion.prefs for RLBResp = "<id>:<hex json>"
| (macOS ~/Library/.../Fusion/Profiles; Windows %APPDATA%\...\Support\Fusion\Profiles, unmeasured)
| deletes next.lua after the response (Lua cannot delete files)
| first run: copies bridge/resolve_mcp_bridge.lua + scripts/claude_diag.lua into the user Utility folder
v
bridge/resolve_mcp_bridge.lua (Scripts-menu Lua state, holds live `resolve`)
loop: bmd.wait(0.05); bmd.fileexists -> loadfile -> new id & our session? ->
loadstring+setfenv+xpcall with captured print -> SetPrefs(RLBResp)+SavePrefs
RLBSession written once at start; no fusion: calls while idle; stop = op="stop"; takeover = session mismatch
run needs the exact session id ("*" is for ping and stop only); a failed start save is retried once a second- Prefs keys sit under
Global.ResolveLuaBridge.:RLBResp,RLBSession, and the diagnostic keys (RLBDiag*,RLBMem,RLBLoop,RLBProbe*) the bridge clears at start. TheRLB_*/RLB*names and this prefix predate the project's rename and stay on purpose: installed scripts depend on them. - Caps: 64 KB of JSON by default, 192 KB hard ceiling (before hex); prints 200 lines, 16 KB, 2048
bytes per line (constants in the bridge's
PRINT_MAX_*/MAX_KB_*block andsrc/config.ts). Only the chunk's first return value is sent (extra_returns); dropped prints count inprints_dropped. - The bridge resolves its state dir as stamp >
RLB_STATE_DIRenv >HOME>USERPROFILE(Windows, whereHOMEis nil) > the home prefix ofMapPath("Profile:")(/Library/on macOS,AppDataon Windows); astate_dir_matchof false inresolve_statusmeans a hand-copied or stale script. On win32 the server spells the state dir with forward slashes (C:/Users/x/.davinci-resolve-lua-mcp) everywhere (config, stamp, log, status) so the stamp rule that refuses\holds;sameStateDir()inprotocol.tscompares the bridge's report with ours (either separator, case-insensitive on win32; trailing/only on macOS). After three consecutive failed runs whereGetVersionStringalso fails, the loop exits (statusno_reply,pid_alivetrue). - Runtime state:
RLB_STATE_DIR(default~/.davinci-resolve-lua-mcp, 0700 on macOS; Windows ignores the mode and inherits the profile ACLs) holdsnext.lua,next.lua.tmp,lock(a pid file hard-linked into place, taken per request, absent while idle),lock.takeover(exists only during the takeover of a dead holder's lock; one older than 30 s is abandoned and removed) andserver.log. No queue directories, no heartbeat file, no stop file.retryTransient()inprotocol.tsretriesEBUSY/EPERM/EACCESfor about a second on the request file's rename and delete only: Windows refuses both while the bridge'sloadfileholdsnext.luaopen (it re-reads the file every 50 ms), and never on the lock (Node-to-Node, opened with share-delete).main.tsalso handlesSIGBREAK(Windows Ctrl+Break); Claude Desktop stops the server by closing stdin on both platforms (Windows cannot deliver SIGTERM). - Layout:
src/(ten modules;main.tsis the wiring,server.tsthe tools,lua.tsthe snippets,protocol.tsthe slot and lock,prefs.tsthe reader,bridgeInstall.tsthe self-install),server/index.js(built, git-ignored, shipped),bridge/resolve_mcp_bridge.lua,scripts/(claude_diag.luaships;gen-types.mjs,dev-register.mjs,set-version.mjs,smoke.mjs,release-notes.sh,registry-entry.mjsare developer-only),types/resolve_host.d.lua+.luarc.json(Lua LSP),tests/,docs/(windows.md, the Windows assumptions and measurement checklist;images/, README screenshots; the MP4 recordings are git-ignored, GitHub-hosted),.github/(workflows/tests.yml,workflows/release.yml,dependabot.yml,pull_request_template.md),CONTRIBUTING.md,SECURITY.md,PRIVACY.md,.gitattributes(every text file LF).tsconfig.jsoncoverssrc/andtests/only. The bundle is exactly the eight files allowlisted intests/check_bundle.mjs; anything new goes into.mcpbignore(directories without trailing slashes:mcpb packwalks with theignorepackage after built-in excludes that do not covernode_modules,.claude,.rememberor.out).
Commands, CI and releasing
Targets (Makefile; the README has the table): test = test-lua + test-node; check-bridge,
lint-lua, gen-types; build, typecheck, check-server, inspect, bundle, clean;
install, sign, dev-register/dev-unregister, uninstall-bridge; smoke, stop.
fuscriptexits 0 whatever the script does, somake test-luapasses only on theRLB_TESTS_RESULT: PASSmarker line.make inspectspawns the server with a filtered environment: production paths and the first-run self-install into the real Utility folder. Otherwise drive the built server by hand: pipe JSON-RPC lines (initialize,notifications/initialized,tools/list,tools/call) intoRLB_STATE_DIR=<tmp> RLB_AUTO_INSTALL=false node server/index.js; answers come back one per line on stdout, the log on stderr; in-flight calls finish after stdin closes (5 s grace).- Syntax check of one Lua file:
fuscript -l lua -x 'assert(loadfile("<abs>/f.lua")); print("ok")', with the two-line banner filtered bygrep -v -e '^DaVinci Resolve Script' -e '^Copyright'. make smoke SMOKE_PROJECT="<open project>"mutates the named project (abridge-smoketimeline, the render TargetDir/CustomName, which the API cannot read back, hence the name must equal the open project's).SMOKE_FLAGS=--no-render,--timeout <s>; logs under.out/. The lock is per request, so it runs alongside the installed extension;lock_heldnames a pid whose request outlasted the wait (or a stale lock whose pid is alive). Without--project,scripts/smoke.mjsis the read-only coexistence check. A 10-minute watchdog fails the run when a modal in Resolve wedges the bridge; theManual cleanup in Resolve:line names what to delete by hand. The run refuses until the installed script equals the repo's: the server compares the stamped files byte for byte, so any edit to the bridge orclaude_diag.luareportsupdatedon the next start and the user must relaunchWorkspace > Scripts > resolve_mcp_bridge.make bundle=npm run bundle(npm puts the pinnedmcpbon PATH; nevernpx, unreliable on npm 11):mcpb validate,pack,info, thentests/check_bundle.mjs, which unpacks withmcpb unpack, checks the exact file list and the size, and probes the unpacked server over stdio (tools/list= 15 tools,resolve_status.platform=process.platform, no lock left) under temp dirs with the self-install off. Two packs give the same file list but different bytes (zip mtime); compare withzipinfo -1.make signis optional and self-signed.make dev-registermerges adavinci-resolve-lua-mcp-deventry into the real config after backing it up (flags in the script;--server <path>registers another checkout's build under the same key, replacing the previous entry). A code change then needsmake buildand a Claude Desktop restart. The dev entry and the installed extension answer to the same tool names: disable one while testing the other.- CI (
.github/workflows/tests.yml) runsmake test-nodeandmake bundleon macOS with Node 20 and 24, plus awindows-latestjob with Node 20 and no make (npm ci,bash tests/check_server.sh src,bash tests/lua/check_bridge.sh,npm run typecheck,npm run build,node --import tsx --test tests/*.test.tsunder Git Bash so the glob expands,npm run bundle);.gitattributesforces LF because the runner's Git hascore.autocrlf=true. Both run for branch pushes and pull requests and ignore tag pushes. The job namesnode 20,node 24andwindows node 20are the required status checks of themainruleset: renaming one blocks every PR until the ruleset is edited. Everyuses:is pinned to a full commit SHA with a# vNcomment and the repository settingsha_pinning_requiredrefuses a tag (arelease/X.Y.xbranch cut from a tag older than the pins needs that commit cherry-picked first);.github/dependabot.ymlrefreshes the pins and the npm devDependencies weekly in grouped PRs,@types/nodemajors ignored on purpose.tests.ymlcancels a superseded run of the same ref;release.ymlqueues under one fixedreleasegroup and never cancels.release.ymlstays macOS: the bundle is platform-neutral JS- Lua, one file serves both platforms, and the registry entry has no platform field.
release.ymlruns on av*tag push (only the admin role may create one, tag ruleset): a guard that the tag equalsv+ thepackage.jsonandmanifest.jsonversions, a guard that no release exists for the tag,make test-node,make bundle, a build-provenance attestation of the bundle (actions/attest-build-provenance, withid-tokenandattestationspermissions; the pack is not reproducible, so this is the only cryptographic link from the served bytes to the run),scripts/release-notes.sh, thengh release createwith the bundle attached (the README'sreleases/latest/download/...link follows it; releases are immutable, so the tag and the asset cannot change afterwards, only the notes). A second job then publishes the release to the MCP Registry asio.github.saadk408/davinci-resolve-lua-mcp: it downloads the asset the release serves, hashes it, generatesserver.jsonwithscripts/registry-entry.mjs(nothing is committed; the schema caps the description at 100 characters, so the script carries its own) and publishes withmcp-publisher login github-oidc;mcp-publisheris pinned to a release version and the sha256 of its linux_amd64 tarball in the job'senv(refresh both from theregistry_<version>_checksums.txtasset of the new release). If only that job fails,gh run rerun <id> --failedrepeats it alone. The Lua tests and the smoke test need Resolve and stay local.
- Lua, one file serves both platforms, and the registry entry has no platform field.
- GitHub settings (all set with
gh api, all reversible; CONTRIBUTING.md states the flow): amainruleset (a PR with zero approvals required, squash the only merge method, the three checks required, no force push or deletion, no bypass actors: the escape hatch is disabling the ruleset in Settings), arelease tagsruleset onrefs/tags/v*(creation, update and deletion only for the repository admin role, verified with GraphQLrepositoryRoleNamebecause REST returns only the numeric id), squash-only merge settings withPR_TITLEandPR_BODYas the commit message, head branches auto-deleted, auto-merge allowed (gh pr merge --squash --auto);sha_pinning_requiredand Dependabot alerts on; immutable releases on (Settings > Releases, the one UI-only switch). Secret scanning and push protection were already on; the non-provider-patterns toggle ignores the API on this repository and stays off. A contributor's first PR from a fork waits for the maintainer's approval before its checks run. - Releasing: on a
chore/release-X.Y.Zbranch,node scripts/set-version.mjs X.Y.Zwritespackage.json,manifest.jsonandSERVER_VERSION(textual edits of the version line;manifest.jsonis hand-formatted); when the Lua changed, also the bridge header (line 1 andVERSION),claude_diag.lua(line 1 andSCRIPT),BRIDGE_TAGintests/helpers/fakeBridge.tsand the envelope intests/prefs.test.ts. Thenmake lint-lua,make test,make bundle, the release PR with CI green (both jobs; there is no Windows smoke, the tag message says so). Staging on the real install: remove the installed extension under Settings > Extensions (a reinstall at an equal version shows no dialog),make install(the user's click), the user relaunches the script,make smokeon a scratch project (the smoke spawns the checkout's server; the install exercises the real install path), oneresolve_statusin a chat. Squash-merge, then tag the PR's merge commit, nevermainHEAD (a Dependabot merge may have landed since):sha=$(gh pr view <n> --json mergeCommit --jq .mergeCommit.oid), an annotated tag on it (git tag -a vX.Y.Z "$sha": its message becomes the intro of the release notes; a lightweight tag gets a one-line default) andgit push origin vX.Y.Z(never--tags): the workflow gates, packs, attests and publishes the release with the sha256 in the notes. Verify the served asset, neverdist/:gh release download vX.Y.Z --pattern '*.mcpb' --dir <tmp>,gh attestation verify <tmp>/davinci-resolve-lua-mcp.mcpb -R saadk408/davinci-resolve-lua-mcp, andgh api repos/saadk408/davinci-resolve-lua-mcp/releases/tags/vX.Y.Z --jq .immutableis true. The locally installed bundle is a different pack of the same files (mcpb packnever gives the same bytes twice), sodist/is never committed and a published tag is never re-run; fix forward with a new tag. Rolling back is installing the previous release's asset. A registry entry for a release the workflow did not publish (v0.1.0) is made by hand with the same script:node scripts/registry-entry.mjs vX.Y.Z <sha256 from gh release view --json assets> $(gh api repos/saadk408/davinci-resolve-lua-mcp --jq .id) > .out/server.json, thenmcp-publisher login github(Homebrewmcp-publisher, a browser device-code flow) andmcp-publisher publish .out/server.json.SECURITY.mdpromises support for the latest release only.
Tests
- Lua harness (
tests/lua/):fuscript -l lua <file>runs the main script in a sandbox whose__indexis_G, whiledofiled chunks run in_Gitself, so stubs go in withrawset(_G, ...),Resolveandbmd.scriptappare removed withrawset,bmdis replaced (waita no-op,gettimea clock the tests advance) andHOMEis redirected through the environment. The bridge is loaded withassert(loadfile(path))("RLB_BRIDGE_TESTING"), a vararg the menu host never passes, which makes it return its internals instead of starting the loop;start({resolve, fusion, state_dir, getenv})injects the rest.dkjsonandiocome fromrawget(_G, "require")andrawget(_G, "io")because.luarc.jsondisablespackageandio. Absolute paths everywhere. tests/lua/check_bridge.shgates: under 600 lines (four of headroom today), the two header lines, the stamp literal, forbidden names on comment-stripped lines, and exactly one:SetPrefs(,:SavePrefs(,:GetPrefs(call site each. A new prefs call or adebug./io.reference fails by design: reachdebugthroughgread, keep prefs writes insideset_pref/save_prefs.- Node suite (
node --testthroughtsx): never touches~/Library,/Libraryor%APPDATA%; theRLB_*directories point attests/helpers/tmp.tstemp dirs;tests/helpers/fakeBridge.tsanswersnext.luaby rewriting a Fusion-format prefs file and models the bridge's failure modes; tool tests use a recordingBridgestub (createServertakes the interface) and assert on the captured Lua; thefuscript-backed tests skip themselves when Resolve is absent. Test files cannot use top-levelawait(CJS); useexistsSyncfor skips. Files run concurrently, so after touching the locking inprotocol.tsloop the suite:for i in 1 2 3 4 5 6 7 8; do node --import tsx --test tests/*.test.ts | grep -q '^✖' && echo FAIL; done - On Windows:
config.test.tspins the platform explicitly in every default-path assertion (the win32 cases assert exactC:\...strings through theloadConfig(env, home, platform)seam), thedevRegister.test.tsmode assertions are guarded (a macOS tool), thefuscripttests skip,tools.test.tsbuilds itsTargetDirexpectation fromluaString(root)because backslashes are doubled;npm testcannot run under cmd.exe (no glob expansion), runnode --testfrom Git Bash. tests/check_server.shgrepssrc/(noconsole.log,process.stdout,child_process, network modules,.listen(, raw template holes in Lua strings) and every tracked file except the two gates for the vendor name it explains (git ls-files; outside a checkout, the shipped sources);tests/check_bundle.mjschecks the packed file list, size under 2 MB, that the same name is absent from the unpackedserver/index.js,manifest.jsonandpackage.json, and a stdiotools/list+resolve_statusprobe of the unpacked server under temp dirs with the self-install off (both platforms; it spawns the pinnedmcpb unpack).make lint-lua:gen-types.mjs --check(stale meansmake gen-types), thenlua-language-server --checkat Warning level as JSON in.out/luals-check.json; the server exits 1 whenever any diagnostic exists, so the target greps the report forbridge/andtests/(rc 127: binary missing). Accepted:claude_diag.luakeeps itsneed-check-nilwarnings and one deliberate undefinedioprobe. Probe the generated types with a scratch.luaunder the repo, then delete it.
Resolve: measured facts
Measured on the free edition this project targets (21.1). Blackmagic documents none of the host facts; a point release can change them.
- The scripting docs ship at
/Library/Application Support/Blackmagic Design/DaVinci Resolve/Developer/Scripting/(README.md,CHANGELOG.md,DaVinciResolveScript.pyi,Examples/,Modules/), read-only. The README there has no API tables: the.pyiis the signature reference (quote it, do not recall it). - Point release: compare the
*Last Updated:*line of the shipped README and the CHANGELOG, thenmake gen-typesandmake lint-lua.parseReadmeListsin the generator andDEPRECATED_SECTIONSinsrc/docsSearch.tskey on the exact README headings for deprecated and unsupported names, so a renamed heading silently drops the tags. The Node tests use fixtures: a real docs change is caught only bymake lint-luaand thescripting_api_docscheck inmake smoke. Re-measure the sandbox by runningclaude_diagfrom the Scripts menu in a scratch project and decodingRLBDiag; thebmdclass intypes/resolve_host.d.luais hand-written. - The Scripts-menu Lua state is sandboxed. nil:
io,os.execute,os.remove,os.rename,require,package,ffi,debug,UIManager,arg,bmd.readfile/writefile/readdir;oskeepsclock date difftime getenv time tmpname;printoutput is invisible. Working:setfenv,getfenv,loadfile,dofile,loadstring,load,pcall,xpcall,coroutine,bit,lpeg, the 28bmd.*keys of the Console list (waitsleeps,gettimeis float seconds), the Resolve API, andfusion:GetPrefs/SetPrefs/SavePrefs. The host runs in-process (bmd.getpid()is Resolve's pid), the script environment is_G(which has a metatable), andresolve,fusion,fu,appare userdata globals (oneFusionUIobject behind the last three). The Console is a different state: the menu host has its library set plussetfenv/getfenv, minusdebug. SavePrefsreturns nil, takes single-digit milliseconds even at 512 KB and writes a new inode each time; keys survive Resolve's own saves, a quit and a relaunch; in-memorySetPrefsstate is shared across menu-script runs.Workspace > Scriptslists a newly copied.luawithout a restart.Global.Script.AllowAutomaticScripts = 0does not stop menu scripts.Fusion.prefsis~/Library/Application Support/Blackmagic Design/DaVinci Resolve/Fusion/Profiles/Default/Fusion.prefs(about 22 KB of Lua-table text, mode 0666, one profile).- The user Utility folder
~/Library/Application Support/Blackmagic Design/DaVinci Resolve/Fusion/Scripts/Utility/is the only Resolve location this project writes.fuscriptat/Applications/DaVinci Resolve/DaVinci Resolve.app/Contents/Libraries/Fusion/fuscriptruns plain Lua from a terminal with a full, unsandboxed LuaJIT (-l lua -x '...') and is the Lua test runner. - Measured live: a second click of the script takes over cleanly (the old loop exits on the first
request for the newer session); with live save on,
open_projectwithsave_current=falseneither prompts nor loses work (live save is a user preference, not aGetSettings()key);LoadProjecton a dirty project can raise a modal the bridge cannot answer, soopen_projectsaves first by default and interactive render mode stays off; a render started through the API leaves Resolve on the Deliver page althoughrender_current_timelinenever callsOpenPage(from Edit in the 2026-09-21 smoke run, from Color on 2026-09-24).
Windows (documented, not measured)
From Blackmagic's shipped README unless marked otherwise; nothing here has been run on Windows.
| Item | Value assumed |
| Per-user scripts folder | %APPDATA%\Blackmagic Design\DaVinci Resolve\Support\Fusion\Scripts\Utility (note the Support segment; the all-users root %PROGRAMDATA%\Blackmagic Design\DaVinci Resolve\Fusion\Scripts has none) |
Fusion.prefs | %APPDATA%\Blackmagic Design\DaVinci Resolve\Support\Fusion\Profiles\Default\Fusion.prefs (forum-sourced, consistent with the Support\Fusion layout) |
| Scripting docs | %PROGRAMDATA%\Blackmagic Design\DaVinci Resolve\Support\Developer\Scripting |
fuscript | C:\Program Files\Blackmagic Design\DaVinci Resolve\fuscript.exe (unused by the tooling) |
| State dir | %USERPROFILE%\.davinci-resolve-lua-mcp, stamped with forward slashes |
| Claude Desktop | %APPDATA%\Claude\...; the Microsoft Store build redirects it under %LOCALAPPDATA%\Packages\Claude_<id>\LocalCache\Roaming\Claude\ |
Nothing in the sandbox census, SavePrefs (rename or in place), the takeover, loadfile with
forward slashes, the ANSI-vs-UTF-8 fopen behind loadfile (a non-ASCII %USERPROFILE% may break
it; resolve_status reports state_dir_ascii), os.getenv("USERPROFILE"), the shape of
MapPath("Profile:") or the Utility scan has been measured on Windows. docs/windows.md is the
checklist (run claude_diag from the Scripts menu, decode RLBDiag with the PowerShell snippet
there); a contributor's measurement moves a line into the list above with the Resolve build it was
measured on.
Lua conventions
- Before writing any Lua, read the shipped docs: the
.pyifor every signature, argument order, return shape and enum; the README for calling conventions and the Deprecated and Unsupported sections;Examples/*.luafor idioms only (they use deprecated calls andos.exit). Colon calls, 1-indexed tables, lowercase page names,returnto send a value: see the README'srun_luaguide. - Lua 5.1 (LuaJIT):
xpcall(f, handler)takes no extra arguments, so wrap calls in a closure;debugis nil, so the handler falls back totostringwhendebug.tracebackis absent. - Obtain
resolvewith a plain global read (notrawget; the_Gmetatable would hide it), thenResolve()if that is a function, thenbmd.scriptapp("Resolve").fusionis the first offusion,fu,appwith aSetPrefsmethod, elseresolve:Fusion(). - Resolve "lists" are 1-indexed tables carrying
__flags = 4194304(strip it; iterate withfor i = 1, #list, neverpairs); "dicts" are plain tables keyed by name, some (GetMarkers()) by integer frame. API objects are userdata:pairsand#throw,==works between two fetches. - Encoder rules: a table is a JSON array only when its keys are exactly 1..n; any other integer-keyed
table becomes an object with string keys; userdata, functions and metatabled tables become a
tostring()placeholder, never a crash. Integral numbers below 2^53 use%.0f, others%.17g, never%d(it silently truncates 3.5 to 3 under LuaJIT); NaN and inf become null. - An empty table encodes as
[]when it carried__flags(an empty API list) and as{}otherwise, so the server treats{}as[]wherever a list is expected and tests assert withArray.isArray(x) ? x : []. - API quirks:
GetSettings()returns the frame rate as a number and resolution as strings and has nouseCustomSettingskey;AddRenderJob()returns""on failure, which is truthy, so check#jobId > 0; check every boolean the API returns; marker frames are relative to the timeline start;AddSubFoldermakes the new folder current and allows duplicate names (look bins up by name first, restore withSetCurrentFolder);CreateEmptyTimelinemakes the new timeline current. bmd.readstring/bmd.writestringare Lua-table serialisers, not file I/O.- Lua never expands
~: build every path fromos.getenv("HOME")(macOS) oros.getenv("USERPROFILE")(Windows, whereHOMEis nil), or theRLB_STATE_DIRheader the server stamps into the Lua files at copy time, with forward slashes on both platforms (strip trailing separators with[/\\]+$). The contract spans the bridge (the[==[@@RLB_STATE_DIR@@]==]literal and the line-2 comment),stateDirStampProblem()insrc/config.ts(refuses]==],",\, CR/LF and a leading@@),src/bridgeInstall.ts(replaces every occurrence) andcheck_bridge.sh.
TypeScript conventions
- CJS package (no
"type": "module"),tsconfigmodule: NodeNextin CJS mode: relative imports end in.js,__dirnameworks.@types/nodeis pinned to 20 sotscrejects newer APIs.import * as z from 'zod/v4';InMemoryTransportcomes from@modelcontextprotocol/server,Clientfrom@modelcontextprotocol/client.outputSchemausesz.looseObjectbecause the v2 client rejects extra keys instructuredContentagainst a strictz.object;isErrorresults skip output validation. Context7 id/modelcontextprotocol/typescript-sdk(main) is the v2 SDK; check versions withnpm view @modelcontextprotocol/server version(npm view @modelcontextprotocol/sdkshows only the legacy line). main(options)insrc/main.tsis the wiring;src/index.tsisvoid main(). Its five hooks are a stable extension surface for downstream builds that importmain, no-ops by default:wrapServer(applied in theserveStdiofactory right aftercreateServer; must return thatMcpServeror a Proxy over it,serveStdiochecksinstanceof),onToolFailure(called fromguard(tool, fn)inserver.tswherever a thrownBridgeErrorbecomes anisErrorresult; never on success, never for Lua-side failures, never fromresolve_status),onToolError(the same place, for anything else a tool body throws: a defect, logged astool failed; never for aBridgeError),onBridgeRequest(passed toBridgeClientasonRequest: oneBridgeRequestReportper request after it ends, success or failure, with epoch-ms phase timesstarted_at/lock_acquired_at/written_at/finished_at,polls,request_bytes,outcome,lua_ok,bridge_ms; no code, paths or response body; called in the calling tool's async context,status()pings included) andbeforeExit(awaited on every exit path behind a ref'd 2 s timer, ref'd on purpose so Node cannot exit beforeexit(code)). A throw inside any of the three observers is logged and ignored, never changing a result.options.runtime(env,proc,transport,beforeExitCapMs) is a test seam:tests/main.test.tsdrivesmain()in-process with a fakeEventEmitterprocess and the server half ofInMemoryTransport.createLinkedPair(). Never register on the realprocessin a test: anode --testchild's stdin ends at once and would arm a realprocess.exit.- The request-slot lock is per request, never held while idle:
BridgeClient.request()takes it, waits up to the request's own timeout for a live holder, releases it infinally;status()reports the holder without the lock;main.tstakes it for a moment at startup to remove a leftovernext.lua. Why: Claude Desktop launches the server several times on install and keeps one idle "era probe" sibling alive for the whole session, in utility processes with stdin on/dev/null(the stdin-closed exit path never fires there); a startup lock would be owned by that sibling for ever and every request would answerlock_held. expandHome(value, home, platform)insrc/config.tsexpands a leading~and${HOME}(with\too on win32), because Claude Desktop passes auser_config.defaultsuch as${HOME}/.davinci-resolve-lua-mcpto the server literally;homeisconfig.home(os.homedir(), which is%USERPROFILE%on Windows whereHOMEis unset) andloadConfig(env, home, platform)is the seam the tests use to assert Windows paths on a Mac. A setting with no manifestdefaultthat the user never saved arrives as its unfilled placeholder (${user_config.scripts_dir},${user_config.prefs_dir}; Claude Desktop 2.7032.0, measured 2026-09-24);pick()treats a whole placeholder like"", as unset, so the platform default applies without a config problem.- Scripts that spawn the server use
StdioClientTransport(@modelcontextprotocol/client/stdio), which gives the childgetDefaultEnvironment()(HOME LOGNAME PATH SHELL TERM USER) plus theenvoption only, so everyRLB_*variable is passed explicitly.Client.callToolreturnsstructuredContentforisErrorresults too, validates successes againstoutputSchema(a mismatch throws), and its default timeout is 60 s, the same as the render wait, so pass a timeout per call.close()ends stdin, then SIGTERM after 2 s, then SIGKILL; both exit paths release the lock.
Claude Desktop
- Extensions live in
~/Library/Application Support/Claude/Claude Extensions/<id>/; this one istype: node, run with Claude's bundled Node (the host resolves the user's login PATH but maps a barenodeto its own). On Windows:%APPDATA%\Claude\Claude Extensions\<id>\,%APPDATA%\Claude\claude_desktop_config.json,%APPDATA%\Claude\logs\,%APPDATA%\Claude\extensions-installations.json; the Microsoft Store (MSIX) build virtualises all of them under%LOCALAPPDATA%\Packages\Claude_<id>\LocalCache\Roaming\Claude\.dev-register.mjsknows only the macOS config path; on Windows the config is edited by hand (docs/windows.md). ~/Library/Logs/Claude/mcp-server-DaVinci Resolve Lua MCP.logrecords the manager's connection (initialize,tools/list, era probes, shutdowns) but not the chat's tool calls; stderr is also copied intomain.logas[UtilityProcess stderr], andgrep -h '\[MCP Launch\]\|\[UV Discovery\]' ~/Library/Logs/Claude/main*.logshows how an extension was resolved and started. To prove a tool ran, decode the lastRLBResp(see "Working here").claude_desktop_config.json(mode 0600) may hold other servers; the dev loop merges into it and backs it up first, never clobbers.- Reinstalling the same version shows no dialog: remove the extension under Settings > Extensions,
then
open dist/davinci-resolve-lua-mcp.mcpb(ormake install). Verify from~/Library/Application Support/Claude/extensions-installations.json(installedAt,hash= the sha256 of the.mcpb) and the newstartinglines in~/.davinci-resolve-lua-mcp/server.log(several per launch, one per probe sibling).
Language servers: use them
Two LSP plugins back the LSP tool (line and character are 1-based and must sit on the identifier)
and the diagnostics block the harness appends after every Write or Edit of a .lua, .ts or .mjs
file.
- Lua: the
lua-lspplugin (project scope,.claude/settings.json) wires the tool to alua-language-serveron PATH (Homebrew)..luarc.jsonsetsruntime.versiontoLuaJIT(sosetfenv/getfenv/bitare legal and Lua 5.4 deprecation warnings are wrong) and disablesio,ffi,debugandpackageto mirror the sandbox (os.execute/os.removecannot be disabled per key; the grep gates guard those). Host globals live intypes/resolve_host.d.lua: the 28bmdkeys as a closed class,ResolveandFusion(Execute/RunScriptmarked@deprecated), and the block between theBEGIN GENERATED/END GENERATEDmarkers generated from the.pyibyscripts/gen-types.mjs. Never edit that block by hand: change the generator, runmake gen-types. A method the LSP does not know means the.pyichanged. Never add a name todiagnostics.globals(it mutes typos). Claude Code's LSP client answers no configuration requests, so.luarc.jsonis the only channel; the server picks up file changes within a minute. - TypeScript: the
typescript-lspplugin (user scope) runstypescript-language-server, installed globally under nvm's Node, so it is on PATH only in a shell that sourced nvm. The project'stypescriptis 7.x, which ships notsserverand no JavaScript API, so the server ignores the workspace install and falls back to the globaltypescript: keep that global on the 6.x line (npm i -g typescript@6, the last JavaScript-based release; a 6.0 project with the 7.0 defaults type-checks identically to 7, so the editor's diagnostics matchmake typecheckand CI, which run the native 7). The plugin's log lineUsing Typescript version (bundled) 6.x.yconfirms the fallback. Measured 2026-09-22 with 7.0.2: TypeScript 7's own server (tsc --lsp --stdio) answers hover, definition, symbols and pull diagnostics, but pushes only emptypublishDiagnosticson open and close and never a type error after an edit, a request, a save or a close, while Claude Code collects diagnostics from pushes only; a project.lsp.jsonpointing at it was tried and reverted (only one server per extension runs). Do not switch to it until it pushes. No headless mode;npx tsc --noEmitis the batch equivalent. - After every edit, read the diagnostics block; a warning or error in a file you touched is part of
the task: fix the code, or, when the diagnostic is wrong, fix what the server knows. Never silence
one with
---@diagnostic disable,diagnostics.globals,// @ts-ignore,// @ts-expect-errororas anywithout a comment citing the measured fact that makes it wrong (accepted exceptions: theclaude_diag.luawarnings named under Tests). - Hover a Resolve API method before calling it from Lua; hover or goToDefinition on the SDK's
installed
.d.tsbefore writing against it; findReferences and incomingCalls before changing an exported symbol; documentSymbol before reading a large file (claude_diag.luais 1050 lines). - The LSP never runs code:
fuscript,node --test,tsc --noEmitand the grep gates remain the acceptance gates. Its answers are evidence about declared types, not about Resolve's behaviour; the measurements win.Executable not found in $PATHmeans the binary is missing:brew install lua-language-server, ornpm i -g typescript-language-server typescriptunder nvm.
Working here
- Multi-line commit messages:
git commit -q -F - <<'EOF' ... EOF. - macOS
datehas no%Nandawknostrftime: use zshzmodload zsh/datetime; $EPOCHREALTIMEfor sub-second stamps anddate -r <epoch> '+%H:%M:%S'to format one. - Decoding a payload from
Fusion.prefs: keys are serialised in hash order, so match\bRLBResp = "([^"]*)"(thePrevvariant ofRLBDiagcannot match because the next character isP); the value is<id>:<hex>, andecho <hex> | xxd -r -pis the envelope JSON (op,ok,ms,session,result). Fusion writes strings with\",\\,\nand raw tabs and UTF-8. To compare two prefs files, strip theRLBlines and leading whitespace,sort, thendiff. - Large reference sources go into the session scratchpad via
curl, then grep the relevant lines. .claude/settings.jsonenables themcp-server-devplugin (itsbuild-mcpbskill is the packaging reference andbuild-mcp-serverthe tool-design reference) andlua-lsp; the repo-localcreate-readmeskill under.claude/skills/wrote the README.- One-off live probes against the bridge: a scratch
.mjsunder.out/(git-ignored, bundle-ignored) that spawnsserver/index.jswithStdioClientTransportand calls tools, asscripts/smoke.mjsdoes; a stat loop onFusion.prefsaround a call counts the bridge's saves. Never send mutating Lua to a real project.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

