Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Accounts 2 fixes: a Read-only token gets MCP's read tools, and tools keep the request's address

Claude68fbcec09594
diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.ts
index 7c4557a5..d4afceac 100644
--- a/src/app/api/mcp/route.ts
+++ b/src/app/api/mcp/route.ts
@@ -1,12 +1,15 @@
import { handleMcp } from "@/server/mcp";
import { currentActor } from "@/server/access/actor";
-import { handler } from "@/server/access/route";
+import { handler, type TokenScope } from "@/server/access/route";
/**
* 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_…`.
+ * Every token scope may call it: a Read-only token is offered the read tools only (handleMcp).
*/
-export const POST = handler({ access: "signed-in" }, async (request: Request) => {
+const READ_AND_UP: TokenScope[] = ["read", "generate", "admin"];
+
+export const POST = handler({ access: "signed-in", scopes: READ_AND_UP }, async (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");
@@ -22,10 +25,10 @@ export const POST = handler({ access: "signed-in" }, async (request: Request) =>
});
/** No server-initiated stream: this server only answers requests. */
-export const GET = handler({ access: "signed-in" }, () => {
+export const GET = handler({ access: "signed-in", scopes: READ_AND_UP }, () => {
return new Response("Method Not Allowed", { status: 405, headers: { Allow: "POST" } });
});
-export const DELETE = handler({ access: "signed-in" }, () => {
+export const DELETE = handler({ access: "signed-in", scopes: READ_AND_UP }, () => {
return new Response("Method Not Allowed", { status: 405, headers: { Allow: "POST" } });
});
diff --git a/src/server/mcp.ts b/src/server/mcp.ts
index abb64c54..1aa41165 100644
--- a/src/server/mcp.ts
+++ b/src/server/mcp.ts
@@ -3,7 +3,9 @@ import { z } from "zod";
// The studio modules behind the studio tools (tools.ts imports them too; named here so MCP never runs without them).
import "./assist/studio-routes";
import { apiSchema, executeTool, getTool, planFor, TOOLS, type ToolContext } from "./assist/tools";
-import { currentActor, runAs, type Actor } from "./access/actor";
+import { currentActor, requestScope, withScope, type Actor } from "./access/actor";
+import { auditDenied, auditHidden } from "./access/audit";
+import { AccessError, NotFoundError } from "./access/errors";
import { engineMode } from "./settings";
import { recipeMarkdown } from "@/lib/recipe";
import { enabledSkills, getSkill, skillRecipe } from "./skills";
@@ -44,6 +46,13 @@ const ctx = (): ToolContext => ({ engine: engineMode() === "open" ? "open" : "cl
const READ_ONLY = new Set(["search_models", "list_elements", "list_recent", "check_generations", "estimate_cost", "estimate_job", "list_skills", "load_skill", "read_source"]);
+/**
+ * Whether the person may run tools that make or change things: a Read-only API token gets the read tools only
+ * (docs/research/accounts-8.md §7.10); a session, the local owner and Full, Generate or Admin tokens get them all.
+ */
+const mayWrite = (actor: Actor) => actor.via !== "token" || actor.scopes.some((s) => s === "full" || s === "generate" || s === "admin");
+const READ_ONLY_REFUSAL = "This API token is Read only: it can look things up but not run tools that make or change things. Create a Generate or Full token in Settings → Security.";
+
/** Gated tools other than generate and create_storyboard (priced with estimate_job). */
const jobTools = () => TOOLS.filter((t) => t.gated && t.plan && !["generate", "create_storyboard", "remember"].includes(t.name)).map((t) => t.name);
@@ -56,8 +65,9 @@ function describe(t: (typeof TOOLS)[number]): string {
return `${base} Spends money on paid models (or GPU time on open ones): ${how} and confirm with the user first.`;
}
-function toolList() {
- const tools: { name: string; title: string; description: string; inputSchema: unknown; annotations: { readOnlyHint: boolean; openWorldHint: boolean } }[] = TOOLS.map((t) => ({
+function toolList(actor: Actor) {
+ const offered = mayWrite(actor) ? TOOLS : TOOLS.filter((t) => READ_ONLY.has(t.name));
+ const tools: { name: string; title: string; description: string; inputSchema: unknown; annotations: { readOnlyHint: boolean; openWorldHint: boolean } }[] = offered.map((t) => ({
name: t.name,
title: t.name.replace(/_/g, " ").replace(/^./, (c) => c.toUpperCase()),
description: describe(t),
@@ -111,6 +121,10 @@ async function call(params: unknown) {
const p = CallParams.safeParse(params);
if (!p.success) return null;
const { name, arguments: args = {} } = p.data;
+ if (!READ_ONLY.has(name) && getTool(name) && !mayWrite(currentActor())) {
+ auditDenied("TOKEN_SCOPE", { tool: name });
+ return { content: [{ type: "text", text: READ_ONLY_REFUSAL }], isError: true };
+ }
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) };
@@ -165,10 +179,10 @@ function promptGet(params: unknown) {
/**
* Handle one JSON-RPC message as `actor` (the person behind the bearer token or session; by default whoever the scope
* says is acting); null for notifications (no response). Everything the message runs — tool calls and what they start —
- * acts for that person.
+ * acts for that person, in the request's scope (its address and browser stay on what the tools audit).
*/
export async function handleMcp(msg: unknown, actor: Actor = currentActor()): Promise<JsonRpcResponse | null> {
- return runAs(actor, () => answer(msg));
+ return withScope({ ...requestScope(), actor }, () => answer(msg));
}
async function answer(msg: unknown): Promise<JsonRpcResponse | null> {
@@ -189,7 +203,7 @@ async function answer(msg: unknown): Promise<JsonRpcResponse | null> {
case "ping":
return ok(m.id, {});
case "tools/list":
- return ok(m.id, { tools: toolList() });
+ return ok(m.id, { tools: toolList(currentActor()) });
case "tools/call": {
try {
const r = await call(m.params);
@@ -197,6 +211,9 @@ async function answer(msg: unknown): Promise<JsonRpcResponse | null> {
if (r === undefined) return fail(m.id, -32602, `Unknown tool ${String(m.params?.name)}`);
return ok(m.id, r);
} catch (e) {
+ // A refusal (no access, over a limit) is audited as handler() would, and told to the model like any tool error.
+ if (e instanceof NotFoundError && e.hidden) auditHidden();
+ if (e instanceof AccessError && e.status === 403) auditDenied(e.code ?? "forbidden", { tool: String(m.params?.name), message: e.message });
// 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 });
}
diff --git a/tests/mcp-actor.test.ts b/tests/mcp-actor.test.ts
index 7baa792d..35284e8f 100644
--- a/tests/mcp-actor.test.ts
+++ b/tests/mcp-actor.test.ts
@@ -14,15 +14,17 @@ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-mcp-actor-"));
process.env.FUOBE_DATA_DIR = dir;
process.env.COMFYUI_URL = "http://127.0.0.1:9";
-/** What each tool call saw: the context's actor and the scope's. */
+/** What each tool call saw: the context's actor and the scope's (and the whole scope). */
const calls: { name: string; ctxActor: unknown; scopeActor: unknown }[] = [];
+const scopes: unknown[] = [];
vi.mock("@/server/assist/tools", async (importOriginal) => {
const real = await importOriginal<typeof import("@/server/assist/tools")>();
- const { maybeActor } = await import("@/server/access/actor");
+ const { maybeActor, requestScope } = await import("@/server/access/actor");
return {
...real,
executeTool: async (name: string, input: unknown, ctx: ToolContext) => {
calls.push({ name, ctxActor: ctx.actor, scopeActor: maybeActor() });
+ scopes.push(requestScope());
return real.executeTool(name, input, ctx);
},
};
@@ -31,7 +33,7 @@ vi.mock("@/server/assist/tools", async (importOriginal) => {
const { handleMcp } = await import("@/server/mcp");
const route = await import("@/app/api/mcp/route");
const { db } = await import("@/server/db");
-const { runAs, SYSTEM, LOCAL_OWNER } = await import("@/server/access/actor");
+const { runAs, withScope, SYSTEM, LOCAL_OWNER } = await import("@/server/access/actor");
const { seedPerson, tokenFor, request, actor, asNobody } = await import("./helpers/actors");
afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
@@ -82,6 +84,41 @@ describe("POST /api/mcp", () => {
expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { headers: { origin: "http://localhost:3000" } })).status).toBe(200);
});
+ it("offers a Read-only token the read tools only, and refuses (and audits) a tool that makes things", async () => {
+ const member = seedPerson();
+ const read = tokenFor(member, ["read"]);
+ const init = await post({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } }, { bearer: read });
+ expect(init.status).toBe(200);
+ const listed = (await (await post({ jsonrpc: "2.0", id: 2, method: "tools/list" }, { bearer: read })).json()) as { result: { tools: { name: string; annotations: { readOnlyHint: boolean } }[] } };
+ const names = listed.result.tools.map((t) => t.name);
+ expect(names).toEqual(expect.arrayContaining(["search_models", "check_generations", "estimate_cost"]));
+ expect(names).not.toContain("generate");
+ expect(listed.result.tools.every((t) => t.annotations.readOnlyHint)).toBe(true);
+ calls.length = 0;
+ expect((await post(call("search_models", { query: "video" }), { bearer: read })).status).toBe(200);
+ expect(calls.map((c) => c.name)).toEqual(["search_models"]);
+ const before = (db().prepare("SELECT COUNT(*) AS n FROM audit_log WHERE action = 'denied'").get() as { n: number }).n;
+ calls.length = 0;
+ const refused = (await (await post(call("generate", { prompt: "a lighthouse", modelId: "nano-banana-pro" }), { bearer: read })).json()) as { result: { isError: boolean; content: { text: string }[] } };
+ expect(refused.result.isError).toBe(true);
+ expect(refused.result.content[0].text).toMatch(/Read only/);
+ expect(calls).toEqual([]);
+ const row = db().prepare("SELECT * FROM audit_log ORDER BY seq DESC LIMIT 1").get() as { action: string; actor_id: string; meta_json: string };
+ expect((db().prepare("SELECT COUNT(*) AS n FROM audit_log WHERE action = 'denied'").get() as { n: number }).n).toBe(before + 1);
+ expect(row).toMatchObject({ action: "denied", actor_id: member });
+ expect(JSON.parse(row.meta_json)).toMatchObject({ reason: "TOKEN_SCOPE", tool: "generate", path: "/api/mcp" });
+ // A Generate token gets them all.
+ const all = (await (await post({ jsonrpc: "2.0", id: 3, method: "tools/list" }, { bearer: tokenFor(member, ["generate"]) })).json()) as { result: { tools: { name: string }[] } };
+ expect(all.result.tools.map((t) => t.name)).toContain("generate");
+ });
+
+ it("keeps the request's address and browser in the scope the tools run in", async () => {
+ const alex = actor(seedPerson(), "member", { via: "token", tokenId: "t9" });
+ scopes.length = 0;
+ await withScope({ actor: LOCAL_OWNER, ip: "203.0.113.9", userAgent: "mcp-client/1", method: "POST", path: "/api/mcp" }, () => handleMcp(call("list_elements"), alex));
+ expect(scopes.at(-1)).toMatchObject({ actor: alex, ip: "203.0.113.9", userAgent: "mcp-client/1", method: "POST", path: "/api/mcp" });
+ });
+
it("ignores an invalid token in Just me on this computer, as the proxy does", async () => {
expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { bearer: "fuobe_wrong" })).status).toBe(200);
});