The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
MCP server: let other agents drive the studio
Claude490cce5a2dcd
diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.tsnew file mode 100644index 00000000..08ce06cf--- /dev/null+++ b/src/app/api/mcp/route.ts@@ -0,0 +1,28 @@+import { handleMcp } from "@/server/mcp";++/**+ * MCP endpoint (streamable HTTP, stateless, JSON responses). Point an MCP client at+ * http(s)://<host>/api/mcp; with a password set, send `Authorization: Bearer fuobe_…`.+ */+export async function POST(request: Request) {+ // Browsers send Origin: a web page on another site must not reach this server through the+ // user's browser (DNS rebinding, required by the MCP spec). Native clients send none.+ const origin = request.headers.get("origin");+ if (origin && new URL(origin).host !== new URL(request.url).host) {+ return Response.json({ jsonrpc: "2.0", id: null, error: { code: -32000, message: "Origin not allowed" } }, { status: 403 });+ }+ const body = await request.json().catch(() => undefined);+ if (body === undefined) return Response.json({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }, { status: 400 });+ if (Array.isArray(body)) return Response.json({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Batches aren't supported" } }, { status: 400 });+ const res = await handleMcp(body);+ return res ? Response.json(res) : new Response(null, { status: 202 });+}++/** No server-initiated stream: this server only answers requests. */+export function GET() {+ return new Response("Method Not Allowed", { status: 405, headers: { Allow: "POST" } });+}++export function DELETE() {+ return new Response("Method Not Allowed", { status: 405, headers: { Allow: "POST" } });+}diff --git a/src/components/security-settings.tsx b/src/components/security-settings.tsxindex 3530d6dc..3fc68201 100644--- a/src/components/security-settings.tsx+++ b/src/components/security-settings.tsx@@ -87,6 +87,34 @@ function PasswordForm({ status, onDone }: { status: AuthStatus; onDone: () => vo);}+/** How to point an MCP client (Claude Code, Claude Desktop…) at this studio. */+function McpSnippet({ token, needsToken }: { token: string | null; needsToken: boolean }) {+ const [origin] = useState(() => (typeof window === "undefined" ? "http://localhost:3000" : window.location.origin));+ const auth = needsToken ? ` --header "Authorization: Bearer ${token ?? "fuobe_…"}"` : "";+ const cmd = `claude mcp add --transport http fuobe ${origin}/api/mcp${auth}`;+ return (+ <div className="space-y-1.5 sm:w-[36rem]">+ <p className="text-[12px] font-medium">Connect an agent over MCP</p>+ <div className="flex items-center gap-2 rounded-lg bg-muted px-2.5 py-2">+ <code className="min-w-0 flex-1 overflow-x-auto font-mono text-[11px] whitespace-nowrap">{cmd}</code>+ <button+ onClick={() => {+ void navigator.clipboard.writeText(cmd);+ toast("Copied");+ }}+ className="grid size-7 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-background hover:text-foreground"+ aria-label="Copy command"+ >+ <Copy className="size-3.5" />+ </button>+ </div>+ <p className="text-[11px] text-muted-foreground">+ Any MCP client works (streamable HTTP). It can search models, price a plan, generate and fetch results{needsToken ? " — create a token for it first" : ""}.+ </p>+ </div>+ );+}+function Tokens({ status, onChange }: { status: AuthStatus; onChange: () => void }) {const [name, setName] = useState("");const [fresh, setFresh] = useState<string | null>(null);@@ -154,6 +182,7 @@ function Tokens({ status, onChange }: { status: AuthStatus; onChange: () => void))}</ul>)}+ <McpSnippet token={fresh} needsToken={status.enabled} /><div className="flex gap-2 sm:w-[36rem]"><Input placeholder="Token name, e.g. “Claude Desktop”" value={name} onChange={(e) => setName(e.target.value)} /><Button size="sm" variant="secondary" className="h-9" disabled={!name.trim()} onClick={() => void create()}>diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.tsindex 269eb518..f92cb525 100644--- a/src/server/assist/agent.ts+++ b/src/server/assist/agent.ts@@ -8,7 +8,7 @@ import { db } from "../db";import { getGeneration } from "../generations";import { engineMode, getSetting } from "../settings";import { readRef } from "../storage";-import { apiTools, getTool, planFor, type ToolContext } from "./tools";+import { apiTools, executeTool, getTool, planFor, type ToolContext } from "./tools";/*** The Assist agent loop. History is kept exactly as the API returned it (append-only, thinking@@ -362,16 +362,8 @@ export function offlinePlan(message: string, preferred: Engine): { tool: string;// The loopasync function runTool(name: string, input: unknown, ctx: ToolContext): Promise<{ result: Omit<ToolResult, "tool_use_id">; items: AssistItem[] }> {- const tool = getTool(name);- if (!tool) return { result: { type: "tool_result", is_error: true, content: `Unknown tool ${name}` }, items: [] };- const parsed = tool.schema.safeParse(input);- if (!parsed.success) return { result: { type: "tool_result", is_error: true, content: `Invalid input: ${parsed.error.issues.map((i: { path: PropertyKey[]; message: string }) => `${i.path.map(String).join(".")} ${i.message}`).join("; ")}` }, items: [] };- try {- const out = await tool.run(parsed.data, ctx);- return { result: { type: "tool_result", content: out.content, ...(out.isError && { is_error: true }) }, items: out.items ?? [] };- } catch (e) {- return { result: { type: "tool_result", is_error: true, content: (e as Error).message }, items: [] };- }+ const out = await executeTool(name, input, ctx);+ return { result: { type: "tool_result", content: out.content, ...(out.isError && { is_error: true }) }, items: out.items ?? [] };}function ordered(results: ToolResult[], order: string[]): ToolResult[] {diff --git a/src/server/assist/tools.ts b/src/server/assist/tools.tsindex 03e12d22..c894e695 100644--- a/src/server/assist/tools.ts+++ b/src/server/assist/tools.ts@@ -356,7 +356,7 @@ export const TOOLS: ToolDef<any>[] = [searchModels, listElementsTool, listRecentexport const getTool = (name: string) => TOOLS.find((t) => t.name === name);/** JSON Schema for the API: every object closed, constraints the API doesn't take removed (zod still checks them). */-function apiSchema(schema: z.ZodType): Anthropic.Beta.BetaTool.InputSchema {+export function apiSchema(schema: z.ZodType): Anthropic.Beta.BetaTool.InputSchema {const json = z.toJSONSchema(schema) as Record<string, unknown>;const walk = (node: unknown): unknown => {if (Array.isArray(node)) return node.map(walk);@@ -386,3 +386,16 @@ export function planFor(name: string, input: unknown, ctx: ToolContext): { jobs:const jobs = t?.plan?.(input, ctx) ?? [];return { jobs, total: totalCost(jobs) };}++/** Validate and run a tool. Never throws: failures come back as an error result. */+export async function executeTool(name: string, input: unknown, ctx: ToolContext): Promise<ToolOutcome> {+ const tool = getTool(name);+ if (!tool) return { content: `Unknown tool ${name}`, isError: true };+ const parsed = tool.schema.safeParse(input);+ if (!parsed.success) return { content: `Invalid input: ${parsed.error.issues.map((i: { path: PropertyKey[]; message: string }) => `${i.path.map(String).join(".")} ${i.message}`).join("; ")}`, isError: true };+ try {+ return await tool.run(parsed.data, ctx);+ } catch (e) {+ return { content: (e as Error).message, isError: true };+ }+}diff --git a/src/server/mcp.ts b/src/server/mcp.tsnew file mode 100644index 00000000..4fe1cbf8--- /dev/null+++ b/src/server/mcp.ts@@ -0,0 +1,122 @@+import "server-only";+import { z } from "zod";+import { apiSchema, executeTool, getTool, planFor, TOOLS, type ToolContext } from "./assist/tools";+import { engineMode } from "./settings";++/**+ * Fuobe as an MCP server (Model Context Protocol, streamable HTTP transport, stateless):+ * other agents — Claude Desktop, Claude Code, any MCP client — can look up models, price a+ * plan, start generations and fetch results. Same tools as Assist; the client's own approval+ * prompt replaces Assist's plan card, so `estimate_cost` is offered for asking first.+ */++const PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];+const SERVER_INFO = { name: "fuobe", title: "Fuobe studio", version: "1.0.0" };+const INSTRUCTIONS =+ "Fuobe is an AI image, video and audio studio (paid cloud models and open-source ComfyUI workflows). " ++ "Look up models with search_models, price a plan with estimate_cost and tell the user the cost before you call generate or create_storyboard. " ++ "Generations run in the background: poll check_generations (wait_seconds up to 120) for output URLs. Output URLs are paths on this Fuobe server.";++interface JsonRpcRequest {+ jsonrpc: "2.0";+ id?: string | number | null;+ method: string;+ params?: Record<string, unknown>;+}++type JsonRpcResponse = { jsonrpc: "2.0"; id: string | number | null } & ({ result: unknown } | { error: { code: number; message: string; data?: unknown } });++const ok = (id: JsonRpcRequest["id"], result: unknown): JsonRpcResponse => ({ jsonrpc: "2.0", id: id ?? null, result });+const fail = (id: JsonRpcRequest["id"], code: number, message: string): JsonRpcResponse => ({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });++const ctx = (): ToolContext => ({ engine: engineMode() === "open" ? "open" : "cloud" });++const READ_ONLY = new Set(["search_models", "list_elements", "list_recent", "check_generations", "estimate_cost"]);++function toolList() {+ const tools = TOOLS.map((t) => ({+ name: t.name,+ title: t.name.replace(/_/g, " ").replace(/^./, (c) => c.toUpperCase()),+ // Assist's approval card doesn't exist here: say what the call costs instead.+ description: t.gated ? `${t.description.replace(/The app shows the user the plan[^.]*\.( so call this directly instead of asking for confirmation in text\.)?/, "").trim()} Spends money on paid models (or GPU time on open ones): price it with estimate_cost and confirm with the user first.` : t.description,+ inputSchema: apiSchema(t.schema),+ annotations: { readOnlyHint: READ_ONLY.has(t.name), openWorldHint: !!t.gated },+ }));+ const gen = getTool("generate")!;+ tools.push({+ name: "estimate_cost",+ title: "Estimate cost",+ description: "Price a generate call without running it: the model, operation, number of outputs and estimated USD for each job, and whether it would run as a demo (no provider connected). Call it before generate whenever the user hasn't already agreed to a price.",+ inputSchema: apiSchema(gen.schema),+ annotations: { readOnlyHint: true, openWorldHint: false },+ });+ return tools;+}++type Content = { type: "text"; text: string } | { type: "image"; data: string; mimeType: string };++/** Tool output (Anthropic content blocks or a string) → MCP content. */+function toContent(content: unknown): Content[] {+ if (typeof content === "string") return [{ type: "text", text: content }];+ if (!Array.isArray(content)) return [{ type: "text", text: JSON.stringify(content ?? null) }];+ return content.flatMap((b: { type: string; text?: string; source?: { type: string; data?: string; media_type?: string } }): Content[] => {+ if (b.type === "text") return [{ type: "text", text: b.text ?? "" }];+ if (b.type === "image" && b.source?.type === "base64" && b.source.data) return [{ type: "image", data: b.source.data, mimeType: b.source.media_type ?? "image/png" }];+ return [];+ });+}++const CallParams = z.object({ name: z.string(), arguments: z.record(z.string(), z.unknown()).optional() });++async function call(params: unknown) {+ const p = CallParams.safeParse(params);+ if (!p.success) return null;+ const { name, arguments: args = {} } = p.data;+ if (name === "estimate_cost") {+ const plan = planFor("generate", getTool("generate")!.schema.parse(args), ctx());+ return { content: [{ type: "text", text: JSON.stringify(plan) }], structuredContent: plan, isError: plan.jobs.every((j) => j.error) };+ }+ if (!getTool(name)) return undefined;+ const out = await executeTool(name, args, ctx());+ return { content: toContent(out.content), isError: !!out.isError };+}++/** Handle one JSON-RPC message; null for notifications (no response). */+export async function handleMcp(msg: unknown): Promise<JsonRpcResponse | null> {+ const m = msg as JsonRpcRequest;+ if (!m || m.jsonrpc !== "2.0" || typeof m.method !== "string") return fail(null, -32600, "Invalid request");+ const isNotification = m.id === undefined;+ if (isNotification) return null;+ switch (m.method) {+ case "initialize": {+ const asked = String(m.params?.protocolVersion ?? "");+ return ok(m.id, {+ protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],+ capabilities: { tools: { listChanged: false } },+ serverInfo: SERVER_INFO,+ instructions: INSTRUCTIONS,+ });+ }+ case "ping":+ return ok(m.id, {});+ case "tools/list":+ return ok(m.id, { tools: toolList() });+ case "tools/call": {+ try {+ const r = await call(m.params);+ if (r === null) return fail(m.id, -32602, "tools/call needs a name and arguments");+ if (r === undefined) return fail(m.id, -32602, `Unknown tool ${String(m.params?.name)}`);+ return ok(m.id, r);+ } catch (e) {+ // Bad arguments for estimate_cost and the like: a tool error the model can read.+ return ok(m.id, { content: [{ type: "text", text: (e as Error).message }], isError: true });+ }+ }+ case "resources/list":+ return ok(m.id, { resources: [] });+ case "prompts/list":+ return ok(m.id, { prompts: [] });+ default:+ return fail(m.id, -32601, `Method not found: ${m.method}`);+ }+}diff --git a/tests/mcp.test.ts b/tests/mcp.test.tsnew file mode 100644index 00000000..a6651e9e--- /dev/null+++ b/tests/mcp.test.ts@@ -0,0 +1,57 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, describe, expect, it } from "vitest";++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-mcp-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+const { handleMcp } = await import("@/server/mcp");+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++const rpc = (method: string, params?: unknown) => handleMcp({ jsonrpc: "2.0", id: 1, method, params });++describe("MCP server", () => {+ it("negotiates the protocol version", async () => {+ expect(await rpc("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "t", version: "1" } })).toMatchObject({+ result: { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "fuobe" } },+ });+ const r = (await rpc("initialize", { protocolVersion: "1999-01-01" })) as { result: { protocolVersion: string } };+ expect(r.result.protocolVersion).toBe("2025-11-25");+ });++ it("answers requests but not notifications", async () => {+ expect(await handleMcp({ jsonrpc: "2.0", method: "notifications/initialized" })).toBeNull();+ expect(await rpc("ping")).toEqual({ jsonrpc: "2.0", id: 1, result: {} });+ expect(await rpc("nope")).toMatchObject({ error: { code: -32601 } });+ expect(await handleMcp({ method: "ping" })).toMatchObject({ error: { code: -32600 } });+ });++ it("lists the studio's tools with closed schemas and hints", async () => {+ const r = (await rpc("tools/list")) as { result: { tools: { name: string; description: string; inputSchema: { additionalProperties: boolean }; annotations: { readOnlyHint: boolean } }[] } };+ const names = r.result.tools.map((t) => t.name);+ expect(names).toEqual(expect.arrayContaining(["search_models", "generate", "create_storyboard", "check_generations", "estimate_cost"]));+ const gen = r.result.tools.find((t) => t.name === "generate")!;+ expect(gen.annotations.readOnlyHint).toBe(false);+ expect(gen.description).toMatch(/estimate_cost/);+ expect(gen.description).not.toMatch(/approval card|plan card/i);+ expect(r.result.tools.every((t) => t.inputSchema.additionalProperties === false)).toBe(true);+ });++ it("prices a plan without running it, and reports bad input as a tool error", async () => {+ const r = (await rpc("tools/call", { name: "estimate_cost", arguments: { summary: "x", jobs: [{ model_id: "nano-banana-pro", prompt: "fox", outputs: 2 }] } })) as {+ result: { structuredContent: { jobs: { count: number; modelName: string }[] }; isError: boolean };+ };+ expect(r.result.isError).toBe(false);+ expect(r.result.structuredContent.jobs[0]).toMatchObject({ modelName: "Nano Banana Pro", count: 2 });+ expect(await rpc("tools/call", { name: "estimate_cost", arguments: { jobs: "nope" } })).toMatchObject({ result: { isError: true } });+ expect(await rpc("tools/call", { name: "search_models", arguments: { kind: "smell" } })).toMatchObject({ result: { isError: true } });+ expect(await rpc("tools/call", { name: "rm_rf" })).toMatchObject({ error: { code: -32602 } });+ });++ it("runs a tool and returns MCP content", async () => {+ const r = (await rpc("tools/call", { name: "search_models", arguments: { kind: "video", query: "kling" } })) as { result: { content: { type: string; text: string }[] } };+ const body = JSON.parse(r.result.content[0].text) as { models: { id: string }[] };+ expect(body.models[0].id).toMatch(/kling/);+ });+});