Files

102 lines
6.6 KiB
Markdown
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# CLAUDE.md — fcp-mcp-server
## Idioma (MANDATORY)
Responder **sempre em português** ao usuário, sem exceção. Nunca responder em
inglês nas mensagens de chat/prompt — inclusive resumos, atualizações de
progresso e confirmações. Comentários e nomes de código continuam em inglês
normalmente; a regra é sobre a comunicação com o usuário.
## What This Is
MCP server that reads/writes Final Cut Pro XML (FCPXML) files. 73 tools for timeline analysis, batch editing, QC, generation, multi-track support, media relink, NLE export, transcript-based editing (local Whisper), and LIVE FCP control (push_to_fcp / list_fcp_libraries via Apple events). Reads FCPXML 1.8–1.14 (incl. `.fcpxmld` bundles with sidecar preservation), writes 1.13 by default. Dual-mode (XML + Live) direction: `code/docs/CAPABILITY-AUDIT-2026-06.md`.
## Architecture
Toda a estrutura do projeto fica em `code/`. A pasta `admin/` fica na raiz (fora de `code/`).
```
code/server.py — MCP server entry point. All 62 tool definitions, handlers, resources, prompts.
Dispatch dict pattern: TOOL_HANDLERS maps tool names → async handler functions.
code/fcpxml/parser.py — Reads FCPXML → Python objects (Timeline, Clip, ConnectedClip, Marker, etc.)
code/fcpxml/writer.py — Writes modifications back to FCPXML. Handles markers, trimming, gaps, transitions.
code/fcpxml/rough_cut.py — Generates new timelines from source clips (rough cuts, montages, A/B rolls).
code/fcpxml/diff.py — Timeline comparison engine. Detects added/removed/moved/trimmed clips & markers.
code/fcpxml/export.py — DaVinci Resolve FCPXML v1.9 export + FCP7 XMEML v5 export for cross-NLE workflows.
code/fcpxml/models.py — Data classes: TimeValue, Timecode, Clip, ConnectedClip, CompoundClip, Timeline, etc.
code/fcpxml/media_intel.py — Real media analysis. Audio silence detection + beat detection.
code/fcpxml/dtd.py — Validates output against Apple's official DTDs.
```
## Key Patterns
- **TimeValue**: All times are rational fractions (numerator/denominator) matching FCPXML's `"600/2400s"` format. Never use floats for time math.
- **_parse_project()**: Helper that parses FCPXML and returns `(tree, timeline, project)` tuple. Most handlers start with this.
- **generate_output_path()**: Creates `_modified`, `_chapters`, etc. suffixed output paths so originals aren't overwritten.
- **Tool handlers**: Each tool has its own `async def handle_<name>(arguments: dict)` function. All return via `_text_result(text)` which wraps strings in the MCP `TextContent` list.
- **Connected clips**: Clips with `lane` attribute hang off spine clips. Positive lane = above (video), negative = below (audio). Secondary `<storyline>` elements also contain connected clips.
- **XMEML export**: Converts spine-based model to track-based model. Primary storyline → Track 0, connected clip lanes → higher tracks.
## Running
```bash
cd code && uv run server.py # Start MCP server
cd code && uv run --extra dev pytest tests/ -v # Run tests
```
## Registro de Experiências e Boas Práticas (MANDATORY)
Sempre que um problema de estrutura ou um erro recorrente for detectado e
corrigido, **registre-o** em `code/Engine/docs/05_EXPERIENCIAS.md` (template já
presente no arquivo). Antes de concluir qualquer alteração/correção, aplique e
verifique as boas práticas e o checklist final em
`code/Engine/docs/06_BOAS_PRATICAS.md`.
## Pre-Commit (MANDATORY)
Padrão do sistema: **sempre após concluir uma correção, o sistema é
automaticamente executado/validado.** Acione o script único a cada correção:
```bash
cd code && ./Engine/run_after_fix.sh
```
Ele roda o lint (zero erros) e toda a suíte de testes, e falha se qualquer um
não passar. Equivalente a rodar manualmente os dois comandos abaixo.
## Executar o App Localmente (MANDATORY)
Sempre que uma alteração for feita no app (MacApp/) durante o período de
implementação, **compile e rode o programa localmente no computador** para
validar visualmente a alteração, além de rodar os testes:
```bash
cd code && ./MacApp/build_app.sh --run # compila e abre o app localmente
```
Regra geral: após qualquer alteração, o app deve ser executado localmente
antes de concluir a tarefa. Se houver erro de compilação, corrija antes de
seguir.
Before committing ANY changes, run both:
```bash
cd code && ruff check . --exclude docs/ # Lint — must pass with zero errors
cd code && pytest tests/ -v # Tests — all must pass
```
CI runs both on every push to main. If either fails, the commit gets an X on GitHub. Fix lint errors before committing, not after.
## Testing
1342 tests across 34 files. `test_models.py` covers TimeValue arithmetic, Timecode parsing/formatting, Clip properties, validation models, and Timeline helpers. `test_writer.py` covers insert_clip, add_marker (all types), trim_clip, delete_clip, split_clip, and change_speed operations. `test_server.py` covers MCP tool handlers, parsers, and dispatch. `test_rough_cut.py` covers RoughCutGenerator. `test_features_v05.py` covers connected clips, roles, timeline diff, reformat, silence detection, export, and backward compatibility. `test_marker_pipeline.py` covers build_marker_element shared builder, batch auto-modes, clip index duplicate-name behavior, and write_fcpxml output format. `test_refactored_helpers.py` covers _index_elements, _iter_spine_clips, _find_spine_clip_at_seconds, _resolve_clip_duration, _make_asset_clip, _format_batch_result, and serialize_xml edge cases. `test_transcribe.py` covers phrase/filler span matching, range merge/invert algebra, whisper graceful degradation, and transcript-driven handler cuts against cached transcripts. `test_media_intel.py` covers silencedetect stderr parsing, source-to-timeline mapping, parameter bounds, and real-WAV ffmpeg integration (skips without ffmpeg; CI installs it). Tests use `examples/sample.fcpxml` as fixture data and inline XML fixtures. Tests create temp files and clean up after.
## FCPXML Gotchas
- FCPXML uses rational time everywhere: `"3600/2400s"` = 1.5 seconds
- `offset` in clips is the timeline position, `start` is the source media in-point
- Library clips (`<asset-clip>`) are different from timeline clips (`<clip>`)
- Markers are children of clips, not siblings
- The `<spine>` element is the primary storyline — clips go here
- `.fcpxmld` bundles are DIRECTORIES wrapping `Info.fcpxml` + sidecar data files — sidecars must be copied on save or object-tracking/Cinematic data is destroyed
- `code/examples/sample.fcpxml` is NOT DTD-conformant (pre-`media-rep` assets, sequence-level chapter markers) — don't use it as a DTD-validity fixture