Skip to content

armgit / kokon

Public Imported from GitHub
0

Edit photos by describing the change, on your own GPU. A free, open-source alternative to Nano Banana and ChatGPT image editing: photos stay on your computer, no daily limit. One installer for Windows, Mac and Linux sets up the best open model (Qwen-Image 2.1). MCP server for AI agents.

MCP: outputs in QLS_MCP_ALLOWED_DIRS folders work, and the error names the variable (#39)

Gabriele Lozupone66d47a195d9f
diff --git a/mcp/src/paths.ts b/mcp/src/paths.ts
index aa86179..f3ee7c9 100644
--- a/mcp/src/paths.ts
+++ b/mcp/src/paths.ts
@@ -19,6 +19,9 @@ export const MAX_INPUT_BYTES = 200 * 1024 * 1024;
export class PathError extends Error {}
+/** How to allow another folder (#39). */
+export const ALLOW_HINT = "To allow it, add the folder to QLS_MCP_ALLOWED_DIRS (separated by semicolons) in the env of the MCP client's config, then restart the client.";
+
function realish(target: string): string {
// Resolve symlinks/junctions on the deepest existing ancestor.
let cur = target;
@@ -64,7 +67,7 @@ export function normalize(raw: string, cwd: string): string {
export function checkInput(raw: string, cwd: string, roots: string[]): string {
const abs = normalize(raw, cwd);
if (!INPUT_EXT.includes(p.extname(abs).toLowerCase())) throw new PathError("Only PNG, JPEG, WebP, BMP, GIF, TIFF and HEIC images are supported.");
- if (!roots.some((r) => isWithin(abs, r))) throw new PathError(`${abs} is outside the allowed folders (${roots.join("; ")}).`);
+ if (!roots.some((r) => isWithin(abs, r))) throw new PathError(`${abs} is outside the allowed folders (${roots.join("; ")}). ${ALLOW_HINT}`);
let st: fs.Stats;
try {
st = fs.statSync(abs);
@@ -81,10 +84,17 @@ export function checkOutput(raw: string, cwd: string, roots: string[]): string {
const ext = p.extname(abs).toLowerCase();
if (!ext) abs += ".png";
else if (!OUTPUT_EXT.includes(ext)) throw new PathError("output_path must end in .png, .jpg or .webp.");
- if (!roots.some((r) => isWithin(abs, r))) throw new PathError(`${abs} is outside the allowed output folders (${roots.join("; ")}).`);
+ if (!roots.some((r) => isWithin(abs, r))) throw new PathError(`${abs} is outside the allowed output folders (${roots.join("; ")}). ${ALLOW_HINT}`);
return abs;
}
+/** The workspace to send with a job: the service writes outputs only to its own output folder
+ * and the workspace, so an output in a QLS_MCP_ALLOWED_DIRS folder sends that folder (#39). */
+export function jobWorkspace(out: string | undefined, cwd: string, roots: string[]): string {
+ if (!out || isWithin(out, cwd)) return cwd;
+ return roots.find((r) => isWithin(out, r)) ?? cwd;
+}
+
export function allowedRoots(cwd: string, outputDir: string | null): string[] {
const extra = (process.env.QLS_MCP_ALLOWED_DIRS ?? "")
.split(";")
diff --git a/mcp/src/tools.ts b/mcp/src/tools.ts
index 30afc95..3a8d7da 100644
--- a/mcp/src/tools.ts
+++ b/mcp/src/tools.ts
@@ -2,7 +2,7 @@
// context with the service client, the project folder and a progress callback.
import { z } from "zod";
-import { allowedRoots, checkInput, checkOutput, PathError } from "./paths.js";
+import { allowedRoots, checkInput, checkOutput, jobWorkspace, PathError } from "./paths.js";
import { ServiceClient, ServiceError } from "./service.js";
const quality = z
@@ -177,7 +177,9 @@ export function label(j: JobView): string {
async function runJob(ctx: ToolContext, body: Record<string, unknown>, includePreview: boolean): Promise<ToolResult> {
// The calling model writes the prompt: Kokon's own prompt writer (Prompt+) never runs for MCP.
- const job = await ctx.client.call<JobView>("POST", "/jobs", { ...body, enhance: false, workspace: ctx.cwd, client: "mcp" });
+ const out = typeof body.output_path === "string" ? body.output_path : undefined;
+ const workspace = out ? jobWorkspace(out, ctx.cwd, await roots(ctx)) : ctx.cwd;
+ const job = await ctx.client.call<JobView>("POST", "/jobs", { ...body, enhance: false, workspace, client: "mcp" });
let last = "";
let cancelled = false;
const onAbort = () => {
diff --git a/mcp/test/paths.test.ts b/mcp/test/paths.test.ts
index 6930978..e2f1e3d 100644
--- a/mcp/test/paths.test.ts
+++ b/mcp/test/paths.test.ts
@@ -2,7 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
-import { checkInput, checkOutput, isWithin, normalize, PathError } from "../src/paths";
+import { checkInput, checkOutput, isWithin, jobWorkspace, normalize, PathError } from "../src/paths";
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "qls-mcp-"));
const proj = path.join(tmp, "proj");
@@ -50,4 +50,14 @@ describe("outputs", () => {
expect(() => checkOutput("../escape.png", proj, roots)).toThrow(/outside/);
expect(() => checkOutput("x.exe", proj, roots)).toThrow(/png/);
});
+ it("says how to allow another folder (#39)", () => {
+ expect(() => checkOutput(path.join(outside, "y.png"), proj, roots)).toThrow(/QLS_MCP_ALLOWED_DIRS \(separated by semicolons\)/);
+ expect(() => checkInput(path.join(outside, "x.png"), proj, roots)).toThrow(/QLS_MCP_ALLOWED_DIRS/);
+ });
+ it("sends the allowed folder an output goes to as the job's workspace", () => {
+ const extra = [proj, outside];
+ expect(jobWorkspace(path.join(proj, "a.png"), proj, extra)).toBe(proj);
+ expect(jobWorkspace(path.join(outside, "sub", "a.png"), proj, extra)).toBe(outside);
+ expect(jobWorkspace(undefined, proj, extra)).toBe(proj);
+ });
});
diff --git a/mcp/test/tools.test.ts b/mcp/test/tools.test.ts
index bcbf405..e1717cb 100644
--- a/mcp/test/tools.test.ts
+++ b/mcp/test/tools.test.ts
@@ -1,3 +1,6 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { handlers, label, schemas, toErrorResult } from "../src/tools";
@@ -56,6 +59,32 @@ describe("input validation", () => {
["x", false, "generate"],
]);
});
+ it("an output in a QLS_MCP_ALLOWED_DIRS folder is sent with that folder as the workspace (#39)", async () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "qls-mcp-ws-"));
+ const [proj, extra] = [path.join(tmp, "proj"), path.join(tmp, "thumbs")];
+ fs.mkdirSync(proj);
+ fs.mkdirSync(extra);
+ const sent: Record<string, unknown>[] = [];
+ const client = {
+ call: async (method: string, p: string, body?: Record<string, unknown>) => {
+ if (p === "/config") return { outputDir: path.join(tmp, "out") };
+ if (method === "POST" && body) sent.push(body);
+ return { id: "j", status: "failed", error: { code: "x", message: "stop here" }, results: [], notes: [], queue_position: 0, plan: null, stage: null, step: null };
+ },
+ };
+ const ctx = { client: client as never, cwd: proj, progress: () => {} };
+ const before = process.env.QLS_MCP_ALLOWED_DIRS;
+ process.env.QLS_MCP_ALLOWED_DIRS = extra;
+ try {
+ await handlers.generate_image({ prompt: "x", output_path: path.join(extra, "Upscaled", "a.png") } as never, ctx);
+ await handlers.generate_image({ prompt: "x", output_path: "a.png" } as never, ctx);
+ await handlers.generate_image({ prompt: "x" } as never, ctx);
+ } finally {
+ if (before === undefined) delete process.env.QLS_MCP_ALLOWED_DIRS;
+ else process.env.QLS_MCP_ALLOWED_DIRS = before;
+ }
+ expect(sent.map((b) => b.workspace)).toEqual([extra, proj, proj]);
+ });
it("width without height is rejected before any service call", async () => {
const ctx = { client: {} as never, cwd: process.cwd(), progress: () => {} };
const res = await handlers.generate_image({ prompt: "x", width: 512 } as never, ctx).catch(toErrorResult);