davinci-resolve-mcp 5.2.8 → 5.2.10

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.
@@ -0,0 +1,133 @@
1
+ """trackIndex / mediaType validation for AppendToTimeline clipInfo rows.
2
+
3
+ Resolve takes a trackIndex that names no existing track (0, beyond the track
4
+ count) or that is not an int (``"2"``) and places the item on track 1, answering
5
+ with the new items as if the request were honoured (issue #370). The server's
6
+ own read-back then reports the wrong-track placement as verified. These checks
7
+ run before anything reaches AppendToTimeline.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any, Optional, Tuple
13
+
14
+ MEDIA_TYPES = {1: "video", 2: "audio"}
15
+
16
+
17
+ def _as_int(value: Any) -> Optional[int]:
18
+ """An int from an int, an integral float, or a digit string; else None."""
19
+ if isinstance(value, bool):
20
+ return None
21
+ if isinstance(value, int):
22
+ return value
23
+ if isinstance(value, float):
24
+ return int(value) if value.is_integer() else None
25
+ if isinstance(value, str):
26
+ text = value.strip()
27
+ if text.lstrip("+-").isdigit():
28
+ return int(text)
29
+ return None
30
+
31
+
32
+ def coerce_track_index(value: Any, index: int) -> Tuple[Optional[int], Optional[str]]:
33
+ """(track_index, None) or (None, message) for a clipInfo row's trackIndex."""
34
+ ti = _as_int(value)
35
+ if ti is None:
36
+ return None, (
37
+ f"clip_infos[{index}] track_index must be an integer (1-based), got {value!r}"
38
+ )
39
+ if ti < 1:
40
+ return None, f"clip_infos[{index}] track_index must be >= 1 (1-based), got {ti}"
41
+ return ti, None
42
+
43
+
44
+ def coerce_media_type(value: Any, index: int) -> Tuple[Optional[int], Optional[str]]:
45
+ """(media_type, None) or (None, message); None in means None out."""
46
+ if value is None:
47
+ return None, None
48
+ mt = _as_int(value)
49
+ if mt not in MEDIA_TYPES:
50
+ return None, (
51
+ f"clip_infos[{index}] media_type must be 1 (video only) or 2 (audio only), "
52
+ f"got {value!r}"
53
+ )
54
+ return mt, None
55
+
56
+
57
+ def track_count(timeline: Any, track_type: str) -> Optional[int]:
58
+ try:
59
+ return int(timeline.GetTrackCount(track_type) or 0)
60
+ except Exception:
61
+ return None
62
+
63
+
64
+ def track_range_error(timeline: Any, track_index: int, media_type: Optional[int],
65
+ index: int) -> Optional[dict]:
66
+ """Refusal fields when track_index names no track on `timeline`, else None.
67
+
68
+ With media_type set, the index is checked against that track type. Without
69
+ it, Resolve places video on the video track and audio on the audio track of
70
+ that index, and an audio-only or video-only clip uses only one of them, so
71
+ only an index past both counts is refused. An unreadable count is not
72
+ refused here.
73
+ """
74
+ if timeline is None:
75
+ return None
76
+ types = [MEDIA_TYPES[media_type]] if media_type in MEDIA_TYPES else ["video", "audio"]
77
+ counts = {t: track_count(timeline, t) for t in types}
78
+ if any(c is None for c in counts.values()):
79
+ return None
80
+ if any(track_index <= c for c in counts.values()):
81
+ return None
82
+ described = " and ".join(f"{c} {t}" for t, c in counts.items())
83
+ kind = types[0] if len(types) == 1 else "video or audio"
84
+ return {
85
+ "message": (
86
+ f"clip_infos[{index}] track_index {track_index} names no {kind} track: the "
87
+ f"timeline has {described} track(s). Resolve would place the clip on track 1 "
88
+ "and report success; nothing was appended."
89
+ ),
90
+ "code": "TRACK_INDEX_OUT_OF_RANGE",
91
+ "category": "invalid_input",
92
+ "remediation": "Add the track first (timeline add_track), or pass an existing track_index.",
93
+ "state": {"track_index": track_index, "media_type": media_type, "track_counts": counts},
94
+ }
95
+
96
+
97
+ def needed_tracks(rows: Any) -> Tuple[Optional[dict], Optional[str]]:
98
+ """({"video": n, "audio": m}, None) for the tracks `rows` name, or (None, message).
99
+
100
+ For building a new timeline from rows: each row's track_index (default 1)
101
+ must be valid, and the timeline then needs that many tracks of the row's
102
+ media type, or of both types when the row sets none.
103
+ """
104
+ needed = {"video": 1, "audio": 0}
105
+ for i, ci in enumerate(rows if isinstance(rows, list) else []):
106
+ if not isinstance(ci, dict):
107
+ continue
108
+ ti, err = coerce_track_index(ci.get("trackIndex", ci.get("track_index", 1)), i)
109
+ if err:
110
+ return None, err
111
+ mt, err = coerce_media_type(ci.get("mediaType", ci.get("media_type")), i)
112
+ if err:
113
+ return None, err
114
+ for track_type in ([MEDIA_TYPES[mt]] if mt else ["video", "audio"]):
115
+ needed[track_type] = max(needed[track_type], ti)
116
+ return needed, None
117
+
118
+
119
+ def ensure_tracks(timeline: Any, needed: dict) -> Optional[str]:
120
+ """Add tracks until `timeline` has `needed` of each type; an error message or None."""
121
+ for track_type, count in needed.items():
122
+ current = track_count(timeline, track_type)
123
+ if current is None:
124
+ return f"GetTrackCount({track_type}) failed"
125
+ while current < count:
126
+ try:
127
+ ok = timeline.AddTrack(track_type)
128
+ except Exception as exc:
129
+ return f"AddTrack({track_type}) failed: {exc}"
130
+ if not ok:
131
+ return f"AddTrack({track_type}) returned false at track {current + 1}"
132
+ current += 1
133
+ return None
@@ -0,0 +1,79 @@
1
+ """Refuse tool arguments the tool's signature does not name (issue #372).
2
+
3
+ FastMCP validates a call's arguments with a pydantic model built from the tool
4
+ function's signature, and that model ignores keys it has no field for. For the
5
+ compound tools, which take `(action, params)`, a selector passed beside
6
+ `action` instead of inside `params` — `timeline(action="get_name",
7
+ timeline_name="vB")` — was therefore dropped before any server code ran, and
8
+ the call acted on the current timeline and answered success. Nothing
9
+ downstream could report it as `ignored_params`, because nothing downstream
10
+ ever saw it.
11
+
12
+ The check runs at the protocol boundary, before the tool is called, and
13
+ refuses rather than folding the keys into `params`: a guessed placement is
14
+ another way to act on something the caller did not ask for.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Any, Dict, Iterable, List, Optional
20
+
21
+
22
+ def accepted_arguments(tool: Any) -> Optional[set]:
23
+ """The argument names `tool` accepts (field names and aliases), or None if unknown."""
24
+ model = getattr(getattr(tool, "fn_metadata", None), "arg_model", None)
25
+ fields = getattr(model, "model_fields", None)
26
+ if not isinstance(fields, dict):
27
+ return None
28
+ names = set(fields)
29
+ names.update(f.alias for f in fields.values() if getattr(f, "alias", None))
30
+ return names
31
+
32
+
33
+ def unknown_arguments(tool: Any, arguments: Optional[Dict[str, Any]]) -> List[str]:
34
+ """Keys of `arguments` that `tool` has no parameter for, sorted."""
35
+ if not isinstance(arguments, dict) or not arguments:
36
+ return []
37
+ accepted = accepted_arguments(tool)
38
+ if accepted is None:
39
+ return []
40
+ return sorted(str(k) for k in arguments if k not in accepted)
41
+
42
+
43
+ def refusal(tool_name: str, unknown: Iterable[str], arguments: Dict[str, Any],
44
+ accepted: Optional[set]) -> Dict[str, Any]:
45
+ """The error envelope for a call that passed arguments the tool does not take."""
46
+ unknown = list(unknown)
47
+ quoted = ", ".join(repr(k) for k in unknown)
48
+ takes_params = bool(accepted) and "params" in accepted
49
+ if takes_params:
50
+ moved = dict(arguments.get("params") or {}) if isinstance(arguments.get("params"), dict) else {}
51
+ moved.update({k: arguments[k] for k in unknown})
52
+ message = (
53
+ f"{tool_name} does not take {quoted} beside 'action'; this tool reads its "
54
+ f"arguments from 'params'. Nothing was run: the key would have been dropped "
55
+ f"and the call would have acted with it unset (for a timeline selector, on "
56
+ f"the current timeline)."
57
+ )
58
+ remediation = f"Move {quoted} into params, e.g. params={moved!r}."
59
+ state = {"unknown_arguments": unknown, "corrected_params": moved}
60
+ else:
61
+ message = (
62
+ f"{tool_name} has no parameter {quoted}. Nothing was run: the key would "
63
+ "have been dropped silently."
64
+ )
65
+ remediation = "Pass only the parameters the tool's input schema lists."
66
+ state = {"unknown_arguments": unknown}
67
+ if accepted:
68
+ state["accepted_arguments"] = sorted(accepted)
69
+ return {
70
+ "success": False,
71
+ "error": {
72
+ "message": message,
73
+ "code": "UNKNOWN_ARGUMENTS",
74
+ "category": "invalid_input",
75
+ "retryable": True,
76
+ "remediation": remediation,
77
+ "state": state,
78
+ },
79
+ }
@@ -78,4 +78,28 @@ class ErrorFlaggingFastMCP(FastMCP):
78
78
  """
