Skip to content

Open source CapCut alternative.

TypeScript
30.3 KB
Raw Blame
import { createMcpHandler, fromJsonSchema, McpServer } from "@modelcontextprotocol/server";
import { z } from "zod";
import {
  checkInMemoryRateLimit,
  rateLimitResponse,
} from "@/lib/inference/rate-limit";
import {
  viewSchema,
  WIDGET_URI,
  type ProjectView,
} from "@/clients/chatgpt/contracts";
import {
  commandHints,
  COMMANDS,
  readSkill,
  SKILL_INDEX,
} from "@/clients/chatgpt/server/catalog";
import { DOC_EXPORT_PRESETS } from "@/cut/lib/exportPresets";
import { CUT_LOUDNESS, LOUDNESS_CHOICES, LOUDNESS_IDS } from "@/cut/lib/loudnessSettings";
import { formatCredits } from "@/lib/credits/format-credits";
import {
  chatgptConfig,
  RESOURCE_METADATA_PATH,
  type ChatgptConfig,
} from "@/clients/chatgpt/server/config";
import { accessIdentity } from "@/clients/chatgpt/server/oauthTokens";
import {
  ProjectToolError,
  projectTools,
  type ProjectResult,
} from "@/clients/chatgpt/server/projects";
import { widgetHtml } from "@/clients/chatgpt/widget.generated";
import { searchLinksOf, splitToolDisplay } from "@/cut/lib/toolDisplay";
import { mcpLocale } from "@/clients/chatgpt/server/locale";
import { DEFAULT_LOCALE } from "@/i18n/locales";
import { prisma } from "@/lib/prisma";
import type { Messages } from "@/i18n/namespaces";
import { translatorFor } from "@/i18n/translator";
import { createTranslator } from "use-intl/core";
import englishMessages from "@/i18n/messages/en/chatgpt.json";

const idSchema = z.string().min(1).max(128);
const readOnlyAnnotations = {
  readOnlyHint: true,
  destructiveHint: false,
  openWorldHint: false,
  idempotentHint: true,
};
const editAnnotations = {
  readOnlyHint: false,
  destructiveHint: false,
  openWorldHint: false,
  idempotentHint: false,
};
// Undo and redo overwrite the document with another revision of it.
const historyAnnotations = { ...editAnnotations, destructiveHint: true };

/** The tool behind the composer's @-mention menu. */
const MENTION_TOOL = "find_projects";

export const REPOSITORY_URL = "https://github.com/DonkeyCut/Donkey";

/** What ChatGPT reads before it picks a tool. The first 512 characters carry
 * the weight, so the economics and the workflow come first. */
export const SERVER_INSTRUCTIONS = [
  `Donkey Cut is an open-source video editor (Apache 2.0, ${REPOSITORY_URL}). Edit the connected account's cloud projects: import footage, inspect it, cut it, caption it, preview, undo, export.`,
  "Editing, previews and exports are free. Hosted AI (voiceover, music, images, caption rewriting, transcription past the monthly allowance) spends the account's credits. Imports and exports use the account's cloud storage.",
  "You plan the edit with the user and interpret the footage; Donkey Cut supplies media inspection, signal measurements and editing tools. Use the user's assets and references. Ask for missing files, links or creative decisions when they are needed to fulfill the request. Read read_skill for guidance tailored to this ChatGPT client.",
  "Workflow: list_projects or create_project → open_project → import_media → inspect_project → editing tools (one undo step each) → render_preview → undo/redo → export_video.",
  "Keep the existing editor card for the whole editing session. Its undo history belongs to that card. Call open_project only to open a project initially, switch projects, or recover a missing card. After editing, the existing card shows the changes; use render_preview and get_preview_status to verify the saved preview. Reopening the project creates a fresh editor with empty history.",
  "Every edit runs inside the Donkey Cut editor in the card, on the document the user is looking at: open_project puts that editor in the card, timeline and panels included, when the connection can edit, and the editing and inspection tools, import_media, undo and redo answer that no card is open until it is. A read-only connection sees the current preview playing. Call render_preview only after an edit or when the card reports no current preview.",
  "If the editor shows Reconnect, ask the user to click it to renew the embedded session and reload the editor in ChatGPT. If a tool reports no card open, ask the user to open the project card and keep it open, then resume when it is ready. When the catalog lacks an operation, explain the limit and ask for the required media or a user action in Donkey Cut.",
  "Inspect before editing. Watch and listen to the relevant media before content-based cuts; use silence, beat, level and color measurements for timing and adjustments. Save observations with note_source. Verify changes with the returned state, frames and audio, and give the user a preview to review. Claim only coverage and completed work confirmed by tool results.",
  "A project the user @-mentions arrives as a link ending in /app/p/<projectId>.",
  "Times are seconds; ids come from inspect_project. A tool that answers with a job still running is finished by get_job_status.",
].join("\n");

