davinci-resolve-mcp 5.1.0 → 5.2.0

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/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 = "5.1.0"
14
+ VERSION = "5.2.0"
15
15
 
16
16
  import base64
17
17
  import os
@@ -58,6 +58,7 @@ from src.utils.title_library import list_title_presets as _list_installed_title_
58
58
  from src.utils.title_controls import title_text_targets as _title_text_targets
59
59
  from src.utils.title_controls import title_text_keys as _title_text_keys
60
60
  from src.utils.resolve211_edits import validate_edit_options, validate_transition_options, transition_result
61
+ from src.utils.film_cues import export_cue_sheet as _export_film_cue_sheet
61
62
 
62
63
  # Platform-specific Resolve paths
63
64
  from src.utils.cdl import normalize_cdl_payload
@@ -27632,6 +27633,7 @@ _TIMELINE_ACTIONS = [
27632
27633
  "set_output_blanking", "normalize_audio_level", "auto_align_clips", "get_normalize_audio_modes", "get_output_blanking",
27633
27634
  # Offline authoring — served without a Resolve connection, above the _check() gate.
27634
27635
  "author_offline", "offline_fallback_capabilities",
27636
+ "film_stems_return", "film_preflight", "film_snapshot",
27635
27637
  "list", "get_current", "set_current", "get_name", "set_name", "get_start_frame",
27636
27638
  "get_end_frame", "get_start_timecode", "set_start_timecode", "get_track_count",
27637
27639
  "add_track", "delete_track", "get_track_sub_type", "set_track_enable",
@@ -27685,6 +27687,9 @@ def timeline(action: str, params: Optional[Dict[str, Any]] = None) -> Dict[str,
27685
27687
  get_output_blanking() -> {blanking} — documented on Resolve 21.1+. Pixel coordinates; empty on a clip inheriting timeline blanking.
27686
27688
  list() -> {timelines}
27687
27689
  get_current() -> {name, id, start_frame, end_frame, start_timecode}
27690
+ film_stems_return(delivery_dir, preview?, expected_timeline_id?, expected_fingerprint?) -> verified new-track film stem import; preview defaults true
27691
+ film_snapshot() -> cue_sheet, structural snapshot and picture_fingerprint for later picture-change comparison; read-only
27692
+ film_preflight(delivery_dir?, expected_picture_fingerprint?, tempo_evidence?, calibration_evidence?, capture_profile?, loudness_path?, target_lufs?, true_peak_max?) -> read-only film handoff checks; missing evidence stays unknown
27688
27693
  set_current(index|id|name) -> {success} — id/name are stable across archives; index is 1-based
27689
27694
  get_name() -> {name}
27690
27695
  set_name(name) -> {success}
@@ -27954,6 +27959,35 @@ def timeline(action: str, params: Optional[Dict[str, Any]] = None) -> Dict[str,
27954
27959
  if err:
27955
27960
  return err
27956
27961
 
27962
+ if action == "film_stems_return":
27963
+ from src.utils.film_stem_return import prepare_return
27964
+ try:
27965
+ return prepare_return(proj, p["delivery_dir"], preview=_coerce_bool(p.get("preview"), True),
27966
+ expected_timeline_id=p.get("expected_timeline_id"),
27967
+ expected_fingerprint=p.get("expected_fingerprint"))
27968
+ except (ValueError, TypeError, OSError) as exc:
27969
+ return _err(str(exc))
27970
+
27971
+ if action in ("film_preflight", "film_snapshot"):
27972
+ from src.utils.film_preflight import preflight
27973
+ tl = proj.GetCurrentTimeline()
27974
+ if not tl:
27975
+ return _err("No current timeline")
27976
+ try:
27977
+ snapshot = _timeline_conform_snapshot(tl)
27978
+ sheet = _export_film_cue_sheet(tl)
27979
+ report = preflight(sheet, snapshot,
27980
+ _detect_missing_media_from_snapshot(snapshot),
27981
+ **{key: p[key] for key in ("delivery_dir", "expected_picture_fingerprint",
27982
+ "tempo_evidence", "calibration_evidence", "capture_profile",
27983
+ "loudness_path", "target_lufs", "true_peak_max") if key in p})
27984
+ if action == "film_snapshot":
27985
+ return {"schema": "film-snapshot/v1", "cue_sheet": sheet, "snapshot": snapshot,
27986
+ "picture_fingerprint": report["picture_fingerprint"], "mutations": 0}
27987
+ return report
27988
+ except (ValueError, TypeError, OSError, KeyError) as exc:
27989
+ return _err(str(exc))
27990
+
27957
27991
  # Actions that don't need a current timeline
27958
27992
  if action == "list":
27959
27993
  count = proj.GetTimelineCount()
@@ -28652,6 +28686,8 @@ def timeline_markers(action: str, params: Optional[Dict[str, Any]] = None) -> An
28652
28686
  add(frame|frame_id|frameId|timecode?, color?, name?, note?, duration?, custom_data?, dry_run?/dryRun?) -> {success, frame} or dry-run preview
28653
28687
  If frame/timecode is omitted, add uses the current playhead timecode.
28654
28688
  get_all() -> {markers}
28689
+ export_cue_sheet(color?) -> film-cues/v1 JSON; read-only picture-to-score handoff
28690
+ compare_cue_sheets(before, after, identity_map?, before_snapshot?, after_snapshot?) -> offline film-picture-changes/v1 with optional structural picture impact; no automatic reconform
28655
28691
  get_by_custom_data(custom_data) -> {markers}
28656
28692
  update_custom_data(frame|frame_id|frameId|timecode, custom_data) -> {success}
28657
28693
  get_custom_data(frame|frame_id|frameId|timecode) -> {data}
@@ -28674,6 +28710,35 @@ def timeline_markers(action: str, params: Optional[Dict[str, Any]] = None) -> An
28674
28710
  annotation_boundary_report(scope?) -> {capabilities, annotations}
28675
28711
  """
28676
28712
  p = _params(params)
28713
+ if action == "compare_cue_sheets":
28714
+ from src.utils.film_picture_changes import compare_film_cues, compare_picture_impact
28715
+ try:
28716
+ report = compare_film_cues(p["before"], p["after"], p.get("identity_map"))
28717
+ if "before_snapshot" in p or "after_snapshot" in p:
28718
+ before_snapshot, after_snapshot = p["before_snapshot"], p["after_snapshot"]
28719
+ if not isinstance(before_snapshot, dict) or not isinstance(after_snapshot, dict):
28720
+ return _err("Both structural snapshots must be objects")
28721
+ impact = compare_picture_impact(p["before"], p["after"], before_snapshot, after_snapshot,
28722
+ {})
28723
+ try:
28724
+ impact["editorial_comparison"] = _compare_timeline_snapshots(before_snapshot, after_snapshot)
28725
+ except (AttributeError, TypeError, KeyError) as exc:
28726
+ # Impact validation retains unreadable spans as unknown. The
28727
+ # older comparator requires complete enumeration; its failure
28728
+ # must not discard that conservative evidence or imply a match.
28729
+ impact["editorial_comparison"] = {
28730
+ "status": "unknown", "reason": "Structural comparison unavailable: " + str(exc)}
28731
+ impact["requires_human_review"] = True
28732
+ report["picture_impact"] = impact
28733
+ report["requires_human_review"] |= impact["requires_human_review"]
28734
+ else:
28735
+ report["picture_impact"] = {"status": "unknown", "reason": "Supply both structural snapshots to assess picture edits beneath unchanged cues"}
28736
+ report["requires_human_review"] = True
28737
+ return report
28738
+ except _MissingParam as exc:
28739
+ return _missing_param_error(exc, action)
28740
+ except (ValueError, TypeError, OverflowError, KeyError) as exc:
28741
+ return _err(str(exc))
28677
28742
  _, tl, err = _get_tl()
28678
28743
  if err:
28679
28744
  return err
@@ -28700,6 +28765,11 @@ def timeline_markers(action: str, params: Optional[Dict[str, Any]] = None) -> An
28700
28765
  return _add_marker(tl, marker)
28701
28766
  elif action == "get_all":
28702
28767
  return {"markers": _ser(tl.GetMarkers())}
28768
+ elif action == "export_cue_sheet":
28769
+ try:
28770
+ return _export_film_cue_sheet(tl, color=p.get("color"))
28771
+ except (ValueError, TypeError, OverflowError) as exc:
28772
+ return _err(str(exc))
28703
28773
  elif action == "get_by_custom_data":
28704
28774
  return {"markers": _ser(tl.GetMarkerByCustomData(_first_param(p, "custom_data", "customData", default="")))}
28705
28775
  elif action == "update_custom_data":
@@ -28775,7 +28845,7 @@ def timeline_markers(action: str, params: Optional[Dict[str, Any]] = None) -> An
28775
28845
  return _export_review_report(tl, p)
28776
28846
  elif action == "annotation_boundary_report":
28777
28847
  return _annotation_boundary_report(tl, p)
28778
- return _unknown(action, ["add","get_all","get_by_custom_data","update_custom_data","get_custom_data","delete_by_color","delete_at_frame","delete_by_custom_data","get_current_timecode","set_current_timecode","get_current_video_item","get_thumbnail","get_thumbnail_image",*_ANNOTATION_KERNEL_ACTIONS])
28848
+ return _unknown(action, ["add","get_all","export_cue_sheet","compare_cue_sheets","get_by_custom_data","update_custom_data","get_custom_data","delete_by_color","delete_at_frame","delete_by_custom_data","get_current_timecode","set_current_timecode","get_current_video_item","get_thumbnail","get_thumbnail_image",*_ANNOTATION_KERNEL_ACTIONS])
28779
28849
 
28780
28850
 
28781
28851
  # ═══════════════════════════════════════════════════════════════════════════════
@@ -43,6 +43,7 @@ from src.utils.execution_lifecycle import (
43
43
  RiskClassificationHook,
44
44
  RiskLevel,
45
45
  classify_operation_risk,
46
+ is_preview_only,
46
47
  )
47
48
 
48
49
  logger = logging.getLogger("resolve-mcp.destructive-hook")
@@ -183,6 +184,10 @@ DESTRUCTIVE_ACTIONS_BY_TOOL: Dict[str, FrozenSet[str]] = {
183
184
  "clear_mark_in_out",
184
185
  "set_title_text",
185
186
  "import_into_timeline",
187
+ # Imports the stems and appends each onto a new audio track. Only the
188
+ # apply call (preview=false) mutates; is_preview_only keeps the default
189
+ # preview call from archiving a version.
190
+ "film_stems_return",
186
191
  }),
187
192
  "timeline_markers": frozenset({
188
193
  "add",
@@ -348,6 +353,10 @@ DRY_RUN_DEFAULT_TRUE_ACTIONS: frozenset = frozenset({
348
353
  ("timeline", "ripple_insert"),
349
354
  })
350
355
 
356
+ # Actions whose plan-only flag is `preview` rather than `dry_run` are listed
357
+ # in execution_lifecycle.PREVIEW_DEFAULT_TRUE_ACTIONS, so the risk rating and
358
+ # the archive decision read one table.
359
+
351
360
 
352
361
  # ── Native dry-run allowlist ────────────────────────────────────────────────
353
362
  #
@@ -458,6 +467,8 @@ def _payload_is_plan_only(
458
467
  tool_name: str, action: str, params: Optional[Dict[str, Any]],
459
468
  ) -> bool:
460
469
  """True iff this call only produces a plan and mutates nothing."""
470
+ if is_preview_only(tool_name, action, params):
471
+ return True
461
472
  dry_run = explicit_bool_param(params, "dry_run", "dryRun")
462
473
  if (tool_name, action) in NATIVE_DRY_RUN_ACTIONS and dry_run is True:
463
474
  return True
@@ -30,6 +30,22 @@ from src.utils.bool_params import coerce_bool
30
30
  logger = logging.getLogger("resolve-mcp.execution-lifecycle")
31
31
 
32
32
 
33
+ #: Actions whose plan-only flag is `preview`, defaulting to True: the call
34
+ #: mutates only when `preview` is explicitly false. Shared with
35
+ #: destructive_hook, which uses it to skip archiving a preview call.
36
+ PREVIEW_DEFAULT_TRUE_ACTIONS: frozenset = frozenset({
37
+ ("timeline", "film_stems_return"),
38
+ })
39
+
40
+
41
+ def is_preview_only(tool_name: str, action: str, params: Optional[Dict[str, Any]]) -> bool:
42
+ """True iff this is a `preview`-gated action called in preview mode."""
43
+ if (tool_name, action) not in PREVIEW_DEFAULT_TRUE_ACTIONS:
44
+ return False
45
+ value = params.get("preview") if isinstance(params, dict) else None
46
+ return coerce_bool(value, True)
47
+
48
+
33
49
  class RiskLevel(str, enum.Enum):
34
50
  """Categorized risk level for tool operations."""
35
51
  LOW = "low" # Read-only queries, info probes, and known-reversible edits
@@ -320,6 +336,12 @@ class RiskClassificationHook(LifecycleHook):
320
336
  ("timeline", "insert_fusion_composition"),
321
337
  ("timeline", "insert_ofx_generator"),
322
338
  ("media_pool", "append_to_timeline"),
339
+ # Applied (preview=false): imports the stems into the pool and appends
340
+ # each onto a NEW audio track. Existing tracks are refused rather than
341
+ # touched, but the pool and the track list change and a partial failure
342
+ # is left in place for review. The preview call is classified read-only
343
+ # before this table is consulted (PREVIEW_DEFAULT_TRUE_ACTIONS).
344
+ ("timeline", "film_stems_return"),
323
345
  # Timeline-wide settings. No content lost, but a wrong start timecode
324
346
  # silently invalidates every conform and reference built against it.
325
347
  ("timeline", "set_setting"),
@@ -424,6 +446,19 @@ class RiskClassificationHook(LifecycleHook):
424
446
 
425
447
  pair = (tool_name, action)
426
448
 
449
+ if is_preview_only(tool_name, action, params):
450
+ # Preview reads the package and the timeline and returns a plan
451
+ # with a fingerprint; nothing is written until preview=false.
452
+ return RiskAssessment(
453
+ level=RiskLevel.LOW,
454
+ destructive=False,
455
+ blast_radius=BlastRadius.ITEM,
456
+ confirmation_required=False,
457
+ snapshot_available=None,
458
+ reasons=[f"Preview of '{action}': read-only plan, nothing is written"],
459
+ recognised=True,
460
+ )
461
+
427
462
  if pair in cls._CRITICAL_ACTIONS:
428
463
  level = RiskLevel.CRITICAL
429
464
  destructive = True
@@ -658,6 +693,8 @@ class DriftDetectionHook(LifecycleHook):
658
693
  and post_dur is not None
659
694
  and pre_dur != post_dur
660
695
  and ctx.action not in self._DURATION_ALTERING_ACTIONS
696
+ and not (ctx.tool_name == "timeline" and ctx.action == "film_stems_return"
697
+ and not coerce_bool(ctx.params.get("preview"), True))
661
698
  ):
662
699
  warning = (
663
700
  f"Timeline duration drifted unexpectedly from {pre_dur} to {post_dur} frames "
@@ -0,0 +1,85 @@
1
+ """Read-only picture-to-score interchange; frames, not timecodes, are canonical.
2
+
3
+ Resolve timeline marker keys are relative to timeline start, even for markers
4
+ later than that start's absolute frame number. Never guess/rebase those keys.
5
+ """
6
+ from fractions import Fraction
7
+ import math
8
+ import re
9
+
10
+
11
+ def _integer(value, field, minimum=0):
12
+ if isinstance(value, bool):
13
+ raise ValueError(f"{field} must be an integer >= {minimum}")
14
+ try:
15
+ number = Fraction(str(value))
16
+ except (ValueError, ZeroDivisionError) as exc:
17
+ raise ValueError(f"{field} must be an integer >= {minimum}") from exc
18
+ if number.denominator != 1 or number < minimum:
19
+ raise ValueError(f"{field} must be an integer >= {minimum}")
20
+ return int(number)
21
+
22
+
23
+ def _rate(value):
24
+ text = str(value).strip()
25
+ match = re.fullmatch(r"(\d+(?:\.\d+)?(?:/\d+)?)\s*(?:DF|NDF)?", text)
26
+ if not match:
27
+ raise ValueError("timelineFrameRate must be a positive numeric frame rate")
28
+ text = match[1]
29
+ # Resolve displays rounded NTSC rates. Recover their standard clock rates
30
+ # before converting a feature-length timeline to seconds.
31
+ ntsc = {"23.976": 24000, "23.98": 24000, "29.97": 30000,
32
+ "47.952": 48000, "59.94": 60000, "119.88": 120000}
33
+ try:
34
+ rate = Fraction(ntsc[text], 1001) if text in ntsc else Fraction(text)
35
+ except (ValueError, ZeroDivisionError) as exc:
36
+ raise ValueError("Invalid timelineFrameRate") from exc
37
+ if rate <= 0 or rate > 1000:
38
+ raise ValueError("timelineFrameRate must be between 0 and 1000 fps")
39
+ return rate
40
+
41
+
42
+ def export_cue_sheet(timeline, *, color=None):
43
+ """Return a film-cues/v1 payload without writing files or changing Resolve.
44
+
45
+ ``start_frame`` inside each cue is relative; ``timeline.start_frame`` is
46
+ absolute metadata only. Seconds are convenient approximations; consumers
47
+ must derive timing from integer frames and the rational frame rate.
48
+ """
49
+ if color is not None and (not isinstance(color, str) or not color.strip()):
50
+ raise ValueError("color must be a non-empty marker colour name")
51
+ rate = _rate(timeline.GetSetting("timelineFrameRate"))
52
+ start = _integer(timeline.GetStartFrame(), "timeline start frame")
53
+ markers = timeline.GetMarkers()
54
+ if not isinstance(markers, dict):
55
+ raise ValueError("Resolve did not return a marker dictionary")
56
+ cues = []
57
+ seen = set()
58
+ for key, marker in markers.items():
59
+ if not isinstance(marker, dict):
60
+ raise ValueError("Resolve returned an invalid marker record")
61
+ frame = _integer(key, "marker frame")
62
+ if frame in seen:
63
+ raise ValueError(f"Duplicate marker frame {frame}")
64
+ seen.add(frame)
65
+ duration = _integer(marker.get("duration"), "marker duration", 1)
66
+ values = {}
67
+ for source, target in (("name", "name"), ("note", "note"),
68
+ ("color", "color"), ("customData", "custom_data")):
69
+ value = marker.get(source, "")
70
+ if not isinstance(value, str):
71
+ raise ValueError(f"marker {source} must be a string")
72
+ values[target] = value
73
+ seconds, duration_seconds = float(frame / rate), float(duration / rate)
74
+ if not math.isfinite(seconds) or not math.isfinite(duration_seconds):
75
+ raise ValueError("Marker timing exceeds the supported numeric range")
76
+ if color is not None and values["color"].casefold() != color.casefold():
77
+ continue
78
+ cues.append({"id": f"marker:{frame}", **values,
79
+ "start_frame": frame, "duration_frames": duration,
80
+ "start_seconds": seconds, "duration_seconds": duration_seconds})
81
+ return {"schema": "film-cues/v1",
82
+ "frame_rate": {"numerator": rate.numerator, "denominator": rate.denominator},
83
+ "timeline": {"name": timeline.GetName(), "start_frame": start,
84
+ "start_timecode": timeline.GetStartTimecode()},
85
+ "cues": sorted(cues, key=lambda cue: cue["start_frame"])}