79
79
 
80
80
  async def call_tool(self, name: str, arguments: dict[str, Any]) -> Any:
81
+ refused = refuse_unknown_arguments(self, name, arguments)
82
+ if refused is not None:
83
+ return refused
81
84
  return flag_tool_error(await super().call_tool(name, arguments))
85
+
86
+
87
+ def refuse_unknown_arguments(server: Any, name: str, arguments: Any) -> Any:
88
+ """An `isError` result when `arguments` holds keys the tool does not take (#372), else None."""
89
+ from mcp.types import CallToolResult, TextContent
90
+
91
+ from src.utils import mcp_arg_guard
92
+
93
+ try:
94
+ tool = server._tool_manager.get_tool(name)
95
+ except Exception:
96
+ return None
97
+ unknown = mcp_arg_guard.unknown_arguments(tool, arguments)
98
+ if not unknown:
99
+ return None
100
+ body = mcp_arg_guard.refusal(name, unknown, arguments, mcp_arg_guard.accepted_arguments(tool))
101
+ return CallToolResult(
102
+ content=[TextContent(type="text", text=json.dumps(body, indent=2))],
103
+ structuredContent=body,
104
+ isError=True,
105
+ )
@@ -11,7 +11,7 @@ import shutil
11
11
  import subprocess