/** An editor command as its own tool: the command's schema plus the project
 * it runs on. Validators compile once per process, outside any request. */
type CommandTool = { name: string; title: string; description: string; inputSchema: ReturnType<typeof fromJsonSchema<Record<string, unknown>>> };
let commandTools: CommandTool[] | null = null;

function listCommandTools(): CommandTool[] {
  commandTools ??= COMMANDS.map((command) => {
    const schema = command.inputSchema as { properties?: Record<string, unknown>; required?: string[] };
    return {
      name: command.name,
      title: command.name.charAt(0).toUpperCase() + command.name.slice(1).replaceAll("_", " "),
      description: command.description,
      inputSchema: fromJsonSchema<Record<string, unknown>>({
        ...schema,
        type: "object",
        properties: { projectId: { type: "string", minLength: 1, maxLength: 128, description: "The cloud project's id" }, ...schema.properties },
        required: ["projectId", ...(schema.required ?? [])],
      }),
    };
  });
  return commandTools;
}

/** A file ChatGPT attaches to a call (openai/fileParams). */
const fileSchema = z.object({
  download_url: z.url(),
  file_id: z.string(),
  mime_type: z.string().optional(),
  file_name: z.string().optional(),
});

type MediaBlock = { type: "image" | "audio"; data: string; mimeType: string };

/** Data-URL images and audio in a command's output become MCP image and
 * audio blocks, so base64 never lands in the text the model reads. */
function liftMedia(view: ProjectView): MediaBlock[] {
  const blocks: MediaBlock[] = [];
  const lift = (value: unknown): unknown => {
    const match = typeof value === "string" ? value.match(/^data:((image|audio)\/[a-z0-9.+-]+);base64,([\s\S]+)$/) : null;
    if (!match) return value;
    blocks.push({ type: match[2] as "image" | "audio", data: match[3], mimeType: match[1] });
    return `(${match[2]} ${blocks.length} attached)`;
  };
  for (const result of view.results) {
    const out = result.output as { image?: unknown; images?: unknown[]; audio?: unknown } | null;
    if (!out || typeof out !== "object") continue;
    if ("image" in out) out.image = lift(out.image);
    if (Array.isArray(out.images)) out.images = out.images.map(lift);
    if ("audio" in out) out.audio = lift(out.audio);
  }
  return blocks;
}

/** A command's `display` markup (Google's Search Suggestions beside a grounded
 * check) leaves its output; ChatGPT renders no markup from a tool result, so
 * the output carries the same searches as links to show with the result. */
function liftDisplay(view: ProjectView): void {
  for (const result of view.results) {
    const { output, display } = splitToolDisplay(result.output);
    if (output === result.output) continue;
    const links = (display?.searchSuggestions ?? []).flatMap(searchLinksOf);
    result.output = links.length > 0 ? { ...(output as object), searchSuggestions: links } : output;
  }
}

type Identity = { userId: string; scopes: string[]; grantId: string };
type ChatgptTranslator = Awaited<ReturnType<typeof translatorFor<"chatgpt">>>;
type StatusTool = keyof Messages["chatgpt"]["status"];

// The English source, for servers built without a request (tests, evals).
const ENGLISH = createTranslator({ locale: "en", messages: { chatgpt: englishMessages }, namespace: "chatgpt" });

