Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions app/api/video/render/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { getCorsHeaders } from "@/lib/networking/getCorsHeaders";
import { renderVideoHandler } from "@/lib/render/renderVideoHandler";

/**
* OPTIONS handler for CORS preflight requests.
*
* @returns A NextResponse with CORS headers.
*/
export async function OPTIONS() {
return new NextResponse(null, {
status: 200,
headers: getCorsHeaders(),
});
}

/**
* POST /api/video/render
*
* Triggers a server-side video render as a background task. Returns
* immediately with a Trigger.dev run ID that can be polled via
* GET /api/tasks/runs?runId=<runId> for status and the rendered video URL.
*
* Authentication: x-api-key header or Authorization Bearer token required.
*
* Request body:
* - compositionId: string (required) - The composition to render
* - inputProps: object (optional) - Props to pass to the composition
* - width: number (optional, default 720)
* - height: number (optional, default 1280)
* - fps: number (optional, default 30)
* - durationInFrames: number (optional, default 240)
* - codec: "h264" | "h265" | "vp8" | "vp9" (optional, default "h264")
*
* Response (200):
* - status: "processing"
* - runId: string - The Trigger.dev run ID for the render task
*
* Error (400/401/500):
* - status: "error"
* - error: string
*
* @param request - The request object
* @returns A NextResponse with the render result or error
*/
export async function POST(request: NextRequest): Promise<Response> {
return renderVideoHandler(request);
}
2 changes: 2 additions & 0 deletions lib/mcp/tools/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { registerSendEmailTool } from "./registerSendEmailTool";
import { registerAllArtistTools } from "./artists";
import { registerAllChatsTools } from "./chats";
import { registerAllPulseTools } from "./pulse";
import { registerAllRenderTools } from "./render";

/**
* Registers all MCP tools on the server.
Expand All @@ -37,6 +38,7 @@ export const registerAllTools = (server: McpServer): void => {
registerAllFileTools(server);
registerAllImageTools(server);
registerAllPulseTools(server);
registerAllRenderTools(server);
registerAllSearchTools(server);
registerAllSora2Tools(server);
registerAllSpotifyTools(server);
Expand Down
11 changes: 11 additions & 0 deletions lib/mcp/tools/render/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { registerRenderVideoTool } from "./registerRenderVideoTool";

/**
* Registers all render-related MCP tools.
*
* @param server - The MCP server instance
*/
export function registerAllRenderTools(server: McpServer): void {
registerRenderVideoTool(server);
}
101 changes: 101 additions & 0 deletions lib/mcp/tools/render/registerRenderVideoTool.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js";
import type { ServerRequest, ServerNotification } from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import type { McpAuthInfo } from "@/lib/mcp/verifyApiKey";
import { getToolResultSuccess } from "@/lib/mcp/getToolResultSuccess";
import { getToolResultError } from "@/lib/mcp/getToolResultError";
import { triggerRenderVideo } from "@/lib/trigger/triggerRenderVideo";

/** Schema for the render_video MCP tool arguments. */
const renderVideoSchema = z.object({
compositionId: z
.string()
.describe(
'The composition ID to render (e.g., "SocialPost", "UpdatesAnnouncement", "CommitShowcase")',
),
inputProps: z
.record(z.string(), z.unknown())
.optional()
.describe(
"Input props to pass to the composition. Structure depends on the composition being rendered.",
),
width: z
.number()
.int()
.min(1)
.max(3840)
.optional()
.describe("Output width in pixels (default 720)"),
height: z
.number()
.int()
.min(1)
.max(3840)
.optional()
.describe("Output height in pixels (default 1280)"),
fps: z.number().int().min(1).max(60).optional().describe("Frames per second (default 30)"),
durationInFrames: z
.number()
.int()
.min(1)
.max(1800)
.optional()
.describe("Total frames to render. At 30 fps, 240 frames = 8 seconds (default 240)"),
codec: z.enum(["h264", "h265", "vp8", "vp9"]).optional().describe('Video codec (default "h264")'),
});

