-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add POST /api/video/render endpoint #222
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sidneyswift
wants to merge
1
commit into
test
Choose a base branch
from
feature/video-render-endpoint
base: test
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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."); | ||
| } | ||
|
|
||
| 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); | ||
| } | ||
| }, | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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", | ||
| }); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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:
Repository: recoupable/api
Length of output: 3520
🏁 Script executed:
cat -n lib/mcp/tools/render/registerRenderVideoTool.ts | head -100Repository: 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()withauthInfofromextra.authInforather than manual extraction. This centralizes auth resolution logic and aligns with established patterns inregisterUpdatePulseTool.tsandregisterCreateNewArtistTool.ts.Replace lines 71–76 with:
Also add the import at the top:
🤖 Prompt for AI Agents