export function createChatgptServer(
  identity: Identity,
  config: ChatgptConfig,
  projects = projectTools(identity, config),
  t: ChatgptTranslator = ENGLISH,
) {
  const server = new McpServer(
    { name: "donkey-cut", title: "Donkey Cut", version: "1.3.0" },
    {
      instructions: SERVER_INSTRUCTIONS,
      // The composer's @-menu lists the account's projects through this tool.
      capabilities: { extensions: { "openai/mentions": { searchTool: MENTION_TOOL } } },
    },
  );
  const readMetadata = {
    securitySchemes: [{ type: "oauth2", scopes: ["projects:read"] }],
  };
  const renderMetadata = {
    securitySchemes: [
      { type: "oauth2", scopes: ["projects:read", "previews:render"] },
    ],
  };
  const editMetadata = {
    securitySchemes: [
      { type: "oauth2", scopes: ["projects:read", "projects:write"] },
    ],
  };
  // The status lines ChatGPT shows the person under a call, in their language.
  const status = (tool: StatusTool) => ({
    "openai/toolInvocation/invoking": t(`status.${tool}.invoking`),
    "openai/toolInvocation/invoked": t(`status.${tool}.invoked`),
  });
  const scopeChallenge = (scope: string, text: string) => ({
    isError: true,
    content: [{ type: "text" as const, text }],
    _meta: {
      "mcp/www_authenticate": [
        `Bearer error="insufficient_scope", resource_metadata="${config.issuer}${RESOURCE_METADATA_PATH}", scope="projects:read previews:render projects:write"`,
      ],
      requiredScope: scope,
    },
  });
  const runTool = async (run: () => Promise<ProjectResult>) => {
    try {
      const { view, playback, download, editor } = await projects.withEditor(await run());
      const media = liftMedia(view);
      liftDisplay(view);
      const opened = view.project ? "\nThe Donkey Cut editor is open in the card." : "\nThe Donkey Cut projects home is open in the card.";
      const text = describeProjectView(view) + (editor ? opened : "");
      return {
        content: [{ type: "text" as const, text }, ...media],
        structuredContent: view,
        _meta: { playback, download: download ?? null, editor: editor ?? null, pollMs: config.pollMs },
      };
    } catch (error) {
      if (!(error instanceof ProjectToolError)) {
        console.error(
          "[chatgpt] project tool failed",
          error instanceof Error ? error.name : "Unknown error",
        );
      }
      const message =
        error instanceof ProjectToolError
          ? error.message
          : "Donkey Cut could not complete this request. Try again shortly.";
      return {
        isError: true,
        content: [{ type: "text" as const, text: message }],
      };
    }
  };

  server.registerTool(
    "list_projects",
    {
      title: "List Donkey Cut cloud projects",
      description:
        "List the connected user's saved cloud projects, most recently edited first. Browser and Mac projects become available after being saved to the cloud. Follow nextCursor for more results.",
      inputSchema: z.object({ cursor: idSchema.optional() }),
      outputSchema: viewSchema,
      annotations: readOnlyAnnotations,
      _meta: readMetadata,
    },
    ({ cursor }) => runTool(() => projects.list(cursor)),
  );

  server.registerTool(
    "open_project",
    {
      // The sidebar and the thread panel open the projects home under this title and
      // paint the donkey glyph in the menu's own ink.
      title: "Donkey Cut",
      icons: [{ src: `${config.issuer}/chatgpt-entry.svg`, mimeType: "image/svg+xml", sizes: ["any"] }],
      description:
        "Open a cloud project initially, switch projects, or recover a missing card. Keep the existing card during edits and preview checks: reopening creates a fresh editor with empty undo history. The editable card holds the full editor, timeline, media panel, inspector and preview. A read-only connection sees the preview; use render_preview when its revision is stale or missing. With no projectId, show the projects home, where the user opens or starts a project or browses their library; the card then tells you which project it shows. A deleted project answers view \"missing\" and the card offers to create a new one.",
      inputSchema: z.object({ projectId: idSchema.optional() }),
      outputSchema: viewSchema,
      annotations: readOnlyAnnotations,
      _meta: {
        ...readMetadata,
        ui: { resourceUri: WIDGET_URI },
        "openai/ui": { entrypoints: [{ type: "global" }, { type: "thread" }] },
      },
    },
    ({ projectId }) =>
      runTool(() => (projectId ? projects.open(projectId) : projects.list())),
  );

  server.registerTool(
    "render_preview",
    {
      title: "Render a Donkey Cut preview",
      description:
        "Render the current saved cloud project into a playable preview. Needed only after an edit or when open_project reports no current preview; a current one is returned as is. Returns a job immediately; use get_preview_status to check it. Consumes no AI credits. Does not edit the project.",
      inputSchema: z.object({ projectId: idSchema }),
      outputSchema: viewSchema,
      annotations: { ...readOnlyAnnotations, readOnlyHint: false },
      _meta: renderMetadata,
    },
    ({ projectId }) => {
      if (!identity.scopes.includes("previews:render")) {
        return scopeChallenge("previews:render", "Reconnect Donkey Cut to allow preview rendering.");
      }
      return runTool(() => projects.render(projectId));
    },
  );

  server.registerTool(
    "get_preview_status",
    {
      title: "Check a Donkey Cut preview",
      description:
        "Read render progress or renew the playback URL of an existing preview. Returns expired when the preview needs rendering again.",
      inputSchema: z.object({ projectId: idSchema, jobId: idSchema }),
      outputSchema: viewSchema,
      annotations: readOnlyAnnotations,
      _meta: readMetadata,
    },
    ({ projectId, jobId }) => runTool(() => projects.status(projectId, jobId)),
  );

  const editing = <T,>(run: () => Promise<T>) =>
    identity.scopes.includes("projects:write")
      ? run()
      : Promise.resolve(scopeChallenge("projects:write", "Reconnect Donkey Cut to allow editing."));

  server.registerTool(
    MENTION_TOOL,
    {
      title: "Find Donkey Cut projects",
      description: "Search the connected user's cloud projects by name for the composer's @-mention menu.",
      inputSchema: z.object({ query: z.string().max(200) }),
      annotations: readOnlyAnnotations,
      _meta: { ...readMetadata, ui: { visibility: ["app"] } },
    },
    async ({ query }) => {
      const found = await projects.search(query.trim());
      return {
        content: [],
        structuredContent: { items: found.map((p) => ({ type: "resource_link" as const, uri: p.url, name: p.name, mimeType: "text/html" })) },
      };
    },
  );

  server.registerTool(
    "create_project",
    {
      title: "Create a Donkey Cut project",
      description:
        "Create an empty cloud project. aspect is the output frame as \"W:H\" — 9:16 for TikTok, Reels and Shorts, 16:9 for YouTube, 1:1 square (default 9:16). Free.",
      inputSchema: z.object({ name: z.string().min(1).max(120), aspect: z.string().max(16).optional() }),
      outputSchema: viewSchema,
      annotations: editAnnotations,
      _meta: { ...editMetadata, ...status("createProject") },
    },
    ({ name, aspect }) => editing(() => runTool(() => projects.create(name, aspect))),
  );

  server.registerTool(
    "import_media",
    {
      title: "Import footage into a project",
      description:
        "Bring footage into a cloud project: files the user attached to the chat (files), or links (urls) — TikTok, YouTube, Instagram, an X post, a web page, or a direct video/audio/image link. Every file lands as a project asset with an assetId for add_clip. Free; the bytes use the account's cloud storage. A long download can outlast this call — then the answer carries a job to finish with get_job_status. audio_only keeps just the soundtrack of a link.",
      inputSchema: z.object({
        projectId: idSchema,
        files: z.array(fileSchema).max(10).optional().describe("Files attached in ChatGPT"),
        urls: z.array(z.url()).max(10).optional().describe("Links to import"),
        audio_only: z.boolean().optional(),
      }),
      outputSchema: viewSchema,
      annotations: { ...editAnnotations, openWorldHint: true },
      _meta: { ...editMetadata, "openai/fileParams": ["files"], ...status("importMedia") },
    },
    ({ projectId, files, urls, audio_only }) =>
      editing(() =>
        runTool(() => {
          const items = [
            ...(files ?? []).map((f) => ({ url: f.download_url, ...(f.file_name ? { name: f.file_name } : {}) })),
            ...(urls ?? []).map((url) => ({ url })),
          ];
          if (!items.length) throw new ProjectToolError("Attach files or pass urls.");
          return projects.importMedia(projectId, items, audio_only === true);
        }),
      ),
  );

  server.registerTool(
    "inspect_project",
    {
      title: "Inspect a project",
      description:
        "Read a project's full editor state — media assets with ids, durations, transcripts and notes; the video tracks with clip ids, trims and gaps; soundtrack, titles, captions, aspect. Call it before editing and after an edit you want to verify. Free.",
      inputSchema: z.object({ projectId: idSchema }),
      outputSchema: viewSchema,
      annotations: readOnlyAnnotations,
      _meta: { ...readMetadata, ...status("inspectProject") },
    },
    ({ projectId }) => runTool(() => projects.inspect(projectId)),
  );

  server.registerTool(
    "list_skills",
    {
      title: "List editing guides",
      description: "Guides for Donkey Cut in ChatGPT: the editor-card workflow, watching and listening, signal measurements, timeline editing, captions, transitions, graphics, audio and export. Read one with read_skill before working in an unfamiliar area.",
      inputSchema: z.object({}),
      outputSchema: z.object({ skills: z.array(z.string()) }),
      annotations: readOnlyAnnotations,
      _meta: { ...readMetadata, ...status("listSkills") },
    },
    () => ({
      content: [{ type: "text" as const, text: SKILL_INDEX.join("\n") }],
      structuredContent: { skills: SKILL_INDEX },
    }),
  );

  server.registerTool(
    "read_skill",
    {
      title: "Read an editing guide",
      description: "Read a ChatGPT editing guide from list_skills.",
      inputSchema: z.object({ name: z.string().min(1).max(64) }),
      outputSchema: z.object({ name: z.string(), guide: z.string() }),
      annotations: readOnlyAnnotations,
      _meta: { ...readMetadata, ...status("readSkill") },
    },
    ({ name }) => {
      const doc = readSkill(name);
      if (!doc) return { isError: true, content: [{ type: "text" as const, text: `No such guide. Available: ${SKILL_INDEX.join(", ")}` }] };
      return { content: [{ type: "text" as const, text: doc }], structuredContent: { name, guide: doc } };
    },
  );

  // Every editor command is its own tool, annotated by what it does. A read
  // runs without saving; a write is one undo step in the card's editor. The
  // project view they answer with goes undeclared: a copy of its schema per
  // command would double the tool listing.
  for (const command of listCommandTools()) {
    const hints = commandHints(command.name);
    const reads = hints.readOnlyHint;
    server.registerTool(
      command.name,
      {
        title: command.title,
        description: command.description,
        inputSchema: command.inputSchema,
        annotations: hints,
        _meta: reads ? { ...readMetadata, ...status("inspectProject") } : { ...editMetadata, ...status("editProject") },
      },
      ({ projectId, ...input }) => {
        const call = [{ name: command.name, input }];
        const id = String(projectId);
        return reads
          ? runTool(() => projects.inspect(id, call))
          : editing(() => runTool(() => projects.edit(id, call)));
      },
    );
  }

  server.registerTool(
    "undo",
    {
      title: "Undo the last edit",
      description: "Undo the last step in the editor open in the card, the same as ⌘Z there: ChatGPT's edits, imports and the user's own edits share one history.",
      inputSchema: z.object({ projectId: idSchema }),
      outputSchema: viewSchema,
      annotations: historyAnnotations,
      _meta: { ...editMetadata, ...status("undo") },
    },
    ({ projectId }) => editing(() => runTool(() => projects.undo(projectId))),
  );

  server.registerTool(
    "redo",
    {
      title: "Redo an undone edit",
      description: "Re-apply the step the last undo reverted, in the editor open in the card.",
      inputSchema: z.object({ projectId: idSchema }),
      outputSchema: viewSchema,
      annotations: historyAnnotations,
      _meta: { ...editMetadata, ...status("redo") },
    },
    ({ projectId }) => editing(() => runTool(() => projects.redo(projectId))),
  );

  server.registerTool(
    "export_video",
    {
      title: "Export a project",
      description:
        `Render the saved project to an MP4 the user downloads from the Donkey Cut card. preset: ${DOC_EXPORT_PRESETS.join(" | ")} (original matches the footage; tiktok is best quality 1080p; fast is a smaller 1080p; light is a 720p draft). loudness masters the mix to an integrated target under a true-peak ceiling: ${LOUDNESS_CHOICES.map((c) => (c.id === "off" ? "off (the mix as it plays)" : `${c.id} ${CUT_LOUDNESS.targets[c.id]} LUFS (${c.detail})`)).join(", ")}; the true-peak ceiling is ${CUT_LOUDNESS.truePeakCeiling} dBTP; omitted masters to ${CUT_LOUDNESS.defaultTarget}. stems: true also writes one 24-bit WAV per lane (dialogue from the video clips, then each soundtrack lane), full length and unmastered, zipped as "<name> stems.zip" beside the video in the project's exports. Free; the files count against the account's cloud storage and are listed in the project's exports. A render can outlast this call — finish it with get_export_status.`,
      inputSchema: z.object({
        projectId: idSchema,
        preset: z.enum(DOC_EXPORT_PRESETS).optional(),
        loudness: z.enum(LOUDNESS_IDS).optional(),
        stems: z.boolean().optional(),
      }),
      outputSchema: viewSchema,
      annotations: editAnnotations,
      _meta: { ...editMetadata, ...status("exportVideo") },
    },
    ({ projectId, preset, loudness, stems }) =>
      editing(() => runTool(() => projects.exportVideo(projectId, preset ?? "original", { loudness, stems }))),
  );

  server.registerTool(
    "get_export_status",
    {
      title: "Check an export",
      description: "Read an export's progress; when it is done the Donkey Cut card offers the download.",
      inputSchema: z.object({ jobId: idSchema }),
      outputSchema: viewSchema,
      annotations: readOnlyAnnotations,
      _meta: { ...readMetadata, ...status("exportStatus") },
    },
    ({ jobId }) => runTool(() => projects.exportStatus(jobId)),
  );

  server.registerTool(
    "get_job_status",
    {
      title: "Check a job",
      description: "Finish a call that answered with a running job (an import, an edit, an export): read its progress and, once done, its results.",
      inputSchema: z.object({ jobId: idSchema }),
      outputSchema: viewSchema,
      annotations: readOnlyAnnotations,
      _meta: { ...readMetadata, ...status("jobStatus") },
    },
    ({ jobId }) => runTool(() => projects.jobStatus(jobId)),
  );

  server.registerTool(
    "account_status",
    {
      title: "Account credits and storage",
      description: "The connected account's AI credit balance, cloud storage used against its allowance, and plan. Editing, previews and exports never spend credits.",
      inputSchema: z.object({}),
      outputSchema: viewSchema,
      annotations: readOnlyAnnotations,
      _meta: { ...readMetadata, ...status("accountStatus") },
    },
    () => runTool(() => projects.account()),
  );

  server.registerResource(
    "project-preview",
    WIDGET_URI,
    { mimeType: "text/html;profile=mcp-app" },
    async () => ({
      contents: [
        {
          uri: WIDGET_URI,
          mimeType: "text/html;profile=mcp-app",
          text: widgetHtml(config.issuer),
          _meta: {
            ui: {
              prefersBorder: true,
              domain: "https://chatgpt.donkeycut.com",
              csp: {
                connectDomains: ["https://media.donkeycut.com"],
                resourceDomains: [config.issuer, "https://media.donkeycut.com"],
                frameDomains: [config.issuer],
              },
            },
            // Inline in the conversation; the user can expand it, and
            // entrypoints always open fullscreen.
            "openai/ui": { availableDisplayModes: ["inline", "fullscreen"], preferredDisplayMode: "inline" },
            "openai/widgetDescription":
              "Donkey Cut projects home and editor, or a video preview with render progress, export download, and an Open in Donkey Cut link.",
          },
        },
      ],
    }),
  );
  return server;
}