12
12
  import uuid
13
13
  from pathlib import Path
14
- from src.utils.resolve_writes import set_current_timeline, describe_switch_failure
14
+ from src.utils.resolve_writes import set_current_timeline, describe_switch_failure, unique_id
15
15
  from src.utils.title_library import find_subtitle_preset
16
16
 
17
17
  ROOT = Path(__file__).resolve().parents[2]
@@ -130,10 +130,97 @@ def _preflight(timeline, params):
130
130
  return node, dry_run, track
131
131
 
132
132
 
133
+ def _post_write_database_health(resolve, project_id, timeline, target_track):
134
+ """Check that a live subtitle write left the same project readable.
135
+
136
+ Guards against a native import or timeline switch that answers success
137
+ while Resolve has moved to another project or lost its database. That
138
+ state has not been measured on a build; the check is defensive (#373).
139
+ Never attempt a repair here: the safe remediation is a manual Resolve
140
+ restart.
141
+ """
142
+ health = {
143
+ "healthy": False,
144
+ "project_id_before": project_id,
145
+ "project_id_after": None,
146
+ "project_unchanged": False,
147
+ "database_attached": False,
148
+ "current_timeline_id": None,
149
+ "expected_timeline_id": unique_id(timeline),
150
+ "current_timeline_verified": False,
151
+ "target_track": target_track,
152
+ "target_item_count": None,
153
+ "target_items_healthy": False,
154
+ "errors": [],
155
+ }
156
+ try:
157
+ pm = resolve.GetProjectManager()
158
+ database = pm.GetCurrentDatabase() if pm else None
159
+ health["database_attached"] = bool(database)
160
+ if not database:
161
+ health["errors"].append("Resolve has no database attached")
162
+ current_project = pm.GetCurrentProject() if pm else None
163
+ except Exception as exc:
164
+ health["errors"].append(f"Project/database readback failed: {exc}")
165
+ return health
166
+
167
+ health["project_id_after"] = unique_id(current_project)
168
+ health["project_unchanged"] = bool(
169
+ project_id and health["project_id_after"] == project_id
170
+ )
171
+ if current_project is None:
172
+ health["errors"].append("Resolve returned no current project after the write")
173
+ elif not health["project_unchanged"]:
174
+ health["errors"].append("The current project unique ID changed during the write")
175
+
176
+ try:
177
+ current_timeline = current_project.GetCurrentTimeline() if current_project else None
178
+ health["current_timeline_id"] = unique_id(current_timeline)
179
+ health["current_timeline_verified"] = bool(
180
+ health["expected_timeline_id"]
181
+ and health["current_timeline_id"] == health["expected_timeline_id"]
182
+ )
183
+ if not health["current_timeline_verified"]:
184
+ health["errors"].append("The verified subtitle revision is not the current timeline")
185
+ except Exception as exc:
186
+ health["errors"].append(f"Current timeline readback failed: {exc}")
187
+ return health
188
+
189
+ if not health["current_timeline_verified"]:
190
+ return health
191
+ item_errors = []
192
+ try:
193
+ items = current_timeline.GetItemListInTrack("subtitle", target_track)
194
+ if items is None:
195
+ raise RuntimeError("GetItemListInTrack returned None")
196
+ health["target_item_count"] = len(items)
197
+ for item in items:
198
+ if not unique_id(item):
199
+ item_errors.append("A target subtitle item has no readable unique ID")
200
+ continue
201
+ start, end = item.GetStart(), item.GetEnd()
202
+ if start is None or end is None or end < start:
203
+ item_errors.append(f"Subtitle item {unique_id(item)} has invalid bounds")
204
+ except Exception as exc:
205
+ item_errors.append(f"Target subtitle item readback failed: {exc}")
206
+ health["target_items_healthy"] = not item_errors and health["target_item_count"] is not None
207
+ health["errors"].extend(item_errors)
208
+ health["healthy"] = bool(
209
+ health["database_attached"]
210
+ and health["project_unchanged"]
211
+ and health["current_timeline_verified"]
212
+ and health["target_items_healthy"]
213
+ and not health["errors"]
214
+ )
215
+ return health
216
+
217
+
133
218
  def _revise(resolve, project, timeline, params, safe_dir, *, dry_run, build, check, report, edited_track=None):
