🎥 Make videos programmatically with React
Add WebMCP tools to Remotion Studio
JonnyBurger0c193ac99548
diff --git a/packages/docs/docs/ai/TableOfContents.tsx b/packages/docs/docs/ai/TableOfContents.tsxindex a85ca9cd2d..c6e75d4223 100644--- a/packages/docs/docs/ai/TableOfContents.tsx+++ b/packages/docs/docs/ai/TableOfContents.tsx@@ -21,6 +21,10 @@ export const TableOfContents: React.FC = () => {<strong>{'Plugins'}</strong><div>Use Remotion with Codex, Claude Code, Cursor or Kimi Code</div></TOCItem>+ <TOCItem link="/docs/ai/webmcp">+ <strong>{'WebMCP'}</strong>+ <div>Inspect and control Remotion Studio with an AI agent</div>+ </TOCItem><TOCItem link="/docs/ai/chatbot"><strong>{'Chatbot'}</strong><div>Use the chatbot to get help with Remotion</div>diff --git a/packages/docs/docs/ai/webmcp.mdx b/packages/docs/docs/ai/webmcp.mdxnew file mode 100644index 0000000000..99e06708c4--- /dev/null+++ b/packages/docs/docs/ai/webmcp.mdx@@ -0,0 +1,70 @@+---+image: /generated/articles-docs-ai-webmcp.png+crumb: 'AI'+title: WebMCP+sidebar_label: WebMCP+---++# WebMCP<AvailableFrom v="4.0.518" />++<ExperimentalBadge>+ <p>WebMCP is an experimental browser API. Availability depends on the browser and AI agent.</p>+</ExperimentalBadge>++Remotion Studio exposes WebMCP tools that allow an AI agent to inspect and control the open composition.++Unlike the [deprecated Remotion MCP](/docs/ai/mcp), which provided documentation to agents, WebMCP gives an agent structured access to the current Studio tab.++## Requirements++Start the [Remotion Studio](/docs/studio) and open it in a browser with an AI agent that supports [WebMCP](https://webmachinelearning.github.io/webmcp/).++No Remotion configuration is required. Studio registers its tools when the browser provides `document.modelContext`. Browsers without WebMCP support continue to run Studio without registering tools.++## Available tools++| Tool | Input | Description |+| -------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |+| `get_compositions` | None | Returns mounted compositions as a nested tree of folders and compositions. |+| `select_composition` | `compositionName`: string | Opens a registered composition in Studio. |+| `get_composition` | None | Returns composition metadata and the current frame, or `null` fields for other canvas content. |+| `get_selection` | None | Returns the current frame, composition and source-code context for the selected item. |+| `get_guides` | None | Returns the horizontal and vertical guides drawn over the canvas. |+| `add_guide` | `orientation`: `horizontal` or `vertical`; `position`: number | Adds and shows a guide in the current composition. |+| `remove_guide` | `guideId`: string | Removes a guide from the current composition. |+| `seek_to_frame` | `frame`: a non-negative integer | Seeks the timeline. Values beyond the duration are clamped to the final frame. |+| `play` | None | Starts playback from the current frame. |+| `pause` | None | Pauses playback at the current frame. |+| `set_timeline_zoom` | `zoom`: a positive number | Sets the timeline zoom. Values outside the supported range are clamped. |+| `set_playback_rate` | `playbackRate`: `-4`, `-2`, `-1`, `-0.5`, `-0.25`, `0.25`, `0.5`, `1`, `1.5`, `2` or `4` | Sets the playback speed. Negative values play backwards. |+| `mute` | None | Mutes audio playback. |+| `unmute` | None | Unmutes audio playback. |++Tools that change playback require a composition to be open. `play` is unavailable for still compositions.++`get_selection` returns source-code context when exactly one sequence or property is selected. It returns `null` when there is no selection, multiple items are selected or a guide is selected.++## Example prompts++You can ask a browser agent:++- “What is currently selected in the Studio?”+- “List all mounted compositions and their folders.”+- “Open the `Shapes` composition.”+- “Set the timeline zoom to 2.5x.”+- “Seek to frame 90, set the playback rate to 0.5x and play.”+- “List the guides in the current composition.”+- “Add a vertical guide at 640 pixels.”+- “Mute the preview.”++The agent chooses and invokes the matching tools. Tool calls affect the open Studio tab immediately.++## Browser support++WebMCP is a draft web platform API. Refer to the [WebMCP specification](https://webmachinelearning.github.io/webmcp/) and [Chrome's WebMCP documentation](https://developer.chrome.com/docs/ai/agents) for current browser and agent support.++## See also++- [Prompting videos with coding agents](/docs/ai/coding-agents)+- [Remotion Agent Skills](/docs/ai/skills)+- [Remotion Studio](/docs/studio)diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex 99b5c30d52..2756bf20c3 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -1470,6 +1470,7 @@ const sidebars: SidebarsConfig = {'ai/kimi-code-plugin',],},+ 'ai/webmcp','ai/bolt','ai/chatbot','ai/generate',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex fafe845400..8ff2f95865 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -233,6 +233,15 @@ export const articles = [noAi: false,slug: 'ai/system-prompt',},+ {+ id: 'ai/webmcp',+ title: 'WebMCP',+ relativePath: 'docs/ai/webmcp.mdx',+ compId: 'articles-docs-ai-webmcp',+ crumb: 'AI',+ noAi: false,+ slug: 'ai/webmcp',+ },{id: 'angular',title: 'Using Remotion in Angular',diff --git a/packages/docs/static/generated/articles-docs-ai-webmcp.png b/packages/docs/static/generated/articles-docs-ai-webmcp.pngnew file mode 100644index 0000000000..c96a5400c2Binary files /dev/null and b/packages/docs/static/generated/articles-docs-ai-webmcp.png differdiff --git a/packages/example/e2e/studio.test.mts b/packages/example/e2e/studio.test.mtsindex 10c02f9a0c..a3d9f7db19 100644--- a/packages/example/e2e/studio.test.mts+++ b/packages/example/e2e/studio.test.mts@@ -1833,9 +1833,37 @@ test.describe('visual mode', () => {origin: STUDIO_URL,});await page.addInitScript(() => {+ window.localStorage.setItem('remotion.mute', 'false');+ window.localStorage.setItem('remotion.editorShowGuides', 'true');+ window.localStorage.setItem(+ 'remotion.guidesList',+ JSON.stringify([+ {+ id: 'webmcp-vertical-guide',+ orientation: 'vertical',+ position: 320,+ show: true,+ compositionId: 'AnimatedBarChart',+ },+ {+ id: 'webmcp-horizontal-guide',+ orientation: 'horizontal',+ position: 180,+ show: true,+ compositionId: 'AnimatedBarChart',+ },+ {+ id: 'other-composition-guide',+ orientation: 'vertical',+ position: 100,+ show: true,+ compositionId: 'Shapes',+ },+ ]),+ );type RegisteredTool = {readonly name: string;- readonly execute: () => Promise<unknown>;+ readonly execute: (input: Record<string, unknown>) => Promise<unknown>;};const tools = new Map<string, RegisteredTool>();Object.defineProperty(window, '__remotion_webmcp_tools', {@@ -2054,7 +2082,22 @@ test.describe('visual mode', () => {readonly __remotion_webmcp_tools: Map<string, unknown>;}).__remotion_webmcp_tools;- return tools.has('get_selection');+ return (+ tools.has('get_compositions') &&+ tools.has('select_composition') &&+ tools.has('get_composition') &&+ tools.has('get_selection') &&+ tools.has('get_guides') &&+ tools.has('add_guide') &&+ tools.has('remove_guide') &&+ tools.has('play') &&+ tools.has('pause') &&+ tools.has('mute') &&+ tools.has('unmute') &&+ tools.has('set_timeline_zoom') &&+ tools.has('set_playback_rate') &&+ tools.has('seek_to_frame')+ );}),).toBe(true);@@ -2079,6 +2122,456 @@ test.describe('visual mode', () => {currentSelection: contextForAgents,currentComposition: 'AnimatedBarChart',});+ const webMcpComposition = await page.evaluate(async () => {+ const tools = (+ window as typeof window & {+ readonly __remotion_webmcp_tools: Map<+ string,+ {readonly execute: () => Promise<unknown>}+ >;+ }+ ).__remotion_webmcp_tools;+ const tool = tools.get('get_composition');+ if (!tool) {+ throw new Error('get_composition was not registered');+ }++ return tool.execute();+ });+ expect(webMcpComposition).toEqual({+ compositionName: 'AnimatedBarChart',+ stack: expect.any(String),+ durationInFrames: 180,+ height: 720,+ width: 1280,+ fps: 30,+ currentFrame: 3,+ });+ const webMcpCompositions = await page.evaluate(async () => {+ const tools = (+ window as typeof window & {+ readonly __remotion_webmcp_tools: Map<+ string,+ {readonly execute: () => Promise<unknown>}+ >;+ }+ ).__remotion_webmcp_tools;+ const tool = tools.get('get_compositions');+ if (!tool) {+ throw new Error('get_compositions was not registered');+ }++ return tool.execute();+ });+ expect(webMcpCompositions).toEqual({+ compositions: expect.arrayContaining([+ {+ type: 'folder',+ folderName: 'visual-controls',+ children: [+ {+ type: 'composition',+ compositionName: 'visual-controls',+ },+ {+ type: 'composition',+ compositionName: 'effect-keyframe-e2e',+ },+ ],+ },+ {+ type: 'composition',+ compositionName: 'AnimatedBarChart',+ },+ ]),+ });+ const webMcpSelectCompositionResult = await page.evaluate(async () => {+ const tools = (+ window as typeof window & {+ readonly __remotion_webmcp_tools: Map<+ string,+ {+ readonly execute: (+ input: Record<string, unknown>,+ ) => Promise<unknown>;+ }+ >;+ }+ ).__remotion_webmcp_tools;+ const tool = tools.get('select_composition');+ if (!tool) {+ throw new Error('select_composition was not registered');+ }++ return tool.execute({compositionName: 'package-absolute-fill'});+ });+ expect(webMcpSelectCompositionResult).toEqual({+ currentComposition: 'package-absolute-fill',+ });+ await expect+ .poll(() => new URL(page.url()).pathname)+ .toBe('/package-absolute-fill');+ await expect+ .poll(() =>+ page.evaluate(async () => {+ const tools = (+ window as typeof window & {+ readonly __remotion_webmcp_tools: Map<+ string,+ {readonly execute: () => Promise<unknown>}+ >;+ }+ ).__remotion_webmcp_tools;+ const tool = tools.get('get_composition');+ const result = (await tool?.execute()) as {+ readonly compositionName?: string;+ };+ return result?.compositionName ?? null;+ }),+ )+ .toBe('package-absolute-fill');+ await page.evaluate(async () => {+ const tools = (+ window as typeof window & {+ readonly __remotion_webmcp_tools: Map<+ string,+ {+ readonly execute: (+ input: Record<string, unknown>,+ ) => Promise<unknown>;+ }+ >;+ }+ ).__remotion_webmcp_tools;+ const tool = tools.get('select_composition');+ if (!tool) {+ throw new Error('select_composition was not registered');+ }++ await tool.execute({compositionName: 'AnimatedBarChart'});+ });+ await expect+ .poll(() => new URL(page.url()).pathname)+ .toBe('/AnimatedBarChart');+ const webMcpGuides = await page.evaluate(async () => {+ const tools = (+ window as typeof window & {+ readonly __remotion_webmcp_tools: Map<+ string,+ {+ readonly execute: (+ input: Record<string, unknown>,+ ) => Promise<unknown>;+ }+ >;+ }+ ).__remotion_webmcp_tools;+ const tool = tools.get('get_guides');+ if (!tool) {+ throw new Error('get_guides was not registered');+ }++ return tool.execute({});+ });+ expect(webMcpGuides).toEqual({+ currentComposition: 'AnimatedBarChart',+ guidesVisible: true,+ guides: [+ {+ id: 'webmcp-vertical-guide',+ orientation: 'vertical',+ position: 320,+ visible: true,+ },+ {+ id: 'webmcp-horizontal-guide',+ orientation: 'horizontal',+ position: 180,+ visible: true,+ },+ ],+ });+ await expect(page.locator('.__remotion_editor_guide')).toHaveCount(2);+ const webMcpAddGuideResult = await page.evaluate(async () => {+ const tools = (+ window as typeof window & {+ readonly __remotion_webmcp_tools: Map<+ string,+ {+ readonly execute: (+ input: Record<string, unknown>,+ ) => Promise<unknown>;+ }+ >;+ }+ ).__remotion_webmcp_tools;+ const tool = tools.get('add_guide');+ if (!tool) {+ throw new Error('add_guide was not registered');+ }++ return tool.execute({orientation: 'vertical', position: 640});+ });+ expect(webMcpAddGuideResult).toEqual({+ currentComposition: 'AnimatedBarChart',+ guide: {+ id: expect.any(String),+ orientation: 'vertical',+ position: 640,+ visible: true,+ },+ });+ const addedGuideId = (+ webMcpAddGuideResult as {readonly guide: {readonly id: string}}+ ).guide.id;+ await expect+ .poll(() =>+ page.evaluate(+ ({guideId}) => {+ const guides = JSON.parse(+ localStorage.getItem('remotion.guidesList') ?? '[]',+ ) as {readonly id: string}[];+ return guides.some((guide) => guide.id === guideId);+ },+ {guideId: addedGuideId},+ ),+ )+ .toBe(true);+ await expect(page.locator('.__remotion_editor_guide')).toHaveCount(3);+ const webMcpRemoveGuideResult = await page.evaluate(+ async ({guideId}) => {+ const tools = (+ window as typeof window & {+ readonly __remotion_webmcp_tools: Map<+ string,+ {+ readonly execute: (+ input: Record<string, unknown>,+ ) => Promise<unknown>;+ }+ >;+ }+ ).__remotion_webmcp_tools;+ const tool = tools.get('remove_guide');+ if (!tool) {+ throw new Error('remove_guide was not registered');+ }++ return tool.execute({guideId});+ },+ {guideId: addedGuideId},+ );+ expect(webMcpRemoveGuideResult).toEqual({+ currentComposition: 'AnimatedBarChart',+ guideId: addedGuideId,+ removed: true,+ });+ await expect+ .poll(() =>+ page.evaluate(+ ({guideId}) => {+ const guides = JSON.parse(+ localStorage.getItem('remotion.guidesList') ?? '[]',+ ) as {readonly id: string}[];+ return guides.some((guide) => guide.id === guideId);+ },+ {guideId: addedGuideId},+ ),+ )+ .toBe(false);+ await expect(page.locator('.__remotion_editor_guide')).toHaveCount(2);+ const webMcpPlaybackRateResult = await page.evaluate(async () => {+ const tools = (+ window as typeof window & {+ readonly __remotion_webmcp_tools: Map<+ string,+ {+ readonly execute: (+ input: Record<string, unknown>,+ ) => Promise<unknown>;+ }+ >;+ }+ ).__remotion_webmcp_tools;+ const tool = tools.get('set_playback_rate');+ if (!tool) {+ throw new Error('set_playback_rate was not registered');+ }++ return tool.execute({playbackRate: 1.5});+ });+ expect(webMcpPlaybackRateResult).toEqual({+ currentComposition: 'AnimatedBarChart',+ playbackRate: 1.5,+ });+ await expect(+ page.getByRole('button', {+ name: 'Change the playback rate',+ exact: true,+ }),+ ).toContainText('1.5x');+ const webMcpTimelineZoomResult = await page.evaluate(async () => {+ const tools = (+ window as typeof window & {+ readonly __remotion_webmcp_tools: Map<+ string,+ {+ readonly execute: (+ input: Record<string, unknown>,+ ) => Promise<unknown>;+ }+ >;+ }+ ).__remotion_webmcp_tools;+ const tool = tools.get('set_timeline_zoom');+ if (!tool) {+ throw new Error('set_timeline_zoom was not registered');+ }++ return tool.execute({zoom: 2.5});+ });+ expect(webMcpTimelineZoomResult).toEqual({+ currentComposition: 'AnimatedBarChart',+ timelineZoom: 2.5,+ });+ await expect(+ page.getByTitle('Timeline zoom (2.5x)', {exact: true}),+ ).toBeVisible();+ const webMcpMuteResult = await page.evaluate(async () => {+ const tools = (+ window as typeof window & {+ readonly __remotion_webmcp_tools: Map<+ string,+ {+ readonly execute: (+ input: Record<string, unknown>,+ ) => Promise<unknown>;+ }+ >;+ }+ ).__remotion_webmcp_tools;+ const tool = tools.get('mute');+ if (!tool) {+ throw new Error('mute was not registered');+ }++ return tool.execute({});+ });+ expect(webMcpMuteResult).toEqual({+ currentComposition: 'AnimatedBarChart',+ muted: true,+ });+ await expect(+ page.getByRole('button', {name: 'Unmute video', exact: true}),+ ).toBeVisible();+ const webMcpUnmuteResult = await page.evaluate(async () => {+ const tools = (+ window as typeof window & {+ readonly __remotion_webmcp_tools: Map<+ string,+ {+ readonly execute: (+ input: Record<string, unknown>,+ ) => Promise<unknown>;+ }+ >;+ }+ ).__remotion_webmcp_tools;+ const tool = tools.get('unmute');+ if (!tool) {+ throw new Error('unmute was not registered');+ }++ return tool.execute({});+ });+ expect(webMcpUnmuteResult).toEqual({+ currentComposition: 'AnimatedBarChart',+ muted: false,+ });+ await expect(+ page.getByRole('button', {name: 'Mute video', exact: true}),+ ).toBeVisible();+ const webMcpPlayResult = await page.evaluate(async () => {+ const tools = (+ window as typeof window & {+ readonly __remotion_webmcp_tools: Map<+ string,+ {+ readonly execute: (+ input: Record<string, unknown>,+ ) => Promise<unknown>;+ }+ >;+ }+ ).__remotion_webmcp_tools;+ const tool = tools.get('play');+ if (!tool) {+ throw new Error('play was not registered');+ }++ return tool.execute({});+ });+ expect(webMcpPlayResult).toEqual({+ currentComposition: 'AnimatedBarChart',+ playing: true,+ });+ await expect(+ page.getByRole('button', {name: 'Pause', exact: true}),+ ).toBeVisible();+ const webMcpPauseResult = await page.evaluate(async () => {+ const tools = (+ window as typeof window & {+ readonly __remotion_webmcp_tools: Map<+ string,+ {+ readonly execute: (+ input: Record<string, unknown>,+ ) => Promise<unknown>;+ }+ >;+ }+ ).__remotion_webmcp_tools;+ const tool = tools.get('pause');+ if (!tool) {+ throw new Error('pause was not registered');+ }++ return tool.execute({});+ });+ expect(webMcpPauseResult).toEqual({+ currentComposition: 'AnimatedBarChart',+ playing: false,+ });+ await expect(+ page.getByRole('button', {name: 'Play', exact: true}),+ ).toBeVisible();+ const webMcpSeekResult = await page.evaluate(async () => {+ const tools = (+ window as typeof window & {+ readonly __remotion_webmcp_tools: Map<+ string,+ {+ readonly execute: (+ input: Record<string, unknown>,+ ) => Promise<unknown>;+ }+ >;+ }+ ).__remotion_webmcp_tools;+ const tool = tools.get('seek_to_frame');+ if (!tool) {+ throw new Error('seek_to_frame was not registered');+ }++ return tool.execute({frame: 200});+ });+ expect(webMcpSeekResult).toEqual({+ currentFrame: 179,+ currentComposition: 'AnimatedBarChart',+ });+ await expect(+ page.getByRole('button', {name: '179', exact: true}),+ ).toBeVisible();fs.writeFileSync(configFile,@@ -2167,6 +2660,32 @@ test.describe('visual mode', () => {await expect(settings.getByText('Default codec', {exact: true}),).toHaveCount(0);++ await page.goto(`${STUDIO_URL}/assets/test.gif`);+ await expect+ .poll(() =>+ page.evaluate(async () => {+ const tools = (+ window as typeof window & {+ readonly __remotion_webmcp_tools: Map<+ string,+ {readonly execute: () => Promise<unknown>}+ >;+ }+ ).__remotion_webmcp_tools;+ const tool = tools.get('get_composition');+ return tool?.execute() ?? null;+ }),+ )+ .toEqual({+ compositionName: null,+ stack: null,+ durationInFrames: null,+ height: null,+ width: null,+ fps: null,+ currentFrame: null,+ });} finally {fs.writeFileSync(configFile, configBeforeTest);}diff --git a/packages/studio/src/components/PlaybackRateSelector.tsx b/packages/studio/src/components/PlaybackRateSelector.tsxindex 7cefb7ec1c..e30923939e 100644--- a/packages/studio/src/components/PlaybackRateSelector.tsx+++ b/packages/studio/src/components/PlaybackRateSelector.tsx@@ -4,14 +4,10 @@ import {WHITE_ALPHA_80} from '../helpers/colors';import {useIsStill} from '../helpers/is-current-selected-still';import {Checkmark} from '../icons/Checkmark';import {PlaybackRateIcon} from '../icons/playback-rate';-import {persistPlaybackRate} from '../state/playbackrate';+import {commonPlaybackRates, persistPlaybackRate} from '../state/playbackrate';import type {ComboboxValue} from './NewComposition/ComboBox';import {TimelineCombobox} from './TimelineCombobox';-const commonPlaybackRates: number[] = [- -4, -2, -1, -0.5, -0.25, 0.25, 0.5, 1, 1.5, 2, 4,-];-const getPlaybackRateLabel = (playbackRate: number) => {return `${playbackRate}x`;};diff --git a/packages/studio/src/components/WebMcp.tsx b/packages/studio/src/components/WebMcp.tsxindex f7168301d9..81a23a77aa 100644--- a/packages/studio/src/components/WebMcp.tsx+++ b/packages/studio/src/components/WebMcp.tsx@@ -1,8 +1,22 @@import {useContext, useEffect, useMemo, useRef, type FC} from 'react';import {Internals} from 'remotion';+import {pause} from '../api/pause';+import {play} from '../api/play';+import {seek} from '../api/seek';+import {createFolderTree} from '../helpers/create-folder-tree';import {formatContextForAgents} from '../helpers/format-file-location';+import {clampTimelineZoom} from '../helpers/get-timeline-max-zoom';+import {+ EditorShowGuidesContext,+ persistGuidesList,+ type Guide,+} from '../state/editor-guides';+import {persistMuteOption} from '../state/mute';+import {commonPlaybackRates, persistPlaybackRate} from '../state/playbackrate';+import {TimelineZoomCtx} from '../state/timeline-zoom';+import {useSelectComposition} from './InitialCompositionLoader';import {findTrackForNodePathInfo} from './Timeline/find-track-for-node-path-info';-import {getCurrentFrame} from './Timeline/imperative-state';+import {getCurrentDuration, getCurrentFrame} from './Timeline/imperative-state';import {parseKeyframeFieldFromNodePath} from './Timeline/parse-keyframe-field-from-node-path';import {useTimelineSelection} from './Timeline/TimelineSelection';import {useResolveStackAndReactToChange} from './Timeline/use-resolved-stack-react-to-change';@@ -13,7 +27,7 @@ type WebMcpTool = {readonly description: string;readonly inputSchema: Record<string, unknown>;readonly annotations: {readonly readOnlyHint: boolean};- readonly execute: () => Promise<unknown>;+ readonly execute: (input: Record<string, unknown>) => Promise<unknown>;};type WebMcpModelContext = {@@ -23,11 +37,48 @@ type WebMcpModelContext = {) => Promise<void>;};+type WebMcpCompositionTreeItem =+ | {+ readonly type: 'composition';+ readonly compositionName: string;+ }+ | {+ readonly type: 'folder';+ readonly folderName: string;+ readonly children: WebMcpCompositionTreeItem[];+ };++const serializeCompositionTree = (+ items: ReturnType<typeof createFolderTree>,+): WebMcpCompositionTreeItem[] => {+ return items.map((item): WebMcpCompositionTreeItem => {+ if (item.type === 'composition') {+ return {+ type: 'composition',+ compositionName: item.composition.id,+ };+ }++ return {+ type: 'folder',+ folderName: item.folderName,+ children: serializeCompositionTree(item.items),+ };+ });+};+const getNoStack = () => null;export const WebMcp: FC = () => {- const {selectedItems} = useTimelineSelection();- const {canvasContent} = useContext(Internals.CompositionManager);+ const {clearSelection, selectedItems} = useTimelineSelection();+ const {canvasContent, compositions, currentCompositionMetadata, folders} =+ useContext(Internals.CompositionManager);+ const {setPlaybackRate} = Internals.usePlaybackRate();+ const {setPlayerMuted} = useContext(Internals.SetMediaVolumeContext);+ const {setZoom: setTimelineZoom} = useContext(TimelineZoomCtx);+ const selectComposition = useSelectComposition();+ const {editorShowGuides, guidesList, setEditorShowGuides, setGuidesList} =+ useContext(EditorShowGuidesContext);const {sequences} = useContext(Internals.SequenceManager);const {overrideIdToNodePathMappings} = useContext(Internals.OverrideIdsToNodePathsGettersContext,@@ -108,10 +159,34 @@ export const WebMcp: FC = () => {}, [currentResolvedLocation, selectedItem, selectedItems.length, track]);const currentSelectionRef = useRef(currentSelection);currentSelectionRef.current = currentSelection;- const currentComposition =- canvasContent?.type === 'composition' ? canvasContent.compositionId : null;+ const selectedItemsRef = useRef(selectedItems);+ selectedItemsRef.current = selectedItems;+ const currentCompositionDefinition = useMemo(() => {+ if (canvasContent?.type !== 'composition') {+ return null;+ }++ return (+ compositions.find(+ (composition) => composition.id === canvasContent.compositionId,+ ) ?? null+ );+ }, [canvasContent, compositions]);+ const currentComposition = currentCompositionDefinition?.id ?? null;const currentCompositionRef = useRef(currentComposition);currentCompositionRef.current = currentComposition;+ const currentCompositionDefinitionRef = useRef(currentCompositionDefinition);+ currentCompositionDefinitionRef.current = currentCompositionDefinition;+ const compositionsRef = useRef(compositions);+ compositionsRef.current = compositions;+ const foldersRef = useRef(folders);+ foldersRef.current = folders;+ const currentCompositionMetadataRef = useRef(currentCompositionMetadata);+ currentCompositionMetadataRef.current = currentCompositionMetadata;+ const guidesListRef = useRef(guidesList);+ guidesListRef.current = guidesList;+ const editorShowGuidesRef = useRef(editorShowGuides);+ editorShowGuidesRef.current = editorShowGuides;useEffect(() => {const {modelContext} = document as Document & {@@ -122,8 +197,112 @@ export const WebMcp: FC = () => {}const controller = new AbortController();- modelContext- .registerTool(+ Promise.all([+ modelContext.registerTool(+ {+ name: 'get_compositions',+ title: 'Get Studio compositions',+ description:+ 'Read the mounted Remotion Studio compositions as the nested folder tree shown in the sidebar.',+ inputSchema: {+ type: 'object',+ properties: {},+ additionalProperties: false,+ },+ annotations: {readOnlyHint: true},+ execute: () => {+ const tree = createFolderTree(+ compositionsRef.current,+ foldersRef.current,+ {},+ );+ return Promise.resolve({+ compositions: serializeCompositionTree(tree),+ });+ },+ },+ {signal: controller.signal},+ ),+ modelContext.registerTool(+ {+ name: 'select_composition',+ title: 'Select Studio composition',+ description:+ 'Open a registered composition in Remotion Studio by name.',+ inputSchema: {+ type: 'object',+ properties: {+ compositionName: {+ type: 'string',+ description: 'The name of the composition to open.',+ },+ },+ required: ['compositionName'],+ additionalProperties: false,+ },+ annotations: {readOnlyHint: false},+ execute: ({compositionName}) => {+ if (typeof compositionName !== 'string') {+ throw new Error('compositionName must be a string.');+ }++ const composition = compositionsRef.current.find(+ (candidate) => candidate.id === compositionName,+ );+ if (!composition) {+ throw new Error(`Composition ${compositionName} not found.`);+ }++ selectComposition(composition, true);+ return Promise.resolve({currentComposition: composition.id});+ },+ },+ {signal: controller.signal},+ ),+ modelContext.registerTool(+ {+ name: 'get_composition',+ title: 'Get Studio composition',+ description:+ 'Read the name, source stack, duration, dimensions, frame rate, and current frame of the composition open in Remotion Studio. All fields are null when the canvas is not showing a composition.',+ inputSchema: {+ type: 'object',+ properties: {},+ additionalProperties: false,+ },+ annotations: {readOnlyHint: true},+ execute: () => {+ const composition = currentCompositionDefinitionRef.current;+ if (composition === null) {+ return Promise.resolve({+ compositionName: null,+ stack: null,+ durationInFrames: null,+ height: null,+ width: null,+ fps: null,+ currentFrame: null,+ });+ }++ const metadata = currentCompositionMetadataRef.current;+ return Promise.resolve({+ compositionName: composition.id,+ stack: composition.stack,+ durationInFrames:+ metadata?.durationInFrames ??+ composition.durationInFrames ??+ null,+ height: metadata?.height ?? composition.height ?? null,+ width: metadata?.width ?? composition.width ?? null,+ fps: metadata?.fps ?? composition.fps ?? null,+ currentFrame: getCurrentFrame(),+ });+ },+ },+ {signal: controller.signal},+ ),+ modelContext.registerTool({name: 'get_selection',title: 'Get Studio selection',@@ -143,13 +322,455 @@ export const WebMcp: FC = () => {}),},{signal: controller.signal},- )- .catch(() => undefined);+ ),+ modelContext.registerTool(+ {+ name: 'get_guides',+ title: 'Get Studio guides',+ description:+ 'Read the guides for the current Remotion Studio composition. Vertical guide positions are x-coordinates from the left edge and horizontal guide positions are y-coordinates from the top edge, in composition pixels.',+ inputSchema: {+ type: 'object',+ properties: {},+ additionalProperties: false,+ },+ annotations: {readOnlyHint: true},+ execute: () => {+ const compositionId = currentCompositionRef.current;+ const guidesAreVisible = editorShowGuidesRef.current;++ return Promise.resolve({+ currentComposition: compositionId,+ guidesVisible: guidesAreVisible,+ guides:+ compositionId === null+ ? []+ : guidesListRef.current+ .filter((guide) => guide.compositionId === compositionId)+ .map((guide) => ({+ id: guide.id,+ orientation: guide.orientation,+ position: guide.position,+ visible: guidesAreVisible && guide.show,+ })),+ });+ },+ },+ {signal: controller.signal},+ ),+ modelContext.registerTool(+ {+ name: 'add_guide',+ title: 'Add Studio guide',+ description:+ 'Add a guide to the current Remotion Studio composition. A vertical guide position is an x-coordinate from the left edge and a horizontal guide position is a y-coordinate from the top edge, in composition pixels.',+ inputSchema: {+ type: 'object',+ properties: {+ orientation: {+ type: 'string',+ enum: ['horizontal', 'vertical'],+ description: 'The orientation of the guide.',+ },+ position: {+ type: 'number',+ description:+ 'The guide position in composition pixels. Vertical guides use an x-coordinate and horizontal guides use a y-coordinate.',+ },+ },+ required: ['orientation', 'position'],+ additionalProperties: false,+ },+ annotations: {readOnlyHint: false},+ execute: ({orientation, position}) => {+ if (orientation !== 'horizontal' && orientation !== 'vertical') {+ throw new Error(+ 'orientation must be either "horizontal" or "vertical".',+ );+ }++ if (typeof position !== 'number' || !Number.isFinite(position)) {+ throw new Error('position must be a finite number.');+ }++ const compositionId = currentCompositionRef.current;+ if (compositionId === null) {+ throw new Error('No composition is currently selected.');+ }++ const guide: Guide = {+ id: crypto.randomUUID(),+ orientation,+ position,+ show: true,+ compositionId,+ };+ const nextGuides = [...guidesListRef.current, guide];+ guidesListRef.current = nextGuides;+ setGuidesList(() => nextGuides);+ persistGuidesList(nextGuides);+ editorShowGuidesRef.current = true;+ setEditorShowGuides(() => true);++ return Promise.resolve({+ currentComposition: compositionId,+ guide: {+ id: guide.id,+ orientation: guide.orientation,+ position: guide.position,+ visible: true,+ },+ });+ },+ },+ {signal: controller.signal},+ ),+ modelContext.registerTool(+ {+ name: 'remove_guide',+ title: 'Remove Studio guide',+ description:+ 'Remove a guide from the current Remotion Studio composition by its guide ID.',+ inputSchema: {+ type: 'object',+ properties: {+ guideId: {+ type: 'string',+ minLength: 1,+ description:+ 'The guide ID returned by get_guides or add_guide.',+ },+ },+ required: ['guideId'],+ additionalProperties: false,+ },+ annotations: {readOnlyHint: false},+ execute: ({guideId}) => {+ if (typeof guideId !== 'string' || guideId.length === 0) {+ throw new Error('guideId must be a non-empty string.');+ }++ const compositionId = currentCompositionRef.current;+ if (compositionId === null) {+ throw new Error('No composition is currently selected.');+ }++ const guideExists = guidesListRef.current.some(+ (guide) =>+ guide.id === guideId && guide.compositionId === compositionId,+ );+ if (!guideExists) {+ throw new Error(+ `Guide ${guideId} not found in the current composition.`,+ );+ }++ const nextGuides = guidesListRef.current.filter(+ (guide) =>+ guide.id !== guideId || guide.compositionId !== compositionId,+ );+ guidesListRef.current = nextGuides;+ setGuidesList(() => nextGuides);+ persistGuidesList(nextGuides);++ const removedGuideWasSelected = selectedItemsRef.current.some(+ (item) => item.type === 'guide' && item.guideId === guideId,+ );+ if (removedGuideWasSelected) {+ clearSelection();+ }++ return Promise.resolve({+ currentComposition: compositionId,+ guideId,+ removed: true,+ });+ },+ },+ {signal: controller.signal},+ ),+ modelContext.registerTool(+ {+ name: 'play',+ title: 'Play Studio composition',+ description:+ 'Start playing the current Remotion Studio composition from the current frame.',+ inputSchema: {+ type: 'object',+ properties: {},+ additionalProperties: false,+ },+ annotations: {readOnlyHint: false},+ execute: () => {+ const compositionId = currentCompositionRef.current;+ if (compositionId === null) {+ throw new Error('No composition is currently selected.');+ }++ if (getCurrentDuration() <= 1) {+ throw new Error(+ 'The current composition is a still and cannot play.',+ );+ }++ if (Internals.timeValueRef.current === null) {+ throw new Error('Studio playback controls are not ready.');+ }++ play();+ return Promise.resolve({+ currentComposition: compositionId,+ playing: true,+ });+ },+ },+ {signal: controller.signal},+ ),+ modelContext.registerTool(+ {+ name: 'pause',+ title: 'Pause Studio composition',+ description:+ 'Pause the current Remotion Studio composition at the current frame.',+ inputSchema: {+ type: 'object',+ properties: {},+ additionalProperties: false,+ },+ annotations: {readOnlyHint: false},+ execute: () => {+ const compositionId = currentCompositionRef.current;+ if (compositionId === null) {+ throw new Error('No composition is currently selected.');+ }++ if (Internals.timeValueRef.current === null) {+ throw new Error('Studio playback controls are not ready.');+ }++ pause();+ return Promise.resolve({+ currentComposition: compositionId,+ playing: false,+ });+ },+ },+ {signal: controller.signal},+ ),+ modelContext.registerTool(+ {+ name: 'mute',+ title: 'Mute Studio composition',+ description:+ 'Mute audio playback for the current Remotion Studio composition.',+ inputSchema: {+ type: 'object',+ properties: {},+ additionalProperties: false,+ },+ annotations: {readOnlyHint: false},+ execute: () => {+ const compositionId = currentCompositionRef.current;+ if (compositionId === null) {+ throw new Error('No composition is currently selected.');+ }++ setPlayerMuted(true);+ persistMuteOption(true);+ return Promise.resolve({+ currentComposition: compositionId,+ muted: true,+ });+ },+ },+ {signal: controller.signal},+ ),+ modelContext.registerTool(+ {+ name: 'unmute',+ title: 'Unmute Studio composition',+ description:+ 'Unmute audio playback for the current Remotion Studio composition.',+ inputSchema: {+ type: 'object',+ properties: {},+ additionalProperties: false,+ },+ annotations: {readOnlyHint: false},+ execute: () => {+ const compositionId = currentCompositionRef.current;+ if (compositionId === null) {+ throw new Error('No composition is currently selected.');+ }++ setPlayerMuted(false);+ persistMuteOption(false);+ return Promise.resolve({+ currentComposition: compositionId,+ muted: false,+ });+ },+ },+ {signal: controller.signal},+ ),+ modelContext.registerTool(+ {+ name: 'set_timeline_zoom',+ title: 'Set Studio timeline zoom',+ description:+ 'Set the timeline zoom factor for the current Remotion Studio composition. The zoom is clamped to the range supported by the composition duration.',+ inputSchema: {+ type: 'object',+ properties: {+ zoom: {+ type: 'number',+ exclusiveMinimum: 0,+ description: 'The requested timeline zoom factor.',+ },+ },+ required: ['zoom'],+ additionalProperties: false,+ },+ annotations: {readOnlyHint: false},+ execute: ({zoom}) => {+ if (+ typeof zoom !== 'number' ||+ !Number.isFinite(zoom) ||+ zoom <= 0+ ) {+ throw new Error('zoom must be a positive finite number.');+ }++ const compositionId = currentCompositionRef.current;+ if (compositionId === null) {+ throw new Error('No composition is currently selected.');+ }++ const durationInFrames = getCurrentDuration();+ if (durationInFrames <= 1) {+ throw new Error(+ 'The current composition is a still and has no timeline zoom.',+ );+ }++ const timelineZoom = clampTimelineZoom({+ zoom,+ durationInFrames,+ });+ setTimelineZoom(compositionId, () => timelineZoom, {+ anchorFrame: null,+ anchorContentX: null,+ });++ return Promise.resolve({+ currentComposition: compositionId,+ timelineZoom,+ });+ },+ },+ {signal: controller.signal},+ ),+ modelContext.registerTool(+ {+ name: 'set_playback_rate',+ title: 'Set Studio playback rate',+ description:+ 'Set the playback rate for the current Remotion Studio composition. Negative values play the composition backwards.',+ inputSchema: {+ type: 'object',+ properties: {+ playbackRate: {+ type: 'number',+ enum: commonPlaybackRates,+ description:+ 'The playback multiplier. Negative values play backwards.',+ },+ },+ required: ['playbackRate'],+ additionalProperties: false,+ },+ annotations: {readOnlyHint: false},+ execute: ({playbackRate}) => {+ if (+ typeof playbackRate !== 'number' ||+ !commonPlaybackRates.includes(playbackRate)+ ) {+ throw new Error(+ `playbackRate must be one of: ${commonPlaybackRates.join(', ')}.`,+ );+ }++ const compositionId = currentCompositionRef.current;+ if (compositionId === null) {+ throw new Error('No composition is currently selected.');+ }++ setPlaybackRate(() => playbackRate);+ persistPlaybackRate(playbackRate);+ return Promise.resolve({+ currentComposition: compositionId,+ playbackRate,+ });+ },+ },+ {signal: controller.signal},+ ),+ modelContext.registerTool(+ {+ name: 'seek_to_frame',+ title: 'Seek Studio timeline',+ description:+ 'Seek the current Remotion Studio composition to a frame. Frames past the end of the composition are clamped to the final frame.',+ inputSchema: {+ type: 'object',+ properties: {+ frame: {+ type: 'integer',+ minimum: 0,+ description: 'The zero-based frame to seek to.',+ },+ },+ required: ['frame'],+ additionalProperties: false,+ },+ annotations: {readOnlyHint: false},+ execute: ({frame}) => {+ if (typeof frame !== 'number' || !Number.isInteger(frame)) {+ throw new Error('frame must be an integer.');+ }++ const compositionId = currentCompositionRef.current;+ if (compositionId === null) {+ throw new Error('No composition is currently selected.');+ }++ const currentFrame = Math.min(+ Math.max(0, frame),+ getCurrentDuration() - 1,+ );+ seek(currentFrame);+ return Promise.resolve({+ currentFrame,+ currentComposition: compositionId,+ });+ },+ },+ {signal: controller.signal},+ ),+ ]).catch(() => undefined);return () => {controller.abort();};- }, []);+ }, [+ clearSelection,+ selectComposition,+ setEditorShowGuides,+ setGuidesList,+ setPlaybackRate,+ setPlayerMuted,+ setTimelineZoom,+ ]);return null;};diff --git a/packages/studio/src/state/playbackrate.ts b/packages/studio/src/state/playbackrate.tsindex fb97819cca..8fd0a296e1 100644--- a/packages/studio/src/state/playbackrate.ts+++ b/packages/studio/src/state/playbackrate.ts@@ -1,5 +1,9 @@const key = 'remotion.playbackrate';+export const commonPlaybackRates: number[] = [+ -4, -2, -1, -0.5, -0.25, 0.25, 0.5, 1, 1.5, 2, 4,+];+export const persistPlaybackRate = (option: number) => {localStorage.setItem(key, String(option));};