function describeProjectView(view: ProjectView): string {
  if (view.account) {
    const { credits, storageBytes, storageQuotaBytes, plan } = view.account;
    const storage = typeof storageQuotaBytes !== "number" ? `${mb(storageBytes)} MB used` : `${mb(storageBytes)} of ${mb(storageQuotaBytes)} MB used`;
    return `Plan: ${plan}. AI credit balance: ${formatCredits(credits, DEFAULT_LOCALE)}. Cloud storage: ${storage}. Editing, previews and exports spend no credits.`;
  }
  if (view.view === "projects") {
    if (!view.projects.length) {
      return "No cloud projects yet. Create one with create_project, or open Donkey Cut to save a project to the cloud.";
    }
    return view.projects
      .map((project) => `${project.name}: ${project.id} (${project.url})`)
      .join("\n");
  }
  if (view.view === "missing") {
    return `Project ${view.missing?.id ?? ""} no longer exists. The card offers to create a new project; list_projects shows the others.`;
  }

  const project = view.project!;
  const lines: string[] = [];
  if (view.job && view.job.status !== "done") {
    lines.push(
      view.job.status === "error"
        ? `Job ${view.job.id} (${view.job.kind}) failed: ${view.job.error ?? "unknown error"}.`
        : `Job ${view.job.id} (${view.job.kind}) is ${view.job.status} at ${Math.round(view.job.progress * 100)}%. Call get_job_status with this id to finish.`,
    );
  }
  if (view.results.length) {
    const failed = view.results.filter((r) => !r.ok);
    lines.push(
      `${view.results.length} command${view.results.length === 1 ? "" : "s"} ran${failed.length ? `, ${failed.length} failed` : ""}${view.changed ? "; the project was saved" : "; nothing changed"}.`,
    );
    lines.push(JSON.stringify(view.results));
  }
  if (view.export) {
    const { status, progress, name, error } = view.export;
    lines.push(
      status === "done"
        ? `Export ${name ?? ""} is ready: the Donkey Cut card has the Download button, and the file is in the project's Media panel.`
        : status === "error" || status === "expired"
          ? `Export ${name ?? ""} ${status}: ${error ?? ""}`
          : `Export ${name ?? ""} is ${status} at ${Math.round(progress * 100)}%. Call get_export_status with job id ${view.export.id}.`,
    );
  }
  if (view.preview || !lines.length) {
    const preview = view.preview;
    lines.push(
      `${project.name} (${project.revision}): ${
        !preview ? "no preview yet"
          : preview.status === "done" && preview.revision === project.revision ? "current preview playing in the card"
          : preview.status === "done" ? `preview from earlier revision ${preview.revision ?? "unknown"}`
          : `preview ${preview.status}`
      }.`,
    );
  }
  lines.push(`Open in Donkey Cut: ${project.url}`);
  return lines.join("\n");
}

