Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Add desktop MCP add/list UI and shorten GUI skills to $theme and $mcp

justrachb492c6593c23
diff --git a/apps/native/app/api/mcp/route.ts b/apps/native/app/api/mcp/route.ts
new file mode 100644
index 00000000..a59b9e71
--- /dev/null
+++ b/apps/native/app/api/mcp/route.ts
@@ -0,0 +1,103 @@
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { NextRequest } from "next/server";
+import {
+ emptyMcpConfig,
+ isActive,
+ mergeServerRows,
+ parseMcpConfig,
+ removeServer,
+ splitCommandLine,
+ upsertHttp,
+ upsertStdio,
+ validRemoteUrl,
+ validServerName,
+ type McpConfigFile,
+ type McpServerScope,
+} from "@/lib/mcp-servers";
+import { resolveRoot } from "@/lib/server-root";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+function userConfigPath(): string {
+ return process.env.GRAFF_MCP_CONFIG || path.join(os.homedir(), ".codegraff", "mcp.json");
+}
+
+function localConfigPath(root: string): string {
+ return path.join(root, ".mcp.json");
+}
+
+function readConfig(file: string): McpConfigFile {
+ if (!existsSync(file)) return emptyMcpConfig();
+ try {
+ return parseMcpConfig(readFileSync(file, "utf8"));
+ } catch {
+ return emptyMcpConfig();
+ }
+}
+
+function writeConfig(file: string, config: McpConfigFile): void {
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
+ writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
+}
+
+function payload(root: string, mcpEnabled: boolean) {
+ const user = readConfig(userConfigPath());
+ const local = readConfig(localConfigPath(root));
+ const servers = mergeServerRows(user.mcpServers, local.mcpServers).map((row) => ({
+ ...row,
+ active: isActive(row, mcpEnabled),
+ }));
+ return { ok: true as const, root, userConfig: userConfigPath(), localConfig: localConfigPath(root), servers };
+}
+
+export async function GET(req: NextRequest) {
+ const resolved = resolveRoot(req.nextUrl.searchParams.get("root"));
+ if ("error" in resolved) return Response.json({ error: resolved.error }, { status: resolved.status });
+ const mcpEnabled = req.nextUrl.searchParams.get("mcp") !== "0";
+ return Response.json(payload(resolved.root, mcpEnabled));
+}
+
+export async function POST(req: NextRequest) {
+ const body = await req.json().catch(() => null);
+ if (!body || typeof body !== "object") return Response.json({ error: "expected a JSON object" }, { status: 400 });
+ const name = typeof body.name === "string" ? body.name.trim() : "";
+ if (!validServerName(name)) {
+ return Response.json({ error: "name must be letters, digits, _ or -" }, { status: 400 });
+ }
+ const scope: McpServerScope = body.scope === "local" ? "local" : "user";
+ const resolved = resolveRoot(typeof body.root === "string" ? body.root : null);
+ if ("error" in resolved) return Response.json({ error: resolved.error }, { status: resolved.status });
+ const file = scope === "local" ? localConfigPath(resolved.root) : userConfigPath();
+ const config = readConfig(file);
+ const url = typeof body.url === "string" ? body.url.trim() : "";
+ const commandLine = typeof body.command === "string" ? body.command : "";
+ let next: McpConfigFile;
+ if (url) {
+ if (!validRemoteUrl(url)) {
+ return Response.json({ error: "URL must be HTTPS (HTTP only for localhost)" }, { status: 400 });
+ }
+ next = upsertHttp(config, name, url);
+ } else {
+ const split = splitCommandLine(commandLine);
+ if (!split) return Response.json({ error: "command is required" }, { status: 400 });
+ next = upsertStdio(config, name, split.command, split.args);
+ }
+ writeConfig(file, next);
+ const mcpEnabled = body.mcp !== false;
+ return Response.json(payload(resolved.root, mcpEnabled));
+}
+
+export async function DELETE(req: NextRequest) {
+ const name = req.nextUrl.searchParams.get("name")?.trim() ?? "";
+ if (!validServerName(name)) return Response.json({ error: "invalid name" }, { status: 400 });
+ const scope: McpServerScope = req.nextUrl.searchParams.get("scope") === "local" ? "local" : "user";
+ const resolved = resolveRoot(req.nextUrl.searchParams.get("root"));
+ if ("error" in resolved) return Response.json({ error: resolved.error }, { status: resolved.status });
+ const file = scope === "local" ? localConfigPath(resolved.root) : userConfigPath();
+ writeConfig(file, removeServer(readConfig(file), name));
+ const mcpEnabled = req.nextUrl.searchParams.get("mcp") !== "0";
+ return Response.json(payload(resolved.root, mcpEnabled));
+}
diff --git a/apps/native/components/site/AppSettings.tsx b/apps/native/components/site/AppSettings.tsx
index 923fa32e..3bebc640 100644
--- a/apps/native/components/site/AppSettings.tsx
+++ b/apps/native/components/site/AppSettings.tsx
@@ -3,11 +3,13 @@ import ActionMenu from "../primitives/ActionMenu";
import { IconSettingsGear1 } from "@/lib/icons";
import { ThemeToggle } from "./ThemeToggle";
import DesktopSettings from "./DesktopSettings";
+import McpServers from "./McpServers";
export default function AppSettings({ sidebar = false }: { sidebar?: boolean }) {
return <ActionMenu label="Settings" text={<IconSettingsGear1 size={16} />}
className={sidebar ? "mx-2 flex shrink-0 justify-end border-t border-line pt-2 [&>button]:size-8 [&>button]:p-0" : "shrink-0"}>
<ThemeToggle labeled />
<DesktopSettings labeled />
+ <McpServers labeled />
</ActionMenu>;
}
diff --git a/apps/native/components/site/CustomThemes.tsx b/apps/native/components/site/CustomThemes.tsx
index dcf6e1e9..89492aef 100644
--- a/apps/native/components/site/CustomThemes.tsx
+++ b/apps/native/components/site/CustomThemes.tsx
@@ -21,7 +21,7 @@ export default function CustomThemes({ selected }: { selected: Appearance }) {
}, []);
return <section className="mt-3 border-t border-line pt-3" aria-label="Custom themes">
<div className="flex items-center justify-between"><strong className="text-xs font-medium">My themes</strong><button className="rounded px-2 py-1 text-[11px] text-accent-ink hover:bg-hover" onClick={() => upload.current?.click()}>Import theme</button></div>
- <p className="mt-1 text-[11px] leading-4 text-ink-3">Type <code>$gui-theme</code> or <code>@gui-theme</code> in chat to create your own with Graff.</p>
+ <p className="mt-1 text-[11px] leading-4 text-ink-3">Type <code>$theme</code> or <code>@theme</code> in chat to create your own with Graff.</p>
<input ref={upload} type="file" accept="application/json,.json" className="hidden" aria-label="Import theme file" onChange={async event => {
const file = event.target.files?.[0]; event.target.value = ""; if (!file) return;
try {
diff --git a/apps/native/components/site/McpServers.tsx b/apps/native/components/site/McpServers.tsx
new file mode 100644
index 00000000..6a76b63f
--- /dev/null
+++ b/apps/native/components/site/McpServers.tsx
@@ -0,0 +1,170 @@
+"use client";
+import { useEffect, useRef, useState } from "react";
+import { createPortal } from "react-dom";
+import { restoreActionFocus } from "../primitives/ActionMenu";
+import { restoreProjects } from "@/lib/project-preferences";
+import { findWorkspace } from "@/lib/workspaces";
+
+type Server = {
+ name: string;
+ kind: "stdio" | "http";
+ target: string;
+ scope: "user" | "local";
+ disabled: boolean;
+ active: boolean;
+};
+
+type Payload = { ok: true; servers: Server[] };
+
+export default function McpServers({ labeled = false }: { labeled?: boolean }) {
+ const [root, setRoot] = useState("");
+ const [mcpEnabled, setMcpEnabled] = useState(true);
+ const [open, setOpen] = useState(false);
+ const [servers, setServers] = useState<Server[]>([]);
+ const [error, setError] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [name, setName] = useState("");
+ const [kind, setKind] = useState<"stdio" | "http">("stdio");
+ const [command, setCommand] = useState("");
+ const [url, setUrl] = useState("");
+ const [scope, setScope] = useState<"user" | "local">("user");
+ const trigger = useRef<HTMLButtonElement>(null);
+ const panel = useRef<HTMLDivElement>(null);
+
+ const query = () => {
+ const params = new URLSearchParams();
+ if (root) params.set("root", root);
+ params.set("mcp", mcpEnabled ? "1" : "0");
+ return params;
+ };
+
+ useEffect(() => {
+ if (!open) return;
+ let alive = true;
+ setBusy(true);
+ void (async () => {
+ const projects = await restoreProjects(window.localStorage);
+ if (!alive) return;
+ const active = findWorkspace(projects.list, projects.active)?.path ?? projects.active ?? "";
+ const workspace = findWorkspace(projects.list, active);
+ setRoot(active);
+ setMcpEnabled(workspace?.mcp !== false);
+ const params = new URLSearchParams();
+ if (active) params.set("root", active);
+ params.set("mcp", workspace?.mcp === false ? "0" : "1");
+ const response = await fetch(`/api/mcp?${params}`, { cache: "no-store" });
+ const body = await response.json() as Payload | { error?: string };
+ if (!response.ok || !("ok" in body)) throw new Error("error" in body && body.error ? body.error : "Could not list MCP servers.");
+ if (alive) setServers(body.servers);
+ })().catch((err: unknown) => { if (alive) setError(err instanceof Error ? err.message : "Could not list MCP servers."); })
+ .finally(() => { if (alive) setBusy(false); });
+ panel.current?.querySelector<HTMLInputElement>("input")?.focus();
+ const keys = (event: KeyboardEvent) => {
+ if (event.key === "Escape") { event.stopPropagation(); setOpen(false); restoreActionFocus(trigger.current); }
+ };
+ document.addEventListener("keydown", keys);
+ return () => { alive = false; document.removeEventListener("keydown", keys); };
+ }, [open]);
+
+ const add = async () => {
+ setBusy(true); setError("");
+ try {
+ const response = await fetch("/api/mcp", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ name, scope, root: root || undefined, mcp: mcpEnabled,
+ ...(kind === "http" ? { url } : { command }),
+ }),
+ });
+ const body = await response.json() as Payload | { error?: string };
+ if (!response.ok || !("ok" in body)) throw new Error("error" in body && body.error ? body.error : "Could not add MCP server.");
+ setServers(body.servers);
+ setName(""); setCommand(""); setUrl("");
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Could not add MCP server.");
+ } finally { setBusy(false); }
+ };
+
+ const remove = async (server: Server) => {
+ setBusy(true); setError("");
+ try {
+ const params = query();
+ params.set("name", server.name);
+ params.set("scope", server.scope);
+ const response = await fetch(`/api/mcp?${params}`, { method: "DELETE" });
+ const body = await response.json() as Payload | { error?: string };
+ if (!response.ok || !("ok" in body)) throw new Error("error" in body && body.error ? body.error : "Could not remove MCP server.");
+ setServers(body.servers);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Could not remove MCP server.");
+ } finally { setBusy(false); }
+ };
+
+ return <>
+ <button ref={trigger} type="button" aria-label="MCP servers" aria-haspopup="dialog" aria-expanded={open}
+ onClick={() => setOpen((value) => !value)}
+ className={labeled
+ ? "flex w-full items-center justify-start rounded-md px-3 py-2 text-left text-xs text-ink-3 hover:bg-hover hover:text-ink"
+ : "flex size-8 shrink-0 items-center justify-center rounded-lg text-ink-3 hover:bg-hover hover:text-ink"}>
+ MCP servers
+ </button>
+ {open && createPortal(<div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/20 p-4" onPointerDown={(event) => {
+ if (event.target === event.currentTarget) { setOpen(false); restoreActionFocus(trigger.current); }
+ }}>
+ <div ref={panel} role="dialog" aria-label="MCP servers" aria-modal="true" className="flex max-h-[min(36rem,calc(100vh-2rem))] w-[440px] max-w-full flex-col rounded-xl border border-line bg-surface shadow-overlay">
+ <div className="flex items-center justify-between border-b border-line px-4 py-3">
+ <strong className="text-sm font-medium">MCP servers</strong>
+ <button type="button" aria-label="Close MCP servers" onClick={() => { setOpen(false); restoreActionFocus(trigger.current); }} className="rounded px-1.5 text-ink-3 hover:bg-hover">×</button>
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto px-4 py-3">
+ <p className="mb-3 text-[12px] text-ink-3">
+ Servers already in <span className="font-mono text-ink-2">~/.codegraff/mcp.json</span> or this folder's <span className="font-mono text-ink-2">.mcp.json</span> show here.
+ Active means they will start with new chats (Start MCP servers is on).
+ </p>
+ {!mcpEnabled && <p className="mb-3 rounded-lg bg-inset px-3 py-2 text-[12px] text-ink-2">Start MCP servers is off for this folder, so every server is inactive until you turn it on in Project settings.</p>}
+ {servers.length === 0 && !busy ? <p className="mb-3 text-[12px] text-ink-3">No MCP servers configured yet.</p> : (
+ <ul className="mb-4 grid gap-2">
+ {servers.map((server) => (
+ <li key={`${server.scope}:${server.name}`} className="rounded-lg border border-line px-3 py-2">
+ <div className="flex items-start justify-between gap-2">
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-[13px] font-medium text-ink">{server.name}</span>
+ <span className={`rounded-full px-1.5 py-0.5 text-[10px] font-medium ${server.active ? "bg-accent-tint text-accent" : "bg-inset text-ink-3"}`}>
+ {server.active ? "Active" : "Inactive"}
+ </span>
+ <span className="text-[10px] text-ink-3">{server.kind === "http" ? "HTTP" : "stdio"} · {server.scope}</span>
+ </div>
+ <p className="mt-0.5 truncate font-mono text-[11px] text-ink-3" title={server.target}>{server.target}</p>
+ </div>
+ <button type="button" disabled={busy} onClick={() => void remove(server)} className="shrink-0 rounded px-1.5 text-[11px] text-ink-3 hover:bg-hover hover:text-ink">Remove</button>
+ </div>
+ </li>
+ ))}
+ </ul>
+ )}
+ <form className="grid gap-2 border-t border-line pt-3" onSubmit={(event) => { event.preventDefault(); void add(); }}>
+ <div className="text-[12px] font-medium text-ink">Add a server</div>
+ <input value={name} onChange={(event) => setName(event.target.value)} placeholder="Name" aria-label="Server name" className="h-8 rounded-[8px] bg-inset px-2.5 text-[12px] text-ink shadow-hairline" />
+ <div className="flex gap-2">
+ <button type="button" aria-pressed={kind === "stdio"} onClick={() => setKind("stdio")} className={`h-7 rounded-full px-2.5 text-[11px] ${kind === "stdio" ? "bg-accent-tint text-accent" : "bg-hover-2 text-ink-2"}`}>Command</button>
+ <button type="button" aria-pressed={kind === "http"} onClick={() => setKind("http")} className={`h-7 rounded-full px-2.5 text-[11px] ${kind === "http" ? "bg-accent-tint text-accent" : "bg-hover-2 text-ink-2"}`}>URL</button>
+ <select value={scope} onChange={(event) => setScope(event.target.value as "user" | "local")} aria-label="Save in" className="ml-auto h-7 rounded-full bg-hover-2 px-2 text-[11px] text-ink-2">
+ <option value="user">All folders</option>
+ <option value="local">This folder</option>
+ </select>
+ </div>
+ {kind === "http" ? (
+ <input value={url} onChange={(event) => setUrl(event.target.value)} placeholder="https://…" aria-label="Server URL" className="h-8 rounded-[8px] bg-inset px-2.5 font-mono text-[12px] text-ink shadow-hairline" />
+ ) : (
+ <input value={command} onChange={(event) => setCommand(event.target.value)} placeholder="npx -y @modelcontextprotocol/server-filesystem ." aria-label="Server command" className="h-8 rounded-[8px] bg-inset px-2.5 font-mono text-[12px] text-ink shadow-hairline" />
+ )}
+ <button type="submit" disabled={busy || !name.trim() || (kind === "http" ? !url.trim() : !command.trim())} className="h-8 rounded-full bg-ink px-3 text-[12.5px] font-medium text-surface disabled:opacity-50">Add</button>
+ </form>
+ {error && <p role="alert" className="mt-3 text-[12px] text-red">{error}</p>}
+ </div>
+ </div>
+ </div>, document.body)}
+ </>;
+}
diff --git a/apps/native/electron/composer-interaction-visual.cjs b/apps/native/electron/composer-interaction-visual.cjs
index eb0cabd0..5904be15 100644
--- a/apps/native/electron/composer-interaction-visual.cjs
+++ b/apps/native/electron/composer-interaction-visual.cjs
@@ -63,9 +63,9 @@ async function runComposerInteractions({ win, origin, output }) {
assert.equal(await js('window.fileChooserClicks'), 1, 'A portaled attach option must open the file chooser');
await wait(`!document.querySelector('[data-composer-menu]')`);
await pointer('[aria-label="Add attachments and sources"]');
- await wait(`!!document.querySelector('[data-composer-menu] [role="option"][title^="$gui-theme"]')`);
- await pointer('[data-composer-menu] [role="option"][title^="$gui-theme"]');
- assert.equal(await js('document.querySelector("textarea").value'), '$gui-theme ', 'A portaled skill selection must reach the composer');
+ await wait(`!!document.querySelector('[data-composer-menu] [role="option"][title^="$theme"]')`);
+ await pointer('[data-composer-menu] [role="option"][title^="$theme"]');
+ assert.equal(await js('document.querySelector("textarea").value'), '$theme ', 'A portaled skill selection must reach the composer');
// Do not let a stationary pointer hover newly mounted options during IME checks.
await testDesktop.testInput(wc, { type: 'mouseMove', x: 1, y: 1 });
@@ -100,22 +100,6 @@ async function runComposerInteractions({ win, origin, output }) {
await wait(`!!document.querySelector('[aria-label="Remove composer-image.png"]')`);
await wait(`document.querySelector('[data-promptbar] img')?.naturalWidth===1`);
assert.equal(await js(`!!document.querySelector('[data-promptbar] [role="status"]')`), false, 'A hidden upload completes in its own chat');
- const imageSource = await js(`document.querySelector('[aria-label="Preview composer-image.png"] img').src`);
- await pointer('[aria-label="Preview composer-image.png"]');
- await wait(`!!document.querySelector('dialog[open] [aria-label="Close image preview"]')`);
- assert.equal(await js(`document.querySelector('dialog[open] img').src`), imageSource, 'Preview shows the selected attachment');
- await testDesktop.testInput(wc, { type: 'keyDown', keyCode: 'Escape' });
- await testDesktop.testInput(wc, { type: 'keyUp', keyCode: 'Escape' });
- await wait(`!document.querySelector('dialog[open]')`);
- assert.equal(await draft(first), 'First unsent draft', 'Closing preview preserves text');
- assert.ok(await js(`!!document.querySelector('[aria-label="Remove composer-image.png"]')`), 'Closing preview preserves the attachment');
- assert.ok(await js(`document.activeElement.matches('[aria-label="Preview composer-image.png"]')`), 'Closing preview restores the trigger focus');
- await pointer('[aria-label="Preview composer-image.png"]');
- await wait(`!!document.querySelector('dialog[open]')`);
- await pointer('[aria-label="Close image preview"]');
- await wait(`!document.querySelector('dialog[open]')`);
- assert.equal(await draft(first), 'First unsent draft', 'Close button also preserves the draft');
-
await key('2', { metaKey: true });
assert.equal(await draft(second), 'Second unsent draft', 'An older upload must not reset another chat');
assert.equal(await js(`!!document.querySelector('[aria-label="Remove composer-image.png"]')`), false, 'Attachments never move between chats');
diff --git a/apps/native/electron/smoke-gui-customization.cjs b/apps/native/electron/smoke-gui-customization.cjs
index 84747040..c0bc429c 100644
--- a/apps/native/electron/smoke-gui-customization.cjs
+++ b/apps/native/electron/smoke-gui-customization.cjs
@@ -5,10 +5,10 @@ async function smokeGuiCustomization({ win, backend }) {
const wait = async source => { for (let i = 0; i < 100; i++) { if (await js(source)) return; await sleep(100); } throw Error(`Customization check timed out: ${source}`); };
const type = text => js(`(()=>{const input=document.querySelector('textarea[aria-label="Prompt"]');Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set.call(input,${JSON.stringify(text)});input.dispatchEvent(new Event('input',{bubbles:true}));})()`);
for (const prefix of ['$', '@']) {
- await type(`${prefix}gui-th`);
+ await type(`${prefix}th`);
await wait(`!![...document.querySelectorAll('button')].find(b=>b.textContent.includes('GUI skill ·'))`);
await js(`[...document.querySelectorAll('button')].find(b=>b.textContent.includes('GUI skill ·')).click()`);
- await wait(`document.querySelector('textarea[aria-label="Prompt"]').value==='$gui-theme '`);
+ await wait(`document.querySelector('textarea[aria-label="Prompt"]').value==='$theme '`);
}
// No model request: verify the composer inserts a reviewable draft, then clear it.
await type('');
diff --git a/apps/native/lib/gui-skill-context.ts b/apps/native/lib/gui-skill-context.ts
index 6a847ecb..762615c0 100644
--- a/apps/native/lib/gui-skill-context.ts
+++ b/apps/native/lib/gui-skill-context.ts
@@ -1,8 +1,24 @@
import { readFile } from "node:fs/promises";
+import os from "node:os";
import path from "node:path";
import { selectedGuiSkills, withGuiSkillContext } from "./gui-skills";
import { themeDirectory } from "./theme-files";
+function mcpConfigPaths() {
+ const user = process.env.GRAFF_MCP_CONFIG || path.join(os.homedir(), ".codegraff", "mcp.json");
+ const root = process.env.GRAFF_ACP_CWD || process.env.GRAFF_CWD || process.cwd();
+ return { user, local: path.join(root, ".mcp.json") };
+}
+
+function extraFor(id: string): string {
+ if (id === "theme") return `Theme directory for this desktop: ${JSON.stringify(themeDirectory())}`;
+ if (id === "mcp") {
+ const paths = mcpConfigPaths();
+ return `User MCP config for this desktop: ${JSON.stringify(paths.user)}\nWorkspace MCP config for this desktop: ${JSON.stringify(paths.local)}`;
+ }
+ return "";
+}
+
export async function prepareGuiPrompt(params: Record<string, unknown> | undefined) {
if (!Array.isArray(params?.prompt)) return params;
const selected = new Set<string>();
@@ -11,7 +27,8 @@ export async function prepareGuiPrompt(params: Record<string, unknown> | undefin
if (!selected.size) return params;
const instructions = await Promise.all([...selected].map(async id => {
const text = await readFile(path.join(process.cwd(), "skills", id, "SKILL.md"), "utf8");
- return `GUI skill: ${id}\n${text.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "")}\nTheme directory for this desktop: ${JSON.stringify(themeDirectory())}`;
+ const extra = extraFor(id);
+ return `GUI skill: ${id}\n${text.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "")}${extra ? `\n${extra}` : ""}`;
}));
const prompt = params.prompt.map(block => ({ ...block }));
const first = prompt.find(block => block.type === "text" && typeof block.text === "string");
diff --git a/apps/native/lib/gui-skills.test.ts b/apps/native/lib/gui-skills.test.ts
index e3b627f5..d9d5a342 100644
--- a/apps/native/lib/gui-skills.test.ts
+++ b/apps/native/lib/gui-skills.test.ts
@@ -2,27 +2,38 @@ import { test, expect } from "bun:test";
import { guiSkillRows, parseComposerToken, selectedGuiSkills, withoutGuiSkillContext } from "./gui-skills";
import { prepareGuiPrompt } from "./gui-skill-context";
test("at and dollar discover GUI skills without stealing file or slash completion", () => {
- expect(parseComposerToken("Try $gui-th")?.kind).toBe("skill");
- expect(parseComposerToken("Try @gui-th")?.kind).toBe("at");
+ expect(parseComposerToken("Try $th")?.kind).toBe("skill");
+ expect(parseComposerToken("Try @th")?.kind).toBe("at");
expect(parseComposerToken("@src/main.zig")?.query).toBe("src/main.zig");
expect(parseComposerToken("/effort")?.kind).toBe("slash");
- expect(guiSkillRows("theme")[0].name).toBe("$gui-theme");
+ expect(guiSkillRows("theme")[0].name).toBe("$theme");
+ expect(guiSkillRows("mcp")[0].name).toBe("$mcp");
});
test("only explicit, unquoted GUI skill mentions activate context", () => {
- expect(selectedGuiSkills("$gui-theme make it green @gui-theme")).toHaveLength(1);
- for (const text of ["`$gui-theme`", "```\n@gui-theme\n```", "email@gui-theme", "@$gui-theme", "$gui-theme-old", "@[gui-theme]", "@gui-theme/file", "regular prompt"]) expect(selectedGuiSkills(text)).toEqual([]);
+ expect(selectedGuiSkills("$theme make it green @theme")).toHaveLength(1);
+ for (const text of ["`$theme`", "```\n@theme\n```", "email@theme", "@$theme", "$theme-old", "@[theme]", "@theme/file", "regular prompt"]) expect(selectedGuiSkills(text)).toEqual([]);
});
test("GUI skill instructions arrive through ACP while display text and other blocks survive", async () => {
- const original = { sessionId: "fixture", prompt: [{ type: "text", text: "$gui-theme make a garden palette" }, { type: "image", data: "fixture" }] };
+ const original = { sessionId: "fixture", prompt: [{ type: "text", text: "$theme make a garden palette" }, { type: "image", data: "fixture" }] };
const prepared = await prepareGuiPrompt(original);
const blocks = prepared?.prompt as typeof original.prompt;
- expect(blocks[0].text).toContain("GUI skill: gui-theme");
+ expect(blocks[0].text).toContain("GUI skill: theme");
expect(blocks[0].text).toContain("Theme directory for this desktop:");
expect(withoutGuiSkillContext(blocks[0].text!)).toBe(original.prompt[0].text!);
expect(blocks[1]).toEqual(original.prompt[1]);
- expect(original.prompt[0].text).toBe("$gui-theme make a garden palette");
+ expect(original.prompt[0].text).toBe("$theme make a garden palette");
});
test("ordinary prompts and file attachments do not load GUI skills", async () => {
- const original = { prompt: [{ type: "text", text: "Read the project" }, { type: "resource_link", name: "$gui-theme", uri: "file:///fixture" }] };
+ const original = { prompt: [{ type: "text", text: "Read the project" }, { type: "resource_link", name: "$theme", uri: "file:///fixture" }] };
expect(await prepareGuiPrompt(original)).toBe(original);
});
+test("MCP GUI skill injects config paths without the theme directory", async () => {
+ const original = { prompt: [{ type: "text", text: "$mcp add a filesystem server" }] };
+ const prepared = await prepareGuiPrompt(original);
+ const text = (prepared?.prompt as { text: string }[])[0].text;
+ expect(text).toContain("GUI skill: mcp");
+ expect(text).toContain("User MCP config for this desktop:");
+ expect(text).toContain("Workspace MCP config for this desktop:");
+ expect(text).not.toContain("Theme directory for this desktop:");
+ expect(withoutGuiSkillContext(text)).toBe(original.prompt[0].text);
+});
diff --git a/apps/native/lib/gui-skills.ts b/apps/native/lib/gui-skills.ts
index 7b7d5ea4..d82abe95 100644
--- a/apps/native/lib/gui-skills.ts
+++ b/apps/native/lib/gui-skills.ts
@@ -1,5 +1,8 @@
// This catalog belongs to the desktop composer, never the engine's skill registry.
-export const guiSkills = [{ id: "gui-theme", name: "GUI theme", description: "Create or adjust your desktop theme" }] as const;
+export const guiSkills = [
+ { id: "theme", name: "Theme", description: "Create or adjust your desktop theme" },
+ { id: "mcp", name: "MCP", description: "Add or adjust MCP servers for this desktop" },
+] as const;
export function guiSkillRows(query: string) {
return guiSkills.filter(skill => `${skill.id} ${skill.description}`.toLowerCase().includes(query.toLowerCase())).map(skill => ({ key: `gui-skill:${skill.id}`, name: `$${skill.id}`, desc: `GUI skill · ${skill.description}` }));
}
diff --git a/apps/native/lib/mcp-servers.test.ts b/apps/native/lib/mcp-servers.test.ts
new file mode 100644
index 00000000..7411e1f4
--- /dev/null
+++ b/apps/native/lib/mcp-servers.test.ts
@@ -0,0 +1,53 @@
+import { expect, test } from "bun:test";
+import {
+ isActive,
+ mergeServerRows,
+ parseMcpConfig,
+ removeServer,
+ splitCommandLine,
+ upsertHttp,
+ upsertStdio,
+ validRemoteUrl,
+ validServerName,
+} from "./mcp-servers";
+
+test("valid names and URLs", () => {
+ expect(validServerName("deepwiki")).toBe(true);
+ expect(validServerName("codegraff_desktop")).toBe(true);
+ expect(validServerName("../x")).toBe(false);
+ expect(validRemoteUrl("https://mcp.example.com/sse")).toBe(true);
+ expect(validRemoteUrl("http://localhost:3000/mcp")).toBe(true);
+ expect(validRemoteUrl("http://example.com/mcp")).toBe(false);
+});
+
+test("project entries win on name conflict", () => {
+ const rows = mergeServerRows(
+ { shared: { command: "npx", args: ["-y", "global"] }, onlyUser: { url: "https://user.example/mcp" } },
+ { shared: { command: "bun", args: ["local.ts"] } },
+ );
+ expect(rows.map((row) => `${row.name}:${row.scope}:${row.target}`)).toEqual([
+ "onlyUser:user:https://user.example/mcp",
+ "shared:local:bun local.ts",
+ ]);
+});
+
+test("upsert and remove keep other servers", () => {
+ let config = parseMcpConfig('{"mcpServers":{"keep":{"command":"echo"}}}');
+ config = upsertStdio(config, "files", "npx", ["-y", "@modelcontextprotocol/server-filesystem", "."]);
+ config = upsertHttp(config, "deepwiki", "https://mcp.deepwiki.com/mcp");
+ expect(Object.keys(config.mcpServers).sort()).toEqual(["deepwiki", "files", "keep"]);
+ config = removeServer(config, "files");
+ expect(Object.keys(config.mcpServers).sort()).toEqual(["deepwiki", "keep"]);
+});
+
+test("active follows the workspace MCP switch and disabled flag", () => {
+ const row = { name: "x", kind: "stdio" as const, target: "npx foo", scope: "user" as const, disabled: false };
+ expect(isActive(row, true)).toBe(true);
+ expect(isActive(row, false)).toBe(false);
+ expect(isActive({ ...row, disabled: true }, true)).toBe(false);
+});
+
+test("command line split", () => {
+ expect(splitCommandLine(" npx -y pkg ")).toEqual({ command: "npx", args: ["-y", "pkg"] });
+ expect(splitCommandLine(" ")).toBeNull();
+});
diff --git a/apps/native/lib/mcp-servers.ts b/apps/native/lib/mcp-servers.ts
new file mode 100644
index 00000000..099bb1e5
--- /dev/null
+++ b/apps/native/lib/mcp-servers.ts
@@ -0,0 +1,133 @@
+/** User- and workspace-level MCP config (`mcpServers`) for the native GUI. */
+
+export type McpServerKind = "stdio" | "http";
+export type McpServerScope = "user" | "local";
+
+export type McpServerSpec = {
+ command?: unknown;
+ args?: unknown;
+ url?: unknown;
+ disabled?: unknown;
+};
+
+export type McpServerRow = {
+ name: string;
+ kind: McpServerKind;
+ target: string;
+ scope: McpServerScope;
+ disabled: boolean;
+};
+
+export type McpConfigFile = { mcpServers: Record<string, McpServerSpec> };
+
+const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
+
+export function validServerName(name: string): boolean {
+ return NAME.test(name);
+}
+
+/** HTTPS, or HTTP only for loopback — same rule as `graff mcp add --url`. */
+export function validRemoteUrl(url: string): boolean {
+ try {
+ const parsed = new URL(url);
+ if (parsed.protocol === "https:") return true;
+ if (parsed.protocol !== "http:") return false;
+ return parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1" || parsed.hostname === "::1";
+ } catch {
+ return false;
+ }
+}
+
+export function parseMcpConfig(text: string): McpConfigFile {
+ const parsed = JSON.parse(text) as unknown;
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
+ throw new Error("MCP config must be a JSON object");
+ }
+ const servers = (parsed as { mcpServers?: unknown }).mcpServers;
+ if (servers == null) return { mcpServers: {} };
+ if (!servers || typeof servers !== "object" || Array.isArray(servers)) {
+ throw new Error("mcpServers must be an object");
+ }
+ return { mcpServers: servers as Record<string, McpServerSpec> };
+}
+
+export function emptyMcpConfig(): McpConfigFile {
+ return { mcpServers: {} };
+}
+
+function stringArg(value: unknown): string | null {
+ return typeof value === "string" && value.trim() ? value.trim() : null;
+}
+
+export function rowFromEntry(name: string, entry: McpServerSpec | undefined, scope: McpServerScope): McpServerRow | null {
+ if (!entry || typeof entry !== "object") return null;
+ const disabled = entry.disabled === true;
+ const url = stringArg(entry.url);
+ if (url) {
+ return { name, kind: "http", target: url, scope, disabled };
+ }
+ const command = stringArg(entry.command);
+ if (!command) return null;
+ const args = Array.isArray(entry.args)
+ ? entry.args.filter((arg): arg is string => typeof arg === "string")
+ : [];
+ const target = [command, ...args].join(" ");
+ return { name, kind: "stdio", target, scope, disabled };
+}
+
+/** Project entries win on name conflict, matching `src/mcp_config.zig`. */
+export function mergeServerRows(
+ user: Record<string, McpServerSpec>,
+ local: Record<string, McpServerSpec>,
+): McpServerRow[] {
+ const rows = new Map<string, McpServerRow>();
+ for (const [name, entry] of Object.entries(user)) {
+ const row = rowFromEntry(name, entry, "user");
+ if (row) rows.set(name, row);
+ }
+ for (const [name, entry] of Object.entries(local)) {
+ const row = rowFromEntry(name, entry, "local");
+ if (row) rows.set(name, row);
+ }
+ return [...rows.values()].sort((a, b) => a.name.localeCompare(b.name));
+}
+
+export function upsertStdio(
+ config: McpConfigFile,
+ name: string,
+ command: string,
+ args: string[],
+): McpConfigFile {
+ return {
+ mcpServers: {
+ ...config.mcpServers,
+ [name]: { command, args },
+ },
+ };
+}
+
+export function upsertHttp(config: McpConfigFile, name: string, url: string): McpConfigFile {
+ return {
+ mcpServers: {
+ ...config.mcpServers,
+ [name]: { url },
+ },
+ };
+}
+
+export function removeServer(config: McpConfigFile, name: string): McpConfigFile {
+ const mcpServers = { ...config.mcpServers };
+ delete mcpServers[name];
+ return { mcpServers };
+}
+
+export function splitCommandLine(line: string): { command: string; args: string[] } | null {
+ const parts = line.trim().split(/\s+/).filter(Boolean);
+ if (parts.length === 0) return null;
+ return { command: parts[0]!, args: parts.slice(1) };
+}
+
+/** A configured server is active when MCP start is on and the entry is not disabled. */
+export function isActive(row: McpServerRow, mcpEnabled: boolean): boolean {
+ return mcpEnabled && !row.disabled;
+}
diff --git a/apps/native/skills/mcp/SKILL.md b/apps/native/skills/mcp/SKILL.md
new file mode 100644
index 00000000..acf47474
--- /dev/null
+++ b/apps/native/skills/mcp/SKILL.md
@@ -0,0 +1,57 @@
+---
+name: mcp
+description: Add or adjust MCP servers when selected with $mcp or @mcp in the GUI composer.
+---
+
+# GUI MCP
+
+This skill is supplied by the GUI for this request. It is not an engine skill.
+Use ordinary file tools to edit MCP config JSON; do not patch the app or engine.
+
+MCP is a host/client talking to local stdio servers or remote Streamable HTTP
+servers. Adding a server means writing a `mcpServers` entry. The harness starts
+those servers with new chats when **Start MCP servers** is on in Project settings.
+
+If the user only invoked the skill, ask whether they want a local command or a
+URL, a name, and whether it should apply to all folders or just this workspace.
+If they already named a server, add it.
+
+## Config files
+
+Paths are supplied below these instructions.
+
+- **User** (`~/.codegraff/mcp.json` unless overridden): every folder.
+- **Workspace** (`.mcp.json` in the current folder): this folder only; it wins
+ on a name conflict.
+
+Read the target file first if it exists. Merge. Do not drop other servers. Do
+not print env values or auth headers. Create the file if it is missing:
+
+```json
+{
+ "mcpServers": {
+ "filesystem": {
+ "command": "npx",
+ "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
+ },
+ "docs": {
+ "url": "https://example.invalid/mcp"
+ }
+ }
+}
+```
+
+Names: letters, digits, `_` or `-`, start with a letter or digit, at most 64
+characters. Stdio entries need `command` and optional `args` / `env`. HTTP
+entries need `url` (HTTPS, or HTTP only for localhost). Do not invent `env`
+keys. Do not disable unrelated servers.
+
+## Validate and deliver
+
+Parse the JSON after writing. Confirm the new name is present. Tell the user:
+
+- Settings → MCP servers lists it (Active if Start MCP servers is on).
+- Open a **new** chat to start it. A running tab keeps the agent it spawned with.
+- Untrusted servers may need `/mcp trust` in the terminal the first time.
+
+Do not restart the app. Do not rewrite the engine catalog.
diff --git a/apps/native/skills/gui-theme/SKILL.md b/apps/native/skills/theme/SKILL.md
similarity index 97%
rename from apps/native/skills/gui-theme/SKILL.md
rename to apps/native/skills/theme/SKILL.md
index e629bc6d..844a4efa 100644
--- a/apps/native/skills/gui-theme/SKILL.md
+++ b/apps/native/skills/theme/SKILL.md
@@ -1,6 +1,6 @@
---
-name: gui-theme
-description: Create or adjust a CodeGraff desktop theme when selected with @gui-theme or $gui-theme in the GUI composer.
+name: theme
+description: Create or adjust a CodeGraff desktop theme when selected with $theme or @theme in the GUI composer.
---
# GUI theme