Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Add shutDownStudio() and WebMCP lifecycle tools

Jonny Burgera4697435568a
diff --git a/packages/docs/docs/ai/webmcp.mdx b/packages/docs/docs/ai/webmcp.mdx
index 7a56afa5ce..7696c65b06 100644
--- a/packages/docs/docs/ai/webmcp.mdx
+++ b/packages/docs/docs/ai/webmcp.mdx
@@ -23,6 +23,7 @@ Agents can:
- Play, pause and seek
- Set timeline zoom, playback rate, and mute state
- See, add and remove guides
+- Restart or shut down the Studio server
## Requirements
@@ -42,6 +43,34 @@ The shape of inputs and outputs is not currently stable.
Tools that modify the timeline, playback or guides require a composition to be open.
+### `restart_studio`<AvailableFrom v="4.0.521" />
+
+Restarts the Studio server using [`restartStudio()`](/docs/studio/restart-studio). Requires a writable Studio with a running server. No composition needs to be open. The browser temporarily disconnects and reconnects when Studio is ready.
+
+```ts title="Input"
+{}
+```
+
+```ts title="Output"
+{}
+```
+
+The output acknowledges the restart request; it does not wait for the restarted server to be ready.
+
+### `shut_down_studio`<AvailableFrom v="4.0.521" />
+
+Gracefully shuts down the Studio server using [`shutDownStudio()`](/docs/studio/shut-down-studio). Requires a writable Studio with a running server. No composition needs to be open. Start Studio again from the terminal to reconnect.
+
+```ts title="Input"
+{}
+```
+
+```ts title="Output"
+{}
+```
+
+The output acknowledges the shutdown request; the connection closes as Studio shuts down.
+
### `get_current_error`<AvailableFrom v="4.0.520" />
Returns the error currently shown in the Studio error overlay. It waits for source map symbolication and includes symbolicated stack frames when available, while preserving the raw stack as a fallback. Returns `null` when the error overlay is not visible.
diff --git a/packages/docs/docs/studio/restart-studio.mdx b/packages/docs/docs/studio/restart-studio.mdx
index 428ff9b9fb..87566f7734 100644
--- a/packages/docs/docs/studio/restart-studio.mdx
+++ b/packages/docs/docs/studio/restart-studio.mdx
@@ -37,6 +37,12 @@ In order to use this function:
Otherwise, the function will throw.
+## Return value
+
+Returns a promise that resolves to an empty object when the server acknowledges the restart request. The browser temporarily disconnects while Studio restarts.
+
## See also
+- [`shutDownStudio()`](/docs/studio/shut-down-studio)
+
- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/studio/src/api/restart-studio.ts)
diff --git a/packages/docs/docs/studio/shut-down-studio.mdx b/packages/docs/docs/studio/shut-down-studio.mdx
new file mode 100644
index 0000000000..c16607d28c
--- /dev/null
+++ b/packages/docs/docs/studio/shut-down-studio.mdx
@@ -0,0 +1,49 @@
+---
+image: /generated/articles-docs-studio-shut-down-studio.png
+title: shutDownStudio()
+crumb: "@remotion/studio"
+---
+
+# shutDownStudio()<AvailableFrom v="4.0.521" />
+
+Gracefully shuts down the [Remotion Studio](/docs/studio) server. Start Studio again from your terminal to reconnect.
+
+```tsx twoslash title="ShutDownButton.tsx"
+import { shutDownStudio } from "@remotion/studio";
+
+export const ShutDownButton: React.FC = () => {
+ return (
+ <button
+ type="button"
+ onClick={async () => {
+ try {
+ await shutDownStudio();
+ console.log("Studio is shutting down");
+ } catch (err) {
+ console.error(err);
+ }
+ }}
+ >
+ Shut down Studio
+ </button>
+ );
+};
+```
+
+## Requirements
+
+This function is only available in a writable Studio with a running server. It throws outside Studio, in Browser Studio, or in a read-only Studio.
+
+## Return value
+
+Returns a promise that resolves to an empty object when the server acknowledges the shutdown request. The connection closes as Studio shuts down. The promise rejects if the request fails.
+
+## Compatibility
+
+<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering={false} serverSideRendering={false} player={false} studio hideServers />
+
+## See also
+
+- [`restartStudio()`](/docs/studio/restart-studio)
+- [WebMCP](/docs/ai/webmcp)
+- [Source code](https://github.com/remotion-dev/remotion/blob/main/packages/studio/src/api/shut-down-studio.ts)
diff --git a/packages/docs/docs/studio/table-of-contents-data.ts b/packages/docs/docs/studio/table-of-contents-data.ts
index 9d6a7e4cc4..289849485a 100644
--- a/packages/docs/docs/studio/table-of-contents-data.ts
+++ b/packages/docs/docs/studio/table-of-contents-data.ts
@@ -39,6 +39,11 @@ export const studioTableOfContents = [
label: 'restartStudio()',
description: 'Restart the Studio Server.',
},
+ {
+ link: '/docs/studio/shut-down-studio',
+ label: 'shutDownStudio()',
+ description: 'Shut down the Studio Server.',
+ },
{
link: '/docs/studio/play',
label: 'play()',
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index 03e4a8385f..07c745d9c8 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -801,6 +801,7 @@ const sidebars: SidebarsConfig = {
'studio/write-static-file',
'studio/delete-static-file',
'studio/restart-studio',
+ 'studio/shut-down-studio',
'studio/save-default-props',
'studio/play',
'studio/pause',
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index a492a185f7..f6cc3609e5 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -7264,6 +7264,15 @@ export const articles = [
noAi: false,
slug: 'studio/shortcuts',
},
+ {
+ id: 'studio/shut-down-studio',
+ title: 'shutDownStudio()',
+ relativePath: 'docs/studio/shut-down-studio.mdx',
+ compId: 'articles-docs-studio-shut-down-studio',
+ crumb: '@remotion/studio',
+ noAi: false,
+ slug: 'studio/shut-down-studio',
+ },
{
id: 'studio/studio',
title: 'Starting the Studio',
diff --git a/packages/docs/static/generated/articles-docs-studio-shut-down-studio.png b/packages/docs/static/generated/articles-docs-studio-shut-down-studio.png
new file mode 100644
index 0000000000..279d707f92
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-studio-shut-down-studio.png differ
diff --git a/packages/example/e2e/studio-lifecycle-webmcp.test.mts b/packages/example/e2e/studio-lifecycle-webmcp.test.mts
new file mode 100644
index 0000000000..fabd156577
--- /dev/null
+++ b/packages/example/e2e/studio-lifecycle-webmcp.test.mts
@@ -0,0 +1,113 @@
+import {spawn} from 'node:child_process';
+import {createServer} from 'node:net';
+import {expect, test} from '@playwright/test';
+import {e2eEntryPoint, exampleDir, remotionBin} from './constants.mts';
+
+test('WebMCP restarts Studio and gracefully shuts it down through the public APIs', async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ const portServer = createServer();
+ await new Promise<void>((resolve) =>
+ portServer.listen(0, '127.0.0.1', resolve),
+ );
+ const address = portServer.address();
+ if (!address || typeof address === 'string') throw new Error('No test port');
+ await new Promise<void>((resolve) => portServer.close(() => resolve()));
+ const studioUrl = `http://localhost:${address.port}`;
+ const studio = spawn(
+ remotionBin,
+ [
+ 'studio',
+ e2eEntryPoint,
+ '--port',
+ String(address.port),
+ '--no-open',
+ '--force-new',
+ ],
+ {cwd: exampleDir, stdio: 'pipe'},
+ );
+ let logs = '';
+ studio.stdout.on('data', (data: Buffer) => {
+ logs += data.toString();
+ });
+ studio.stderr.on('data', (data: Buffer) => {
+ logs += data.toString();
+ });
+ const exited = new Promise<number | null>((resolve) =>
+ studio.once('exit', resolve),
+ );
+ try {
+ await expect.poll(() => logs, {timeout: 60000}).toContain('Built in');
+ await page.addInitScript(() => {
+ type Tool = {
+ name: string;
+ annotations: {readOnlyHint: boolean};
+ execute: (input: Record<string, unknown>) => Promise<unknown>;
+ };
+ const tools = new Map<string, Tool>();
+ Object.defineProperty(window, '__remotion_webmcp_tools', {value: tools});
+ Object.defineProperty(document, 'modelContext', {
+ value: {
+ registerTool: (tool: Tool, options: {signal: AbortSignal}) => {
+ tools.set(tool.name, tool);
+ options.signal.addEventListener('abort', () => {
+ if (tools.get(tool.name) === tool) tools.delete(tool.name);
+ });
+ return Promise.resolve();
+ },
+ },
+ });
+ });
+ await page.goto(studioUrl);
+ const runTool = async (name: string) => {
+ await expect
+ .poll(() =>
+ page.evaluate((toolName) => {
+ return (
+ window as typeof window & {
+ __remotion_webmcp_tools: Map<string, unknown>;
+ }
+ ).__remotion_webmcp_tools.has(toolName);
+ }, name),
+ )
+ .toBe(true);
+ return page.evaluate(async (toolName) => {
+ const tool = (
+ window as typeof window & {
+ __remotion_webmcp_tools: Map<
+ string,
+ {
+ annotations: {readOnlyHint: boolean};
+ execute: (input: Record<string, unknown>) => Promise<unknown>;
+ }
+ >;
+ }
+ ).__remotion_webmcp_tools.get(toolName);
+ if (!tool) throw new Error('Tool not registered');
+ return {
+ readOnly: tool.annotations.readOnlyHint,
+ result: await tool.execute({}),
+ };
+ }, name);
+ };
+ expect(await runTool('restart_studio')).toEqual({
+ readOnly: false,
+ result: {},
+ });
+ await expect.poll(() => logs).toContain('Restarting server...');
+ await expect
+ .poll(() => logs.split('Built in').length, {timeout: 60000})
+ .toBeGreaterThanOrEqual(3);
+ await page.reload();
+ expect(await runTool('shut_down_studio')).toEqual({
+ readOnly: false,
+ result: {},
+ });
+ expect(await exited).toBe(0);
+ expect(logs).toContain('Shutting down Studio...');
+ } finally {
+ if (studio.exitCode === null) studio.kill('SIGTERM');
+ await exited;
+ }
+});
diff --git a/packages/studio-server/src/preview-server/routes/restart-studio.ts b/packages/studio-server/src/preview-server/routes/restart-studio.ts
index 992b62691b..082df6bd01 100644
--- a/packages/studio-server/src/preview-server/routes/restart-studio.ts
+++ b/packages/studio-server/src/preview-server/routes/restart-studio.ts
@@ -8,8 +8,8 @@ import {signalRestart} from '../close-and-restart';
export const handleRestartStudio: ApiHandler<
RestartStudioRequest,
RestartStudioResponse
-> = () => {
- signalRestart();
+> = ({response}) => {
+ response.once('finish', signalRestart);
return Promise.resolve({});
};
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 06b2bc6a3a..7e20264396 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -1148,6 +1148,8 @@ export type ProjectInfoResponse = {
projectInfo: ProjectInfo;
};
+export type ShutdownStudioResponse = {};
+
export type RestartStudioRequest = {};
export type RestartStudioResponse = {};
@@ -1424,7 +1426,7 @@ export type ApiRoutes = {
CopyRenderOutputToAssetResponse
>;
'/api/upgrade-remotion': ReqAndRes<{version: string}, {}>;
- '/api/shutdown-studio': ReqAndRes<{}, {}>;
+ '/api/shutdown-studio': ReqAndRes<{}, ShutdownStudioResponse>;
'/api/restart-studio': ReqAndRes<RestartStudioRequest, RestartStudioResponse>;
'/api/update-config': ReqAndRes<UpdateConfigRequest, UpdateConfigResponse>;
'/api/default-editor-info': ReqAndRes<
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index 7bc7216fa9..24bac14e56 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -114,6 +114,7 @@ export {
ReorderSequenceResponse,
RestartStudioRequest,
RestartStudioResponse,
+ ShutdownStudioResponse,
SaveEffectPropsRequest,
SaveEffectPropsResponse,
SaveInlineCaptionPatchesRequest,
diff --git a/packages/studio/src/api/shut-down-studio.ts b/packages/studio/src/api/shut-down-studio.ts
new file mode 100644
index 0000000000..65cb415546
--- /dev/null
+++ b/packages/studio/src/api/shut-down-studio.ts
@@ -0,0 +1,25 @@
+/**
+ * @description Shuts down the Remotion Studio.
+ * @see [Documentation](https://www.remotion.dev/docs/studio/shut-down-studio)
+ */
+
+import type {ShutdownStudioResponse} from '@remotion/studio-shared';
+import {getRemotionEnvironment} from 'remotion';
+import {callApi} from '../components/call-api';
+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';
+
+export const shutDownStudio = (): Promise<ShutdownStudioResponse> => {
+ if (!getRemotionEnvironment().isStudio) {
+ throw new Error('shutDownStudio() is only available in the Studio');
+ }
+
+ if (getBrowserStudioOperations() !== null) {
+ throw new Error('shutDownStudio() is not supported in Browser Studio');
+ }
+
+ if (window.remotion_isReadOnlyStudio) {
+ throw new Error('shutDownStudio() is not available in read-only Studio');
+ }
+
+ return callApi('/api/shutdown-studio', {});
+};
diff --git a/packages/studio/src/components/UpdateStatusContext.tsx b/packages/studio/src/components/UpdateStatusContext.tsx
index f328771a99..c26e96ac01 100644
--- a/packages/studio/src/components/UpdateStatusContext.tsx
+++ b/packages/studio/src/components/UpdateStatusContext.tsx
@@ -9,6 +9,7 @@ import React, {
useState,
} from 'react';
import {VERSION} from 'remotion';
+import {shutDownStudio} from '../api/shut-down-studio';
import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';
import {canShowUpdates} from '../helpers/can-show-updates';
import {StudioServerConnectionCtx} from '../helpers/client-id';
@@ -78,7 +79,7 @@ export const UpdateStatusProvider: React.FC<{
setUpgradeState('shutting-down');
setUpgradeError(null);
try {
- await callApi('/api/shutdown-studio', {});
+ await shutDownStudio();
setUpgradeState('shutdown');
} catch (err) {
setUpgradeError((err as Error).message);
diff --git a/packages/studio/src/components/WebMcp.tsx b/packages/studio/src/components/WebMcp.tsx
index 03a83d7db6..3b9198989d 100644
--- a/packages/studio/src/components/WebMcp.tsx
+++ b/packages/studio/src/components/WebMcp.tsx
@@ -2,7 +2,9 @@ import {useContext, useEffect, useMemo, useRef, type FC} from 'react';
import {Internals} from 'remotion';
import {pause} from '../api/pause';
import {play} from '../api/play';
+import {restartStudio} from '../api/restart-studio';
import {seek} from '../api/seek';
+import {shutDownStudio} from '../api/shut-down-studio';
import {getCurrentError} from '../error-overlay/current-error';
import {calculateTimeline} from '../helpers/calculate-timeline';
import {createFolderTree} from '../helpers/create-folder-tree';
@@ -298,6 +300,38 @@ export const WebMcp: FC = () => {
};
Promise.all([
+ modelContext.registerTool(
+ {
+ name: 'restart_studio',
+ title: 'Restart Studio',
+ description:
+ 'Restart the Studio server. The browser temporarily disconnects and reconnects when Studio is ready. Only available in a writable Studio with a server backend.',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ additionalProperties: false,
+ },
+ annotations: {readOnlyHint: false},
+ execute: () => restartStudio(),
+ },
+ {signal: controller.signal},
+ ),
+ modelContext.registerTool(
+ {
+ name: 'shut_down_studio',
+ title: 'Shut down Studio',
+ description:
+ 'Gracefully shut down the Studio server. The browser disconnects. Start Studio again from the terminal to reconnect. Only available in a writable Studio with a server backend.',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ additionalProperties: false,
+ },
+ annotations: {readOnlyHint: false},
+ execute: () => shutDownStudio(),
+ },
+ {signal: controller.signal},
+ ),
modelContext.registerTool(
{
name: 'get_current_error',
diff --git a/packages/studio/src/index.ts b/packages/studio/src/index.ts
index 26abefb579..111702e964 100644
--- a/packages/studio/src/index.ts
+++ b/packages/studio/src/index.ts
@@ -16,6 +16,7 @@ export {pause} from './api/pause';
export {play} from './api/play';
export {reevaluateComposition} from './api/reevaluate-composition';
export {restartStudio} from './api/restart-studio';
+export {shutDownStudio} from './api/shut-down-studio';
export {saveDefaultProps} from './api/save-default-props';
export {seek} from './api/seek';
export {toggle} from './api/toggle';
diff --git a/packages/studio/src/test/restart-studio.test.ts b/packages/studio/src/test/restart-studio.test.ts
index 4a1907f567..1ce6c98c0d 100644
--- a/packages/studio/src/test/restart-studio.test.ts
+++ b/packages/studio/src/test/restart-studio.test.ts
@@ -1,5 +1,6 @@
import {afterEach, expect, test} from 'bun:test';
import {restartStudio} from '../api/restart-studio';
+import {shutDownStudio} from '../api/shut-down-studio';
import {makeBrowserStudioOperations} from './make-browser-studio-operations';
const originalFetch = globalThis.fetch;
@@ -18,24 +19,40 @@ afterEach(() => {
Reflect.deleteProperty(globalThis, 'window');
});
-test('rejects restarting Browser Studio without making a server request', () => {
- const fetchCalls: string[] = [];
- globalThis.fetch = ((input) => {
- fetchCalls.push(String(input));
- return Promise.reject(new Error('Unexpected request'));
- }) as typeof fetch;
- Object.defineProperty(globalThis, 'window', {
- configurable: true,
- value: {
- remotion_browserStudio: makeBrowserStudioOperations({}),
+test.each([
+ ['restartStudio', restartStudio],
+ ['shutDownStudio', shutDownStudio],
+] as const)(
+ '%s rejects unsupported environments before making a request',
+ (name, action) => {
+ const fetchCalls: string[] = [];
+ globalThis.fetch = ((input) => {
+ fetchCalls.push(String(input));
+ return Promise.reject(new Error('Unexpected request'));
+ }) as typeof fetch;
+ const studioWindow = {
+ remotion_browserStudio: null as ReturnType<
+ typeof makeBrowserStudioOperations
+ > | null,
remotion_isPlayer: false,
remotion_isReadOnlyStudio: false,
- remotion_isStudio: true,
- },
- });
-
- expect(() => restartStudio()).toThrow(
- 'restartStudio() is not supported in Browser Studio',
- );
- expect(fetchCalls).toEqual([]);
-});
+ remotion_isStudio: false,
+ };
+ Object.defineProperty(globalThis, 'window', {
+ configurable: true,
+ value: studioWindow,
+ });
+ expect(() => action()).toThrow(`${name}() is only available in the Studio`);
+ studioWindow.remotion_isStudio = true;
+ studioWindow.remotion_browserStudio = makeBrowserStudioOperations({});
+ expect(() => action()).toThrow(
+ `${name}() is not supported in Browser Studio`,
+ );
+ studioWindow.remotion_browserStudio = null;
+ studioWindow.remotion_isReadOnlyStudio = true;
+ expect(() => action()).toThrow(
+ `${name}() is not available in read-only Studio`,
+ );
+ expect(fetchCalls).toEqual([]);
+ },
+);