const mb = (bytes: number) => Math.round(bytes / 1024 ** 2);

/** POST /api/chatgpt/mcp: this protocol accepts scoped OAuth access tokens. */
export async function mcpEndpoint(request: Request) {
  const config = await chatgptConfig();
  if (!config.enabled) {
    return new Response("ChatGPT connection is not enabled.", { status: 503 });
  }
  // ChatGPT's server-to-server transport has no Origin. Browser callers use the app bridge.
  const origin = request.headers.get("origin");
  if (origin && origin !== config.issuer) {
    return new Response("Forbidden", { status: 403 });
  }

  const authorizationHeader = request.headers.get("authorization");
  const identity =
    authorizationHeader && /^Bearer /i.test(authorizationHeader)
      ? await accessIdentity(authorizationHeader.slice(7), config)
      : null;
  if (!identity || !identity.scopes.includes("projects:read")) {
    return new Response(null, {
      status: identity ? 403 : 401,
      headers: {
        "WWW-Authenticate": `Bearer resource_metadata="${config.issuer}${RESOURCE_METADATA_PATH}", scope="projects:read previews:render projects:write"`,
        "Cache-Control": "no-store",
      },
    });
  }

  const rateLimit = checkInMemoryRateLimit({
    key: `chatgpt:mcp:${identity.userId}`,
    limit: config.requestsPerMinute,
    windowMs: 60000,
  });
  if (!rateLimit.ok) {
    return rateLimitResponse(rateLimit.retryAfterSeconds);
  }

  const locale = await mcpLocale(request, identity.userId);
  const handler = chatgptHttpHandler(
    identity,
    config,
    projectTools(identity, config, prisma, locale),
    await translatorFor(locale, "chatgpt"),
  );
  try {
    const response = await handler.fetch(request);
    // Materialize the body before closing the per-request handler.
    const body = await response.arrayBuffer();
    return new Response(body.byteLength ? body : null, {
      status: response.status,
      headers: {
        ...Object.fromEntries(response.headers),
        "Cache-Control": "no-store",
      },
    });
  } finally {
    await handler.close();
  }
}

/**
 * Serves protocol 2026-07-28 requests directly and answers 2025-era clients
 * through the stateless initialize path, so a ChatGPT connection works
 * whichever revision it sends. Every request gets a fresh server.
 */
export function chatgptHttpHandler(
  identity: Identity,
  config: ChatgptConfig,
  projects?: ReturnType<typeof projectTools>,
  t?: ChatgptTranslator,
) {
  return createMcpHandler(
    () => createChatgptServer(identity, config, projects, t),
    {
      onerror: (error) =>
        console.warn("[chatgpt] mcp request rejected", error.message),
    },
  );
}