134
219
  """Export, build(source, output, staging) a patched DRT, import it as a selected
135
220
  revision and check(readback, patch) Resolve's re-export of it. The original is
136
221
  never modified and stays active on any failure or preview."""
222
+ project_id = unique_id(project)
223
+ database_health = None
137
224
  name = params.get("revision_name") or f"{timeline.GetName()} - subtitles {uuid.uuid4().hex[:8]}"
138
225
  if any(project.GetTimelineByIndex(i).GetName() == name for i in range(1, project.GetTimelineCount() + 1)):
139
226
  return {"success": False, "error": "revision_name already exists"}
@@ -179,17 +266,39 @@ def _revise(resolve, project, timeline, params, safe_dir, *, dry_run, build, che
179
266
  if original_timecode:
180
267
  if not imported.SetCurrentTimecode(original_timecode) or imported.GetCurrentTimecode() != original_timecode:
181
268
  warnings.append("Subtitle revision was selected, but its playhead could not be restored")
269
+ database_health = _post_write_database_health(
270
+ resolve, project_id, imported, params.get("track", 1)
271
+ )
272
+ if not database_health["healthy"]:
273
+ result = {
274
+ "success": False,
275
+ "error": "Resolve project/database health verification failed after the subtitle write",
276
+ "error_code": "RESOLVE_DATABASE_UNHEALTHY",
277
+ "restart_required": True,
278
+ "remediation": ("Quit and restart Resolve manually, then reopen and inspect the project before "
279
+ "retrying. This tool does not repair a detached Resolve database."),
280
+ "api_success": True,
281
+ "verified": False,
282
+ "database_health": database_health,
283
+ "original_export": str(source),
284
+ "failed_revision": imported.GetName(),
285
+ }
286
+ return result
182
287
  succeeded = True
183
288
  result = {"success": True, "restart_required": False, "original_timeline": timeline.GetName(),
184
289
  "timeline": imported.GetName(), "timeline_id": imported.GetUniqueId(),
185
- "patch": patch, **report, "render_verified": False}
290
+ "patch": patch, **report, "render_verified": False,
291
+ "api_success": True, "database_health": database_health, "verified": True}
186
292
  if warnings:
187
293
  result["warnings"] = warnings
188
294
  return result
189
295
  except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc:
190
296
  result = {"success": False, "error": str(exc), "restart_required": False,
297
+ "api_success": False, "verified": False,
191
298
  "original_export": str(source),
192
299
  "failed_revision": imported.GetName() if imported else None}
300
+ if database_health is not None:
301
+ result["database_health"] = database_health
193
302
  return result
194
303
  finally:
195
304
  # A failed or preview operation must leave the user's working timeline active.