/**
* Registers the "render_video" MCP tool.
*
* Triggers a server-side video render as a background task and returns
* a run ID that can be polled for status. Uses the same shared
* triggerRenderVideo function as the REST API endpoint.
*
* @param server - The MCP server instance to register the tool on.
*/
export function registerRenderVideoTool(server: McpServer): void {
server.registerTool(
"render_video",
{
description: `Trigger a server-side video render. Returns a run ID that can be polled for status and the rendered video URL.

IMPORTANT:
- compositionId is required — it must match a registered composition
- inputProps vary by composition (e.g., SocialPost needs videoUrl, captionText)
- The render runs in the background; poll the returned runId for completion
- Default output: 720×1280 at 30 fps, 8 seconds, h264 codec`,
inputSchema: renderVideoSchema,
},
async (args, extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => {
const authInfo = extra.authInfo as McpAuthInfo | undefined;
const accountId = authInfo?.extra?.accountId;

if (!accountId) {
return getToolResultError("Authentication required.");
}
Comment on lines +70 to +76
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Search for resolveAccountId definition and usage
rg -n "resolveAccountId" --type=ts -B2 -A5

Repository: recoupable/api

Length of output: 3520


🏁 Script executed:

cat -n lib/mcp/tools/render/registerRenderVideoTool.ts | head -100

Repository: recoupable/api

Length of output: 4366


Import and use resolveAccountId() to derive the account ID from authentication.

The codebase establishes a consistent pattern for MCP tools: use resolveAccountId() with authInfo from extra.authInfo rather than manual extraction. This centralizes auth resolution logic and aligns with established patterns in registerUpdatePulseTool.ts and registerCreateNewArtistTool.ts.

Replace lines 71–76 with:

const authInfo = extra.authInfo as McpAuthInfo | undefined;
const { accountId, error } = await resolveAccountId({ authInfo });

if (error || !accountId) {
  return getToolResultError(error || "Authentication required.");
}

Also add the import at the top:

import { resolveAccountId } from "@/lib/mcp/resolveAccountId";
🤖 Prompt for AI Agents
In `@lib/mcp/tools/render/registerRenderVideoTool.ts` around lines 70 - 76, The
code manually extracts accountId from extra.authInfo; replace that with the
shared resolver: import resolveAccountId and call await resolveAccountId({
authInfo }) using the existing authInfo variable, then check the returned {
accountId, error } and return getToolResultError(error || "Authentication
required.") if error or no accountId; update the handler where authInfo is used
(the async handler in registerRenderVideoTool) to follow the same pattern as
registerUpdatePulseTool and registerCreateNewArtistTool.


try {
const handle = await triggerRenderVideo({
compositionId: args.compositionId,
inputProps: args.inputProps ?? {},
width: args.width ?? 720,
height: args.height ?? 1280,
fps: args.fps ?? 30,
durationInFrames: args.durationInFrames ?? 240,
codec: args.codec ?? "h264",
accountId,
});

return getToolResultSuccess({
status: "processing",
runId: handle.id,
message: "Video render triggered. Poll for status using the runId.",
});
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to trigger video render";
return getToolResultError(message);
}
},
);
}
185 changes: 185 additions & 0 deletions lib/render/__tests__/renderVideoHandler.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest, NextResponse } from "next/server";
import { renderVideoHandler } from "@/lib/render/renderVideoHandler";

import { validateAuthContext } from "@/lib/auth/validateAuthContext";
import { validateRenderVideoBody } from "@/lib/render/validateRenderVideoBody";
import { triggerRenderVideo } from "@/lib/trigger/triggerRenderVideo";

vi.mock("@/lib/networking/getCorsHeaders", () => ({
getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })),
}));

vi.mock("@/lib/auth/validateAuthContext", () => ({
validateAuthContext: vi.fn(),
}));

vi.mock("@/lib/render/validateRenderVideoBody", () => ({
validateRenderVideoBody: vi.fn(),
}));

vi.mock("@/lib/trigger/triggerRenderVideo", () => ({
triggerRenderVideo: vi.fn(),
}));

vi.mock("@/lib/networking/safeParseJson", () => ({
safeParseJson: vi.fn(),
}));

