davinci-resolve-mcp 4.18.0 → 4.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,40 @@
2
2
 
3
3
  Release history for the DaVinci Resolve MCP Server. The latest release is summarized in the root README; older entries live here to keep the README focused.
4
4
 
5
+ ## What's New in v4.18.1 — Names with `$` or `\` are written as typed
6
+
7
+ ### Fixed
8
+
9
+ - **`drt assemble_project` no longer rewrites a merged timeline's name when it
10
+ contains `$`** (#332, thanks @Dev-next-gen). The name was inserted with a
11
+ replacement string, and JavaScript expands `$&`, `$'` and `$$` in one. A
12
+ second timeline named `R2 $& $'` wrote an `MpFolder.xml` that no longer
13
+ parsed, and `Spot $$ 30s` came out as `Spot $ 30s`, so a `folder` move then
14
+ failed to find the timeline.
15
+ - **The same fix in 53 more places in the offline `.drp`/`.drt` writers.**
16
+ Caption text in `placeSubtitles`, generator, title and compound clip names,
17
+ media pool clip names and file paths, and every other value inserted into
18
+ the XML now goes in with a replacer function, so `$`-sequences stay literal.
19
+ A new guard test fails the advanced suite if a `replace()` call passes an
20
+ interpolated template as a string.
21
+ - **The audio-only fallback clone in `cut-media` now XML-escapes the source
22
+ file name and path.** A source path containing `&`, such as
23
+ `Smith & Jones/clip.mov`, wrote invalid XML.
24
+ - **Re-running media analysis on a clip no longer fails when the new analysis
25
+ text contains a backslash.** The managed block in the clip's metadata was
26
+ replaced with `re.sub` using the text as a replacement string, so a Windows
27
+ path raised `bad escape \F` and `\t` turned into a tab. The text is now
28
+ inserted as-is.
29
+
30
+ ### Validation
31
+
32
+ - Advanced Node suite on Node 20 with a fresh `npm ci`: 1,224 tests, 0 failed.
33
+ With the fixes reverted, the guard and the caption, generator and title tests
34
+ fail.
35
+ - Python suite: the new metadata test fails with `bad escape \F` without the
36
+ fix and passes with it.
37
+ - Offline file writers only. No Resolve API behaviour changed.
38
+
5
39
  ## What's New in v4.18.0 — Edit captions with Resolve open
6
40
 
7
41
  ### Added
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  English | [简体中文](README.zh-CN.md)
4
4
 
5
- [![Version](https://img.shields.io/badge/version-4.18.0-blue.svg)](https://github.com/samuelgursky/davinci-resolve-mcp/releases)
5
+ [![Version](https://img.shields.io/badge/version-4.18.1-blue.svg)](https://github.com/samuelgursky/davinci-resolve-mcp/releases)
6
6
  [![npm](https://img.shields.io/npm/v/davinci-resolve-mcp.svg?label=npm&color=CB3837)](https://www.npmjs.com/package/davinci-resolve-mcp)
7
7
  [![API Coverage](https://img.shields.io/badge/API%20Coverage-100%25-brightgreen.svg)](docs/reference/api-coverage.md)
8
8
  [![Tools](https://img.shields.io/badge/MCP%20Tools-37%20(390%20full)-blue.svg)](#server-modes)
package/README.zh-CN.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [English](README.md) | 简体中文
4
4
 
5
- [![Version](https://img.shields.io/badge/version-4.18.0-blue.svg)](https://github.com/samuelgursky/davinci-resolve-mcp/releases)
5
+ [![Version](https://img.shields.io/badge/version-4.18.1-blue.svg)](https://github.com/samuelgursky/davinci-resolve-mcp/releases)
6
6
  [![npm](https://img.shields.io/npm/v/davinci-resolve-mcp.svg?label=npm&color=CB3837)](https://www.npmjs.com/package/davinci-resolve-mcp)
7
7
  [![API Coverage](https://img.shields.io/badge/API%20Coverage-100%25-brightgreen.svg)](docs/reference/api-coverage.md)
8
8
  [![Tools](https://img.shields.io/badge/MCP%20Tools-37%20(390%20full)-blue.svg)](#服务器模式)
@@ -12,7 +12,7 @@
12
12
  [![Python](https://img.shields.io/badge/python-3.10+-green.svg)](https://www.python.org/downloads/)
13
13
  [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT)
14
14
 
15
- > 本翻译对应 v4.18.0 版 README。如与英文原版有出入,以 [英文原版](README.md) 为准。
15
+ > 本翻译对应 v4.18.1 版 README。如与英文原版有出入,以 [英文原版](README.md) 为准。
16
16
 
17
17
  一个 Model Context Protocol (MCP) 服务器,让 AI 助手通过官方脚本 API 控制 DaVinci Resolve Studio(达芬奇)。它提供完整的 API 覆盖,外加带护栏的工作流助手,涵盖剪辑、媒体池整理、渲染设置、审阅标记、调色、Fusion、Fairlight、项目生命周期任务、扩展开发,以及不碰源媒体的媒体分析。
18
18
 
package/install.py CHANGED
@@ -37,7 +37,7 @@ from src.utils.update_check import (
37
37
 
38
38
  # ─── Version ──────────────────────────────────────────────────────────────────
39
39
 
40
- VERSION = "4.18.0"
40
+ VERSION = "4.18.1"
41
41
  # Only hard floor: mcp[cli] requires Python 3.10+. There is no upper bound —
42
42
  # Resolve's scripting bridge loads into newer interpreters on recent builds
43
43
  # (Python 3.14 verified against Resolve Studio 20.3.2). Older Resolve builds
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "davinci-resolve-mcp",
3
- "version": "4.18.0",
3
+ "version": "4.18.1",
4
4
  "description": "NPM bootstrapper for the DaVinci Resolve MCP Server.",
5
5
  "license": "MIT",
6
6
  "author": "Samuel Gursky <samgursky@gmail.com>",
@@ -467,7 +467,7 @@ export const drtTool = {
467
467
  } catch { return whole; }
468
468
  });
469
469
  // pool clip: uuid remap + keyed SeqRef patch + fresh numeric IDs
470
- let tlNew = applyBlobs(apply(tlEl)).replace(/<ID>\d+<\/ID>/g, `<ID>${nextPoolId}<\/ID>`.replace('<\/ID>', '</ID>'));
470
+ let tlNew = applyBlobs(apply(tlEl)).replace(/<ID>\d+<\/ID>/g, () => `<ID>${nextPoolId}<\/ID>`.replace('<\/ID>', '</ID>'));
471
471
  nextPoolId += 1;
472
472
  const fbM = tlNew.match(/(<Sm2Sequence DbId="[^"]+">\s*<FieldsBlob>)([0-9a-fA-F]+)(<\/FieldsBlob>)/);
473
473
  if (fbM) {
@@ -486,14 +486,14 @@ export const drtTool = {
486
486
  // Children live INSIDE <MediaVec> — an element appended after its
487
487
  // close parses fine and is silently invisible (measured: the whole
488
488
  // REEL_02 subtree vanished while every id chain checked out).
489
- mpXml = mpXml.replace('</MediaVec>', `${tlNew}\n</MediaVec>`);
489
+ mpXml = mpXml.replace('</MediaVec>', () => `${tlNew}\n</MediaVec>`);
490
490
  for (const el of mediaEls) {
491
491
  const id = el.match(/DbId="([^"]+)"/)[1];
492
- if (!mpXml.includes(`DbId="${id}"`)) mpXml = mpXml.replace('</MediaVec>', `${el}\n</MediaVec>`);
492
+ if (!mpXml.includes(`DbId="${id}"`)) mpXml = mpXml.replace('</MediaVec>', () => `${el}\n</MediaVec>`);
493
493
  }
494
494
  const pj2 = await zip.file('project.xml').async('string');
495
495
  for (const blob of pj2.match(/<Element>\s*<Sm2(?:Sequence|TiItem)LockableBlob DbId="[^"]+">[\s\S]*?<\/Sm2(?:Sequence|TiItem)LockableBlob>\s*<\/Element>/g) || []) {
496
- pjXml = pjXml.replace('</LocableBlobSet>', `${apply(blob)}</LocableBlobSet>`);
496
+ pjXml = pjXml.replace('</LocableBlobSet>', () => `${apply(blob)}</LocableBlobSet>`);
497
497
  }
498
498
  // THE timeline registry (found the hard way — two invisible merges):
499
499
  // project.xml's <TimelineHandleVec> lists each pool clip's embedded
@@ -503,7 +503,7 @@ export const drtTool = {
503
503
  const vec2 = pj2.match(/<TimelineHandleVec>([\s\S]*?)<\/TimelineHandleVec>/);
504
504
  if (vec2) {
505
505
  for (const h of vec2[1].match(/<Element>[^<]*<\/Element>/g) || []) {
506
- pjXml = pjXml.replace('</TimelineHandleVec>', ` ${apply(h)}\n </TimelineHandleVec>`);
506
+ pjXml = pjXml.replace('</TimelineHandleVec>', () => ` ${apply(h)}\n </TimelineHandleVec>`);
507
507
  }
508
508
  }
509
509
  // future merges must not collide with THIS timeline's fresh ids either
@@ -534,7 +534,7 @@ export const drtTool = {
534
534
  const hit = mpXml.match(tlRe);
535
535
  if (!hit) throw new Error(`assemble_project: could not locate pool clip for timeline ${names[i]} to move into folder ${folder}`);
536
536
  mpXml = mpXml.replace(hit[0], '');
537
- bin.clips.push(hit[0].replace(/<MpFolder>[^<]*<\/MpFolder>/, `<MpFolder>${bin.id}</MpFolder>`));
537
+ bin.clips.push(hit[0].replace(/<MpFolder>[^<]*<\/MpFolder>/, () => `<MpFolder>${bin.id}</MpFolder>`));
538
538
  }
539
539
  // Register the bins in Master's FieldsBlob — the parent folder blob
540
540
  // is the SUBFOLDER registry (measured: with it blanked, a bin's
@@ -213,7 +213,7 @@ async function convert(inputPath, outputPath, options = {}) {
213
213
  // Auto-generate output path if not provided
214
214
  if (!outputPath) {
215
215
  const ext = CONTAINER_EXTENSIONS[preset.container] || '.wav';
216
- outputPath = inputPath.replace(/\.[^.]+$/, `_${presetName}${ext}`);
216
+ outputPath = inputPath.replace(/\.[^.]+$/, () => `_${presetName}${ext}`);
217
217
  }
218
218
 
219
219
  onProgress(10);
@@ -0,0 +1,95 @@
1
+ // A string passed as the replacement to String.prototype.replace expands `$&`,
2
+ // `$'`, `` $` `` and `$$`, so a name or caption carrying them is rewritten on its
3
+ // way into the XML (#332: `R2 $& $'` as a timeline name made MpFolder.xml
4
+ // unparseable; `Spot $$ 30s` came out as `Spot $ 30s`). Interpolated
5
+ // replacements are therefore passed as functions, which insert their result
6
+ // literally. This file guards that rule and checks the writers that carry user
7
+ // text.
8
+
9
+ const test = require('node:test');
10
+ const assert = require('node:assert');
11
+ const fs = require('node:fs');
12
+ const path = require('node:path');
13
+ const JSZip = require('jszip');
14
+ const { escapeXml } = require('../xml-builder');
15
+ const { createEmptyProject } = require('../author-project');
16
+ const { placeSubtitles } = require('../place-subtitles');
17
+ const { placeGenerator } = require('../place-generator');
18
+ const { placeFusionTitle } = require('../place-fusion-title');
19
+
20
+ const ROOT = path.resolve(__dirname, '..', '..', '..');
21
+ const TRICKY = "Spot $$ 30s $& $' $` end";
22
+
23
+ function sourceFiles(dir) {
24
+ const out = [];
25
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
26
+ if (entry.name === 'node_modules' || entry.name === '__tests__') continue;
27
+ const full = path.join(dir, entry.name);
28
+ if (entry.isDirectory()) out.push(...sourceFiles(full));
29
+ else if (/\.(m?js)$/.test(entry.name)) out.push(full);
30
+ }
31
+ return out;
32
+ }
33
+
34
+ // `.replace(<string or regex literal>, `...${...}...`)` on one line. A template
35
+ // that uses a $-backreference ($1, $&, $<name>) needs the string form and is allowed.
36
+ const STRING_REPLACEMENT = /\.replace\(\s*(?:'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|\/(?:[^/\\\n]|\\.)+\/[a-z]*)\s*,\s*`((?:[^`\\]|\\.)*)`/g;
37
+ const BACKREF = /\$(?:[0-9&'`]|<[A-Za-z_]\w*>)/;
38
+
39
+ function offenders(text) {
40
+ const found = [];
41
+ for (const m of text.matchAll(STRING_REPLACEMENT)) {
42
+ const template = m[1];
43
+ if (!template.includes('${')) continue;
44
+ if (BACKREF.test(template.replace(/\$\{[^}]*\}/g, ''))) continue;
45
+ found.push(m[0].slice(0, 120));
46
+ }
47
+ return found;
48
+ }
49
+
50
+ test('no interpolated replace() replacement is passed as a string', () => {
51
+ const files = [...sourceFiles(path.join(ROOT, 'server')), ...sourceFiles(path.join(ROOT, 'vendor'))];
52
+ assert.ok(files.length > 50, `scanned ${files.length} files`);
53
+ const bad = [];
54
+ for (const file of files) {
55
+ for (const hit of offenders(fs.readFileSync(file, 'utf8'))) bad.push(`${path.relative(ROOT, file)}: ${hit}`);
56
+ }
57
+ assert.deepStrictEqual(bad, [], 'pass the replacement as () => `...` so $-sequences stay literal');
58
+ });
59
+
60
+ test('the guard catches the #332 form and allows the safe ones', () => {
61
+ assert.strictEqual(offenders("x.replace('</MediaVec>', `${el}\\n</MediaVec>`)").length, 1);
62
+ assert.strictEqual(offenders('x.replace(/<Name>[^<]*<\\/Name>/, `<Name>${n}</Name>`)').length, 1);
63
+ assert.strictEqual(offenders("x.replace('</MediaVec>', () => `${el}\\n</MediaVec>`)").length, 0);
64
+ assert.strictEqual(offenders('x.replace(/(<a>)<b\\/>/, `$1<b>${hex}</b>`)').length, 0);
65
+ assert.strictEqual(offenders("x.replace('a', 'b')").length, 0);
66
+ });
67
+
68
+ async function sequenceXml(buffer) {
69
+ const zip = await JSZip.loadAsync(buffer);
70
+ const parts = [];
71
+ for (const name of Object.keys(zip.files)) {
72
+ if (/SeqContainer\/[^/]+\.xml$|SeqContainer\d*\.xml$/.test(name)) parts.push(await zip.files[name].async('string'));
73
+ }
74
+ return parts.join('\n');
75
+ }
76
+
77
+ test('placeSubtitles keeps $-sequences in caption text', async () => {
78
+ const { buffer, startFrame } = await createEmptyProject({ timelineName: 'Subs' });
79
+ const res = await placeSubtitles(buffer, { subtitles: [{ startFrame, durationFrames: 48, text: TRICKY }] });
80
+ assert.ok((await sequenceXml(res.buffer)).includes(`<Name>${escapeXml(TRICKY)}</Name>`));
81
+ });
82
+
83
+ test('placeGenerator keeps $-sequences in the generator name', async () => {
84
+ const { buffer, startFrame } = await createEmptyProject({ timelineName: 'Gen' });
85
+ const res = await placeGenerator(buffer, { generatorName: TRICKY, trackIndex: 2, startFrame, durationFrames: 24 });
86
+ const xml = await sequenceXml(res.buffer);
87
+ assert.ok(xml.includes(`<PrettyType>${escapeXml(TRICKY)}</PrettyType>`));
88
+ assert.ok(xml.includes(`<Name>${escapeXml(TRICKY)}</Name>`));
89
+ });
90
+
91
+ test('placeFusionTitle keeps $-sequences in the clip name', async () => {
92
+ const { buffer, startFrame } = await createEmptyProject({ timelineName: 'Title' });
93
+ const res = await placeFusionTitle(buffer, { trackIndex: 2, startFrame, durationFrames: 24, name: TRICKY });
94
+ assert.ok((await sequenceXml(res.buffer)).includes(`<Name>${escapeXml(TRICKY)}</Name>`));
95
+ });
@@ -247,7 +247,7 @@ async function assembleTimeline(spec = {}) {
247
247
  if (!hit) throw new Error(`assembleTimeline: item markers — no ${kind} clip starting at ${cut.startFrame} on track ${cut.track ?? 1}`);
248
248
  const blob = encodeTimelineMarkersBlob(cut.markers);
249
249
  const el = `<Element>\n <Sm2TiItemLockableBlob DbId="${randomUUID()}">\n <FieldsBlob>${blob.toString('hex')}</FieldsBlob>\n <BlobOwner>${hit[1]}</BlobOwner>\n <DbSavedTime>0</DbSavedTime>\n </Sm2TiItemLockableBlob>\n </Element>\n `;
250
- pj = pj.replace('</LocableBlobSet>', `${el}</LocableBlobSet>`);
250
+ pj = pj.replace('</LocableBlobSet>', () => `${el}</LocableBlobSet>`);
251
251
  }
252
252
  zipIM.file('project.xml', pj);
253
253
  buffer = await zipIM.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
@@ -417,7 +417,7 @@ async function assembleTimeline(spec = {}) {
417
417
  const setM = pjX.match(/<LocableBlobSet>[\s\S]*?<\/LocableBlobSet>/);
418
418
  if (!setM) throw new Error('assembleTimeline: project.xml has no LocableBlobSet to hold markers');
419
419
  const el = `<Element>\n <Sm2SequenceLockableBlob DbId="${randomUUID()}">\n <FieldsBlob>${blob.toString('hex')}</FieldsBlob>\n <BlobOwner>${seqIdM}</BlobOwner>\n <DbSavedTime>0</DbSavedTime>\n </Sm2SequenceLockableBlob>\n </Element>\n `;
420
- pjX = pjX.replace('</LocableBlobSet>', `${el}</LocableBlobSet>`);
420
+ pjX = pjX.replace('</LocableBlobSet>', () => `${el}</LocableBlobSet>`);
421
421
  zipM.file('project.xml', pjX);
422
422
  buffer = await zipM.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
423
423
  }
@@ -27,6 +27,7 @@ const {
27
27
  emptyTrackClone,
28
28
  } = require('./seq-surgery');
29
29
  const { clipDbId, setClipStart, setClipDuration, setClipIn, setClipInEmpty } = require('./splice-clips');
30
+ const { escapeXml } = require('./xml-builder');
30
31
 
31
32
  /**
32
33
  * @param {Buffer|string} drpInput
@@ -96,7 +97,7 @@ async function cutSourceIntoClips(drpInput, opts = {}) {
96
97
  if (cut.mediaRef) {
97
98
  // Multi-source: point this cut at ITS source's transplanted pool
98
99
  // element instead of the donor's.
99
- c = c.replace(/<MediaRef>[0-9a-f-]{36}<\/MediaRef>/, `<MediaRef>${cut.mediaRef}</MediaRef>`);
100
+ c = c.replace(/<MediaRef>[0-9a-f-]{36}<\/MediaRef>/, () => `<MediaRef>${cut.mediaRef}</MediaRef>`);
100
101
  }
101
102
  if (cut.srcMeta && !native && cut.audioOnly) {
102
103
  // Every clone must carry ITS OWN source identity — a donor clone
@@ -106,15 +107,15 @@ async function cutSourceIntoClips(drpInput, opts = {}) {
106
107
  // A1 (measured, E15), and a TC-bearing video source fails the whole
107
108
  // render with "Full resolution media not found" (measured, E31).
108
109
  const { name, mediaFilePath, fps, frameCount } = cut.srcMeta;
109
- c = c.replace(/<Name>[\s\S]*?<\/Name>/, `<Name>${name}</Name>`);
110
- c = c.replace(/<MediaFilePath>[\s\S]*?<\/MediaFilePath>/, `<MediaFilePath>${mediaFilePath}</MediaFilePath>`);
110
+ c = c.replace(/<Name>[\s\S]*?<\/Name>/, () => `<Name>${escapeXml(name)}</Name>`);
111
+ c = c.replace(/<MediaFilePath>[\s\S]*?<\/MediaFilePath>/, () => `<MediaFilePath>${escapeXml(mediaFilePath)}</MediaFilePath>`);
111
112
  const rate = Buffer.alloc(16);
112
113
  rate.writeDoubleLE(fps, 0);
113
- c = c.replace(/<MediaFrameRate>[0-9a-fA-F]*<\/MediaFrameRate>/, `<MediaFrameRate>${rate.toString('hex')}</MediaFrameRate>`);
114
+ c = c.replace(/<MediaFrameRate>[0-9a-fA-F]*<\/MediaFrameRate>/, () => `<MediaFrameRate>${rate.toString('hex')}</MediaFrameRate>`);
114
115
  const idm = Buffer.alloc(9);
115
116
  idm.writeUInt8(0x02, 0);
116
117
  idm.writeDoubleBE((frameCount - 1) / fps, 1);
117
- c = c.replace(/<MediaTimemapBA>[0-9a-fA-F]*<\/MediaTimemapBA>/, `<MediaTimemapBA>${idm.toString('hex')}</MediaTimemapBA>`);
118
+ c = c.replace(/<MediaTimemapBA>[0-9a-fA-F]*<\/MediaTimemapBA>/, () => `<MediaTimemapBA>${idm.toString('hex')}</MediaTimemapBA>`);
118
119
  if (cut.audioOnly) {
119
120
  // Generic audio-clip FieldsBlob, verbatim from the live A2 harvest.
120
121
  // (Video clones keep their blob — repointClipBlobsInXml owns it.)
@@ -125,13 +126,13 @@ async function cutSourceIntoClips(drpInput, opts = {}) {
125
126
  // Embedded source timecode base, in SECONDS (harvested with the media
126
127
  // template). Donor default 0 makes Resolve seek the wrong TC and fail
127
128
  // the render with "Full resolution media not found at <TC>".
128
- c = c.replace(/<MediaStartTime>[\s\S]*?<\/MediaStartTime>/, `<MediaStartTime>${cut.mediaStartTime}</MediaStartTime>`);
129
+ c = c.replace(/<MediaStartTime>[\s\S]*?<\/MediaStartTime>/, () => `<MediaStartTime>${cut.mediaStartTime}</MediaStartTime>`);
129
130
  }
130
131
  if (cut.timemap) {
131
132
  // Constant-speed retime: swap the identity MediaTimemapBA for the
132
133
  // caller-built Sm2TimeMap (r19 keyed form render/readback-verified;
133
134
  // the clip's <In>/<Duration> are RECORD-domain, measured live).
134
- c = c.replace(/<MediaTimemapBA>[0-9a-fA-F]*<\/MediaTimemapBA>/, `<MediaTimemapBA>${cut.timemap}</MediaTimemapBA>`);
135
+ c = c.replace(/<MediaTimemapBA>[0-9a-fA-F]*<\/MediaTimemapBA>/, () => `<MediaTimemapBA>${cut.timemap}</MediaTimemapBA>`);
135
136
  }
136
137
  return c;
137
138
  };
@@ -59,11 +59,11 @@ function transplantMediaElement(mpXml, seqXmls, { poolElement, mediaRef }) {
59
59
  const folderId = (mpXml.slice(start, end).match(/<MpFolder>([0-9a-f-]{36})<\/MpFolder>/) || [])[1];
60
60
  let element = poolElement;
61
61
  if (folderId) {
62
- element = element.replace(/<MpFolder>[0-9a-f-]{36}<\/MpFolder>/, `<MpFolder>${folderId}</MpFolder>`);
62
+ element = element.replace(/<MpFolder>[0-9a-f-]{36}<\/MpFolder>/, () => `<MpFolder>${folderId}</MpFolder>`);
63
63
  }
64
64
  const outMp = mpXml.slice(0, start) + element + mpXml.slice(end);
65
65
  const outSeqs = seqXmls.map((seq) =>
66
- seq.replace(/<MediaRef>[0-9a-f-]{36}<\/MediaRef>/g, `<MediaRef>${mediaRef}</MediaRef>`),
66
+ seq.replace(/<MediaRef>[0-9a-f-]{36}<\/MediaRef>/g, () => `<MediaRef>${mediaRef}</MediaRef>`),
67
67
  );
68
68
  return { mpXml: outMp, seqXmls: outSeqs };
69
69
  }
@@ -75,7 +75,7 @@ function insertMediaElement(mpXml, poolElement) {
75
75
  const folderId = (mpXml.match(/<Sm2MpVideoClip[^>]*>[\s\S]*?<MpFolder>([0-9a-f-]{36})<\/MpFolder>/) || [])[1];
76
76
  let element = poolElement;
77
77
  if (folderId) {
78
- element = element.replace(/<MpFolder>[0-9a-f-]{36}<\/MpFolder>/, `<MpFolder>${folderId}</MpFolder>`);
78
+ element = element.replace(/<MpFolder>[0-9a-f-]{36}<\/MpFolder>/, () => `<MpFolder>${folderId}</MpFolder>`);
79
79
  }
80
80
  return mpXml.slice(0, close) + element + mpXml.slice(close);
81
81
  }
@@ -72,22 +72,22 @@ async function placeCompound(drpInput, opts = {}) {
72
72
  // the cuts machinery, 0-based frames).
73
73
  let inner = fs.readFileSync(T('compound-inner-r19.xml'), 'utf8');
74
74
  inner = freshDbIds(inner);
75
- inner = inner.replace(/<Sm2SequenceContainer DbId="[^"]+"/, `<Sm2SequenceContainer DbId="${innerContainerId}"`);
76
- inner = inner.replace(/<Sequence>[0-9a-f-]{36}<\/Sequence>/g, `<Sequence>${innerSequenceId}</Sequence>`);
75
+ inner = inner.replace(/<Sm2SequenceContainer DbId="[^"]+"/, () => `<Sm2SequenceContainer DbId="${innerContainerId}"`);
76
+ inner = inner.replace(/<Sequence>[0-9a-f-]{36}<\/Sequence>/g, () => `<Sequence>${innerSequenceId}</Sequence>`);
77
77
  inner = inner.replace(/<Items>[\s\S]*?<\/Items>/g, '<Items/>');
78
78
  zip.file(`SeqContainer/${innerContainerId}.xml`, inner);
79
79
 
80
80
  // 2) Pool compound element: fresh identities + blob SeqRef patch.
81
81
  let pool = fs.readFileSync(T('compound-pool-r19.xml'), 'utf8');
82
- pool = pool.replace(/<Sm2MpCompoundClip DbId="[^"]+"/, `<Sm2MpCompoundClip DbId="${compoundId}"`);
83
- pool = pool.replace(/<Sm2Sequence DbId="[^"]+"/, `<Sm2Sequence DbId="${innerSequenceId}"`);
84
- pool = pool.replace(/<UniqueSequenceId>[^<]*<\/UniqueSequenceId>/, `<UniqueSequenceId>${crypto.randomUUID()}</UniqueSequenceId>`);
85
- pool = pool.replace(/<UniqueMediaPoolItemId>[^<]*<\/UniqueMediaPoolItemId>/, `<UniqueMediaPoolItemId>${crypto.randomUUID()}</UniqueMediaPoolItemId>`);
86
- pool = pool.replace(/<SmPTZRPreset DbId="[^"]+"/, `<SmPTZRPreset DbId="${crypto.randomUUID()}"`);
82
+ pool = pool.replace(/<Sm2MpCompoundClip DbId="[^"]+"/, () => `<Sm2MpCompoundClip DbId="${compoundId}"`);
83
+ pool = pool.replace(/<Sm2Sequence DbId="[^"]+"/, () => `<Sm2Sequence DbId="${innerSequenceId}"`);
84
+ pool = pool.replace(/<UniqueSequenceId>[^<]*<\/UniqueSequenceId>/, () => `<UniqueSequenceId>${crypto.randomUUID()}</UniqueSequenceId>`);
85
+ pool = pool.replace(/<UniqueMediaPoolItemId>[^<]*<\/UniqueMediaPoolItemId>/, () => `<UniqueMediaPoolItemId>${crypto.randomUUID()}</UniqueMediaPoolItemId>`);
86
+ pool = pool.replace(/<SmPTZRPreset DbId="[^"]+"/, () => `<SmPTZRPreset DbId="${crypto.randomUUID()}"`);
87
87
  // The embedded sequence's <Parent> points BACK at the compound's own id —
88
88
  // the reference sweep found it as the one un-rewired link (a dangling
89
89
  // Parent is presumably as fatal as the dangling MpFolder/SeqRef were).
90
- pool = pool.replace(/<Parent>[0-9a-f-]{36}<\/Parent>/, `<Parent>${compoundId}</Parent>`);
90
+ pool = pool.replace(/<Parent>[0-9a-f-]{36}<\/Parent>/, () => `<Parent>${compoundId}</Parent>`);
91
91
  {
92
92
  const fbM = pool.match(/(<Sm2Sequence DbId="[^"]+">\s*<FieldsBlob>)([0-9a-fA-F]+)(<\/FieldsBlob>)/);
93
93
  if (!fbM) throw new Error('placeCompound: embedded Sm2Sequence FieldsBlob not found');
@@ -98,12 +98,12 @@ async function placeCompound(drpInput, opts = {}) {
98
98
  const patched = encodeKeyedDict({ hdr: dict.hdr, entries: dict.entries }).toString('hex');
99
99
  pool = pool.replace(fbM[0], `${fbM[1]}${patched}${fbM[3]}`);
100
100
  }
101
- pool = pool.replace(/<Name>[^<]*<\/Name>/, `<Name>${escapeXml(name)}</Name>`);
101
+ pool = pool.replace(/<Name>[^<]*<\/Name>/, () => `<Name>${escapeXml(name)}</Name>`);
102
102
  // MediaExtents = [startSec, durationSec] LE doubles; inner starts at 0.
103
103
  const me = Buffer.alloc(16);
104
104
  me.writeDoubleLE(0, 0);
105
105
  me.writeDoubleLE(durationFrames / fps, 8);
106
- pool = pool.replace(/<MediaExtents>[0-9a-fA-F]*<\/MediaExtents>/, `<MediaExtents>${me.toString('hex')}</MediaExtents>`);
106
+ pool = pool.replace(/<MediaExtents>[0-9a-fA-F]*<\/MediaExtents>/, () => `<MediaExtents>${me.toString('hex')}</MediaExtents>`);
107
107
  // Attach to the primary MediaPool folder — and point the element's
108
108
  // <MpFolder> at THAT folder's DbId (the template's value references the
109
109
  // harvest project's folder; a dangling folder ref CRASHES Resolve on
@@ -112,22 +112,22 @@ async function placeCompound(drpInput, opts = {}) {
112
112
  let mpXml = await zip.file(mpPath).async('string');
113
113
  const folderId = (mpXml.match(/<Sm2MpFolder DbId="([^"]+)"/) || [])[1];
114
114
  if (!folderId) throw new Error('placeCompound: target MpFolder has no Sm2MpFolder DbId');
115
- pool = pool.replace(/<MpFolder>[0-9a-f-]{36}<\/MpFolder>/, `<MpFolder>${folderId}</MpFolder>`);
116
- mpXml = mpXml.replace('</MediaVec>', `${pool}\n </MediaVec>`);
115
+ pool = pool.replace(/<MpFolder>[0-9a-f-]{36}<\/MpFolder>/, () => `<MpFolder>${folderId}</MpFolder>`);
116
+ mpXml = mpXml.replace('</MediaVec>', () => `${pool}\n </MediaVec>`);
117
117
  zip.file(mpPath, mpXml);
118
118
 
119
119
  // 3) Parent item: template clone → fresh id, name, placement, MediaRef,
120
120
  // identity timemap over the inner content ((frames − 0.5)/fps, measured).
121
121
  let item = fs.readFileSync(T('compound-item-r19.xml'), 'utf8').trim();
122
122
  item = freshDbIds(item);
123
- item = item.replace(/<Name>[^<]*<\/Name>/, `<Name>${escapeXml(name)}</Name>`);
124
- item = item.replace(/<Start>\d+<\/Start>/, `<Start>${startFrame}</Start>`);
125
- item = item.replace(/<Duration>\d+<\/Duration>/, `<Duration>${durationFrames}</Duration>`);
126
- item = item.replace(/<MediaRef>[0-9a-f-]{36}<\/MediaRef>/, `<MediaRef>${compoundId}</MediaRef>`);
123
+ item = item.replace(/<Name>[^<]*<\/Name>/, () => `<Name>${escapeXml(name)}</Name>`);
124
+ item = item.replace(/<Start>\d+<\/Start>/, () => `<Start>${startFrame}</Start>`);
125
+ item = item.replace(/<Duration>\d+<\/Duration>/, () => `<Duration>${durationFrames}</Duration>`);
126
+ item = item.replace(/<MediaRef>[0-9a-f-]{36}<\/MediaRef>/, () => `<MediaRef>${compoundId}</MediaRef>`);
127
127
  const tm = Buffer.alloc(9);
128
128
  tm.writeUInt8(0x02, 0);
129
129
  tm.writeDoubleBE((durationFrames - 0.5) / fps, 1);
130
- item = item.replace(/<MediaTimemapBA>[0-9a-fA-F]*<\/MediaTimemapBA>/, `<MediaTimemapBA>${tm.toString('hex')}</MediaTimemapBA>`);
130
+ item = item.replace(/<MediaTimemapBA>[0-9a-fA-F]*<\/MediaTimemapBA>/, () => `<MediaTimemapBA>${tm.toString('hex')}</MediaTimemapBA>`);
131
131
 
132
132
  const { match: vec, tracks } = getTrackVec(parentXml, 'video');
133
133
  if (track > tracks.length) throw new Error(`placeCompound: parent video track ${track} does not exist (${tracks.length})`);
@@ -96,9 +96,9 @@ async function placeFusionTitle(drpInput, opts = {}) {
96
96
  throw new Error('placeFusionTitle: template is not a Fusion Title clip');
97
97
  }
98
98
  clip = freshDbIds(clip);
99
- clip = clip.replace(/<Start>\d+<\/Start>/, `<Start>${startFrame}</Start>`);
100
- clip = clip.replace(/<Duration>\d+<\/Duration>/, `<Duration>${durationFrames}</Duration>`);
101
- if (name) clip = clip.replace(/<Name>[\s\S]*?<\/Name>/, `<Name>${escapeXml(name)}</Name>`);
99
+ clip = clip.replace(/<Start>\d+<\/Start>/, () => `<Start>${startFrame}</Start>`);
100
+ clip = clip.replace(/<Duration>\d+<\/Duration>/, () => `<Duration>${durationFrames}</Duration>`);
101
+ if (name) clip = clip.replace(/<Name>[\s\S]*?<\/Name>/, () => `<Name>${escapeXml(name)}</Name>`);
102
102
  const titleInputs = { text, font, style, size, vJustify, hJustify, color };
103
103
  if (Object.values(titleInputs).some((v) => v !== undefined && v !== null)) {
104
104
  const m = clip.match(/<CompositionBA>([0-9a-fA-F]*)<\/CompositionBA>/);
@@ -75,17 +75,17 @@ async function placeGenerator(drpInput, opts = {}) {
75
75
 
76
76
  let gen = fs.readFileSync(snippetPathFor(templateVersion), 'utf8').trim();
77
77
  gen = freshDbIds(gen);
78
- gen = gen.replace(/<PrettyType>[\s\S]*?<\/PrettyType>/, `<PrettyType>${escapeXml(generatorName)}</PrettyType>`);
79
- gen = gen.replace(/<Name>[\s\S]*?<\/Name>/, `<Name>${escapeXml(generatorName)}</Name>`);
80
- gen = gen.replace(/<Start>\d+<\/Start>/, `<Start>${startFrame}</Start>`);
81
- gen = gen.replace(/<Duration>\d+<\/Duration>/, `<Duration>${durationFrames}</Duration>`);
78
+ gen = gen.replace(/<PrettyType>[\s\S]*?<\/PrettyType>/, () => `<PrettyType>${escapeXml(generatorName)}</PrettyType>`);
79
+ gen = gen.replace(/<Name>[\s\S]*?<\/Name>/, () => `<Name>${escapeXml(generatorName)}</Name>`);
80
+ gen = gen.replace(/<Start>\d+<\/Start>/, () => `<Start>${startFrame}</Start>`);
81
+ gen = gen.replace(/<Duration>\d+<\/Duration>/, () => `<Duration>${durationFrames}</Duration>`);
82
82
  const colorNorm = color != null ? normalizeColor(color) : null;
83
83
  if (colorNorm) {
84
84
  const blob = solidColorEffectBlob(colorNorm);
85
85
  if (!/<EffectFiltersBA\s*\/>|<EffectFiltersBA>\s*<\/EffectFiltersBA>/.test(gen)) {
86
86
  throw new Error('placeGenerator: template carries no empty <EffectFiltersBA/> to populate with the colour');
87
87
  }
88
- gen = gen.replace(/<EffectFiltersBA\s*\/>|<EffectFiltersBA>\s*<\/EffectFiltersBA>/, `<EffectFiltersBA>${blob}</EffectFiltersBA>`);
88
+ gen = gen.replace(/<EffectFiltersBA\s*\/>|<EffectFiltersBA>\s*<\/EffectFiltersBA>/, () => `<EffectFiltersBA>${blob}</EffectFiltersBA>`);
89
89
  }
90
90
 
91
91
  const { match: vtv, tracks } = getTrackVec(seqXml, 'video');
@@ -94,9 +94,9 @@ async function placeSubtitles(drpInput, opts = {}) {
94
94
  ' <UserDefinedName/>\n <LayersVec/>\n </Sm2TiTrack>\n </Element>\n ';
95
95
  let xml;
96
96
  if (/<SubtitleTrackVec\/>/.test(seqXml)) {
97
- xml = seqXml.replace('<SubtitleTrackVec/>', `<SubtitleTrackVec>${track}</SubtitleTrackVec>`);
97
+ xml = seqXml.replace('<SubtitleTrackVec/>', () => `<SubtitleTrackVec>${track}</SubtitleTrackVec>`);
98
98
  } else if (/<SubtitleTrackVec>/.test(seqXml)) {
99
- xml = seqXml.replace('</SubtitleTrackVec>', `${track}</SubtitleTrackVec>`);
99
+ xml = seqXml.replace('</SubtitleTrackVec>', () => `${track}</SubtitleTrackVec>`);
100
100
  } else {
101
101
  throw new Error('placeSubtitles: timeline has no SubtitleTrackVec');
102
102
  }
@@ -115,9 +115,9 @@ async function placeTransition(drpInput, opts = {}) {
115
115
  let trans = fs.readFileSync(trackType === 'audio' ? AUDIO_TEMPLATE_PATH : TEMPLATE_PATH, 'utf8').trim();
116
116
  trans = freshDbIds(trans);
117
117
  if (type === 'wipe') {
118
- trans = trans.replace(/<FieldsBlob>[0-9a-fA-F]*<\/FieldsBlob>/, `<FieldsBlob>${WIPE_FIELDS_BLOB}</FieldsBlob>`);
118
+ trans = trans.replace(/<FieldsBlob>[0-9a-fA-F]*<\/FieldsBlob>/, () => `<FieldsBlob>${WIPE_FIELDS_BLOB}</FieldsBlob>`);
119
119
  } else if (STYLE_PRETTY_TYPES[type]) {
120
- trans = trans.replace(/<PrettyType>Cross Dissolve<\/PrettyType>/, `<PrettyType>${STYLE_PRETTY_TYPES[type]}</PrettyType>`);
120
+ trans = trans.replace(/<PrettyType>Cross Dissolve<\/PrettyType>/, () => `<PrettyType>${STYLE_PRETTY_TYPES[type]}</PrettyType>`);
121
121
  }
122
122
  // Span geometry follows <Start>/<Duration>, NOT AlignmentType (the E61
123
123
  // harvest of Resolve's own EDL import carries AlignmentType 2 with the
@@ -132,8 +132,8 @@ async function placeTransition(drpInput, opts = {}) {
132
132
  }
133
133
  }
134
134
  const start = spanStart !== undefined ? spanStart : atFrame - Math.floor(durationFrames / 2);
135
- trans = trans.replace(/<Start>\d+<\/Start>/, `<Start>${start}</Start>`);
136
- trans = trans.replace(/<Duration>\d+<\/Duration>/, `<Duration>${durationFrames}</Duration>`);
135
+ trans = trans.replace(/<Start>\d+<\/Start>/, () => `<Start>${start}</Start>`);
136
+ trans = trans.replace(/<Duration>\d+<\/Duration>/, () => `<Duration>${durationFrames}</Duration>`);
137
137
  const transitionDbId = (trans.match(/<Sm2TiTransition DbId="([^"]+)"/) || [])[1] || null;
138
138
 
139
139
  // Insert the transition <Element> immediately after the left clip's <Element> in <Items>.
@@ -89,7 +89,7 @@ function getItemsInner(trackElement) {
89
89
  function setItemsInner(trackElement, inner) {
90
90
  const body = inner && inner.trim() ? inner : null;
91
91
  if (/<Items\s*\/>/.test(trackElement)) {
92
- return body ? trackElement.replace(/<Items\s*\/>/, `<Items>${body}</Items>`) : trackElement;
92
+ return body ? trackElement.replace(/<Items\s*\/>/, () => `<Items>${body}</Items>`) : trackElement;
93
93
  }
94
94
  return trackElement.replace(/<Items>[\s\S]*?<\/Items>/, body ? `<Items>${body}</Items>` : '<Items/>');
95
95
  }
@@ -37,10 +37,10 @@ function clipDuration(clipXml) {
37
37
  return m ? parseInt(m[1], 10) : null;
38
38
  }
39
39
  function setClipStart(clipXml, v) {
40
- return clipXml.replace(/<Start>\d+<\/Start>/, `<Start>${v}</Start>`);
40
+ return clipXml.replace(/<Start>\d+<\/Start>/, () => `<Start>${v}</Start>`);
41
41
  }
42
42
  function setClipDuration(clipXml, v) {
43
- return clipXml.replace(/<Duration>\d+<\/Duration>/, `<Duration>${v}</Duration>`);
43
+ return clipXml.replace(/<Duration>\d+<\/Duration>/, () => `<Duration>${v}</Duration>`);
44
44
  }
45
45
  // The source IN-point lives in <In> as `<framePos>|<LE-double of framePos*0.001>`, where framePos
46
46
  // is in TIMELINE frames (verified live: Resolve appended a clip with source-in 600 media-frames @29.97
@@ -143,7 +143,7 @@ async function moveClip(drpInput, opts = {}) {
143
143
  // Optionally retime.
144
144
  if (toStart !== undefined && toStart !== null) {
145
145
  if (!Number.isInteger(toStart)) throw new TypeError('moveClip: toStart must be an integer');
146
- clip = clip.replace(/<Start>\d+<\/Start>/, `<Start>${toStart}</Start>`);
146
+ clip = clip.replace(/<Start>\d+<\/Start>/, () => `<Start>${toStart}</Start>`);
147
147
  }
148
148
 
149
149
  // Grow to the destination track with empty clones, then insert.
@@ -92,7 +92,7 @@ if not logging.getLogger().handlers:
92
92
  handlers=[logging.StreamHandler()],
93
93
  )
94
94
 
95
- VERSION = "4.18.0"
95
+ VERSION = "4.18.1"
96
96
  logger = logging.getLogger("davinci-resolve-mcp")
97
97
  logger.info(f"Starting DaVinci Resolve MCP Server v{VERSION}")
98
98
  logger.info(f"Detected platform: {get_platform()}")
package/src/server.py CHANGED
@@ -11,7 +11,7 @@ Usage:
11
11
  python src/server.py --full # Start the 377-tool granular server instead
12
12
  """
13
13
 
14
- VERSION = "4.18.0"
14
+ VERSION = "4.18.1"
15
15
 
16
16
  import base64
17
17
  import os
@@ -13357,7 +13357,9 @@ def _media_analysis_replace_owned_block(existing: Any, body: Any) -> str:
13357
13357
  + re.escape(_MCP_METADATA_BLOCK_END)
13358
13358
  )
13359
13359
  if re.search(pattern, existing_text, flags=re.DOTALL):
13360
- return re.sub(pattern, block, existing_text, flags=re.DOTALL).strip()
13360
+ # A function replacement inserts the block literally: as a string, a
13361
+ # backslash in the analysis text (a Windows path) is read as an escape.
13362
+ return re.sub(pattern, lambda _match: block, existing_text, flags=re.DOTALL).strip()
13361
13363
  return f"{existing_text}\n\n{block}".strip() if existing_text else block
13362
13364
 
13363
13365