describe("renderVideoHandler", () => {
beforeEach(() => {
vi.clearAllMocks();
});

it("returns auth error when authentication fails", async () => {
const errorResponse = NextResponse.json(
{ status: "error", error: "Unauthorized" },
{ status: 401 },
);
vi.mocked(validateAuthContext).mockResolvedValue(errorResponse);

const request = new NextRequest("http://localhost/api/video/render", {
method: "POST",
body: JSON.stringify({ compositionId: "SocialPost" }),
headers: { "Content-Type": "application/json" },
});

const result = await renderVideoHandler(request);

expect(result).toBe(errorResponse);
});

it("returns validation error when body validation fails", async () => {
// Auth passes
vi.mocked(validateAuthContext).mockResolvedValue({
accountId: "test-account-id",
orgId: null,
authToken: "test-token",
});

const errorResponse = NextResponse.json(
{ status: "error", error: "compositionId is required" },
{ status: 400 },
);
vi.mocked(validateRenderVideoBody).mockReturnValue(errorResponse);

const request = new NextRequest("http://localhost/api/video/render", {
method: "POST",
body: JSON.stringify({}),
headers: { "Content-Type": "application/json" },
});

const result = await renderVideoHandler(request);

expect(result).toBe(errorResponse);
});

it("returns processing status with runId on success", async () => {
vi.mocked(validateAuthContext).mockResolvedValue({
accountId: "test-account-id",
orgId: null,
authToken: "test-token",
});

vi.mocked(validateRenderVideoBody).mockReturnValue({
compositionId: "SocialPost",
inputProps: { videoUrl: "https://example.com/video.mp4" },
width: 720,
height: 1280,
fps: 30,
durationInFrames: 240,
codec: "h264",
});

vi.mocked(triggerRenderVideo).mockResolvedValue({
id: "run_render_abc123",
} as never);

const request = new NextRequest("http://localhost/api/video/render", {
method: "POST",
body: JSON.stringify({ compositionId: "SocialPost" }),
headers: { "Content-Type": "application/json" },
});

const result = await renderVideoHandler(request);
const body = await result.json();

expect(result.status).toBe(200);
expect(body).toEqual({
status: "processing",
runId: "run_render_abc123",
});
});

it("passes accountId to triggerRenderVideo", async () => {
vi.mocked(validateAuthContext).mockResolvedValue({
accountId: "my-account-id",
orgId: null,
authToken: "test-token",
});

vi.mocked(validateRenderVideoBody).mockReturnValue({
compositionId: "SocialPost",
inputProps: {},
width: 720,
height: 1280,
fps: 30,
durationInFrames: 240,
codec: "h264",
});

vi.mocked(triggerRenderVideo).mockResolvedValue({
id: "run_123",
} as never);

const request = new NextRequest("http://localhost/api/video/render", {
method: "POST",
body: JSON.stringify({ compositionId: "SocialPost" }),
headers: { "Content-Type": "application/json" },
});

await renderVideoHandler(request);

expect(triggerRenderVideo).toHaveBeenCalledWith(
expect.objectContaining({
accountId: "my-account-id",
compositionId: "SocialPost",
}),
);
});

it("returns 500 when trigger fails", async () => {
vi.mocked(validateAuthContext).mockResolvedValue({
accountId: "test-account-id",
orgId: null,
authToken: "test-token",
});

vi.mocked(validateRenderVideoBody).mockReturnValue({
compositionId: "SocialPost",
inputProps: {},
width: 720,
height: 1280,
fps: 30,
durationInFrames: 240,
codec: "h264",
});

vi.mocked(triggerRenderVideo).mockRejectedValue(new Error("Trigger.dev connection failed"));

const request = new NextRequest("http://localhost/api/video/render", {
method: "POST",
body: JSON.stringify({ compositionId: "SocialPost" }),
headers: { "Content-Type": "application/json" },
});

const result = await renderVideoHandler(request);
const body = await result.json();

expect(result.status).toBe(500);
expect(body).toEqual({
status: "error",
error: "Trigger.dev connection failed",
});
});
});
Loading