graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Add HTTP MCP task service and managed installer registration
justrachf7a52a3704ed
diff --git a/README.md b/README.mdindex 600b2e4a..67c6f72b 100644--- a/README.md+++ b/README.md@@ -255,7 +255,8 @@ for await (const ev of runAgent({ prompt: "summarize README.md", yolo: true }))````graff --json` / `graff --schema` generate the SDKs ([`sdk/`](sdk/)). Remote:-`graff serve`. Embedders: `--no-local-tools` + a sandbox MCP —+`graff serve`. MCP clients can delegate small tasks with+[`graff mcp serve`](docs/mcp-server.md). Embedders: `--no-local-tools` + a sandbox MCP —[Embedding graff](docs/embedding.md).<details>diff --git a/apps/native/app/globals.css b/apps/native/app/globals.cssindex 2a481378..b957ef69 100644--- a/apps/native/app/globals.css+++ b/apps/native/app/globals.css@@ -1,4 +1,5 @@@import "tailwindcss";+@import "./ui-theme.css";/* shadow-plugin (flornkm) — smooth, layered shadow stacks. The unprefixed* entry maps them onto Tailwind's --shadow-xs…2xl scale; our semantic tokens* below build on those values so the whole app picks up the smooth shadows. */@@ -17,107 +18,6 @@* color used sparingly as a condiment.* ────────────────────────────────────────────────────────── */-:root {- /* surfaces — cool, blue-tinted neutrals */- --page: oklch(0.985 0.001 286.376);- --canvas: oklch(0.961 0.002 247.84);- --surface: oklch(1 0 0);- --inset: oklch(0.979 0.002 247.839);- --hover: oklch(0.97 0.002 247.839);- --hover-2: oklch(0.933 0.003 247.86);-- /* ink ramp */- --ink: oklch(0.247 0.006 258.361);- --ink-2: oklch(0.506 0.01 264.477);- --ink-3: oklch(0.695 0.009 264.505);-- /* borders — solid and crisp, not alpha */- --line: oklch(0.946 0.003 264.542);- --line-strong: oklch(0.912 0.005 258.326);- --field: oklch(0.961 0.001 286.375);- --stripe: oklch(0.405 0 0 / 0.075);- --stripe-bg: oklch(0.97 0 0);-- /* accent */- --accent: oklch(0.626 0.205 254.947);- --accent-ink: oklch(0.556 0.187 255.617);- --accent-tint: oklch(0.96 0.019 252.878);-- /* semantic */- --green: oklch(0.603 0.155 150.883);- --green-tint: oklch(0.958 0.017 159.118);- --orange: oklch(0.689 0.179 49.902);- --orange-tint: oklch(0.964 0.021 67.581);- --red: oklch(0.621 0.192 23.042);- --red-tint: oklch(0.956 0.017 17.462);-- /* chart overlays — neutral system colors with enough contrast on either theme */- --tooltip-bg: oklch(0.272 0.008 264.435);- --tooltip-fg: oklch(0.976 0.002 247.839);- --tooltip-muted: oklch(0.731 0.008 260.731);- --tooltip-border: oklch(0.356 0.007 264.474);-- /* shadows — our solid hairline ring + shadow-plugin's smooth layered stacks- * (--shadow-xs…lg come from shadow-plugin/unprefixed) so every surface reads- * consistently across the app. */- --shadow-hairline: 0 0 0 1px var(--line);- --shadow-btn: 0 0 0 1px var(--line-strong), var(--shadow-xs);- --shadow-card: 0 0 0 1px var(--line), var(--shadow-sm);- --shadow-raised: 0 0 0 1px var(--line), var(--shadow-md);- --shadow-overlay: 0 0 0 1px var(--line), var(--shadow-lg);- --shadow-inset-field: inset 0 1px 2px oklch(0 0 0 / 0.12);-}--.dark {- --page: oklch(0.209 0.004 264.477);- --canvas: oklch(0.231 0.004 264.487);- --surface: oklch(0.26 0.006 271.191);- --inset: oklch(0.243 0.004 264.492);- --hover: oklch(0.289 0.006 271.22);- --hover-2: oklch(0.318 0.007 274.747);-- --ink: oklch(0.964 0.002 247.839);- --ink-2: oklch(0.731 0.008 260.731);- --ink-3: oklch(0.541 0.01 264.484);-- --line: oklch(0.308 0.006 258.354);- --line-strong: oklch(0.356 0.007 264.474);- --field: oklch(0.293 0.006 271.223);- --stripe: oklch(1 0 0 / 0.055);- --stripe-bg: oklch(0.226 0.004 264.485);-- --accent: oklch(0.68 0.173 253.301);- --accent-ink: oklch(0.788 0.113 248.33);- --accent-tint: oklch(0.68 0.173 253.301 / 0.16);-- --green: oklch(0.705 0.154 153.814);- --green-tint: oklch(0.705 0.154 153.814 / 0.14);- --orange: oklch(0.746 0.156 55.642);- --orange-tint: oklch(0.746 0.156 55.642 / 0.14);- --red: oklch(0.666 0.18 21.433);- --red-tint: oklch(0.666 0.18 21.433 / 0.14);-- --tooltip-bg: oklch(0.182 0.004 264.459);- --tooltip-fg: oklch(0.964 0.002 247.839);- --tooltip-muted: oklch(0.731 0.008 260.731);- --tooltip-border: oklch(0.308 0.006 258.354);-- --shadow-hairline: 0 0 0 1px var(--line);- /* Elevation rings go to a subtle *light* hairline in dark mode: the ring- * paints over the surface behind the element, so a low-alpha white edge- * dissolves into the shadow as one continuous stroke (per smooth-shadow-ring),- * graduated by how far the surface floats. */- --shadow-btn: 0 0 0 1px oklch(1 0 0 / 0.1), 0 1px 2px oklch(0 0 0 / 0.3);- --shadow-card:- 0 0 0 1px oklch(1 0 0 / 0.11), 0 1px 2px oklch(0 0 0 / 0.2),- 0 2px 6px oklch(0 0 0 / 0.2);- --shadow-raised:- 0 0 0 1px oklch(1 0 0 / 0.13), 0 2px 10px oklch(0 0 0 / 0.22);- --shadow-overlay:- 0 0 0 1px oklch(1 0 0 / 0.15), 0 8px 28px oklch(0 0 0 / 0.34);- --shadow-inset-field: inset 0 1px 2px oklch(0 0 0 / 0.4);-}-@theme inline {/* colors */--color-page: var(--page);diff --git a/apps/native/app/ui-theme.css b/apps/native/app/ui-theme.cssnew file mode 100644index 00000000..bdd7b0ed--- /dev/null+++ b/apps/native/app/ui-theme.css@@ -0,0 +1,101 @@+/* Shared Codegraff desktop and embedded MCP App palette. */+:root {+ /* surfaces — cool, blue-tinted neutrals */+ --page: oklch(0.985 0.001 286.376);+ --canvas: oklch(0.961 0.002 247.84);+ --surface: oklch(1 0 0);+ --inset: oklch(0.979 0.002 247.839);+ --hover: oklch(0.97 0.002 247.839);+ --hover-2: oklch(0.933 0.003 247.86);++ /* ink ramp */+ --ink: oklch(0.247 0.006 258.361);+ --ink-2: oklch(0.506 0.01 264.477);+ --ink-3: oklch(0.695 0.009 264.505);++ /* borders — solid and crisp, not alpha */+ --line: oklch(0.946 0.003 264.542);+ --line-strong: oklch(0.912 0.005 258.326);+ --field: oklch(0.961 0.001 286.375);+ --stripe: oklch(0.405 0 0 / 0.075);+ --stripe-bg: oklch(0.97 0 0);++ /* accent */+ --accent: oklch(0.626 0.205 254.947);+ --accent-ink: oklch(0.556 0.187 255.617);+ --accent-tint: oklch(0.96 0.019 252.878);++ /* semantic */+ --green: oklch(0.603 0.155 150.883);+ --green-tint: oklch(0.958 0.017 159.118);+ --orange: oklch(0.689 0.179 49.902);+ --orange-tint: oklch(0.964 0.021 67.581);+ --red: oklch(0.621 0.192 23.042);+ --red-tint: oklch(0.956 0.017 17.462);++ /* chart overlays — neutral system colors with enough contrast on either theme */+ --tooltip-bg: oklch(0.272 0.008 264.435);+ --tooltip-fg: oklch(0.976 0.002 247.839);+ --tooltip-muted: oklch(0.731 0.008 260.731);+ --tooltip-border: oklch(0.356 0.007 264.474);++ /* shadows — our solid hairline ring + shadow-plugin's smooth layered stacks+ * (--shadow-xs…lg come from shadow-plugin/unprefixed) so every surface reads+ * consistently across the app. */+ --shadow-hairline: 0 0 0 1px var(--line);+ --shadow-btn: 0 0 0 1px var(--line-strong), var(--shadow-xs);+ --shadow-card: 0 0 0 1px var(--line), var(--shadow-sm);+ --shadow-raised: 0 0 0 1px var(--line), var(--shadow-md);+ --shadow-overlay: 0 0 0 1px var(--line), var(--shadow-lg);+ --shadow-inset-field: inset 0 1px 2px oklch(0 0 0 / 0.12);+}++.dark {+ --page: oklch(0.209 0.004 264.477);+ --canvas: oklch(0.231 0.004 264.487);+ --surface: oklch(0.26 0.006 271.191);+ --inset: oklch(0.243 0.004 264.492);+ --hover: oklch(0.289 0.006 271.22);+ --hover-2: oklch(0.318 0.007 274.747);++ --ink: oklch(0.964 0.002 247.839);+ --ink-2: oklch(0.731 0.008 260.731);+ --ink-3: oklch(0.541 0.01 264.484);++ --line: oklch(0.308 0.006 258.354);+ --line-strong: oklch(0.356 0.007 264.474);+ --field: oklch(0.293 0.006 271.223);+ --stripe: oklch(1 0 0 / 0.055);+ --stripe-bg: oklch(0.226 0.004 264.485);++ --accent: oklch(0.68 0.173 253.301);+ --accent-ink: oklch(0.788 0.113 248.33);+ --accent-tint: oklch(0.68 0.173 253.301 / 0.16);++ --green: oklch(0.705 0.154 153.814);+ --green-tint: oklch(0.705 0.154 153.814 / 0.14);+ --orange: oklch(0.746 0.156 55.642);+ --orange-tint: oklch(0.746 0.156 55.642 / 0.14);+ --red: oklch(0.666 0.18 21.433);+ --red-tint: oklch(0.666 0.18 21.433 / 0.14);++ --tooltip-bg: oklch(0.182 0.004 264.459);+ --tooltip-fg: oklch(0.964 0.002 247.839);+ --tooltip-muted: oklch(0.731 0.008 260.731);+ --tooltip-border: oklch(0.308 0.006 258.354);++ --shadow-hairline: 0 0 0 1px var(--line);+ /* Elevation rings go to a subtle *light* hairline in dark mode: the ring+ * paints over the surface behind the element, so a low-alpha white edge+ * dissolves into the shadow as one continuous stroke (per smooth-shadow-ring),+ * graduated by how far the surface floats. */+ --shadow-btn: 0 0 0 1px oklch(1 0 0 / 0.1), 0 1px 2px oklch(0 0 0 / 0.3);+ --shadow-card:+ 0 0 0 1px oklch(1 0 0 / 0.11), 0 1px 2px oklch(0 0 0 / 0.2),+ 0 2px 6px oklch(0 0 0 / 0.2);+ --shadow-raised:+ 0 0 0 1px oklch(1 0 0 / 0.13), 0 2px 10px oklch(0 0 0 / 0.22);+ --shadow-overlay:+ 0 0 0 1px oklch(1 0 0 / 0.15), 0 8px 28px oklch(0 0 0 / 0.34);+ --shadow-inset-field: inset 0 1px 2px oklch(0 0 0 / 0.4);+}diff --git a/apps/native/electron/engine-launcher.cjs b/apps/native/electron/engine-launcher.cjsnew file mode 100644index 00000000..5b09e8c9--- /dev/null+++ b/apps/native/electron/engine-launcher.cjs@@ -0,0 +1,46 @@+const fs = require('node:fs/promises');+const path = require('node:path');+const marker = '# Codegraff bundled engine launcher';+const pathMarker = '# Codegraff GUI CLI PATH';+const quote = value => "'" + value.replaceAll("'", "'\\''") + "'";++async function ensurePath(home, directory, shell = process.env.SHELL || '/bin/zsh') {+ if (process.env.HARNESS_NO_PATH) return;+ const shellName = path.basename(shell);+ const candidates = [+ [path.join(home, '.zshrc'), shellName === 'zsh', `export PATH=${quote(directory)}:"$PATH"`],+ [path.join(home, '.bash_profile'), shellName === 'bash', `export PATH=${quote(directory)}:"$PATH"`],+ [path.join(home, '.bashrc'), shellName === 'bash', `export PATH=${quote(directory)}:"$PATH"`],+ [path.join(home, '.profile'), !['zsh', 'bash', 'fish'].includes(shellName), `export PATH=${quote(directory)}:"$PATH"`],+ [path.join(home, '.config/fish/config.fish'), shellName === 'fish', `fish_add_path -m ${quote(directory)}`],+ ];+ for (const [file, create, line] of candidates) {+ let source;+ try { source = await fs.readFile(file, 'utf8'); }+ catch (error) { if (error.code !== 'ENOENT') throw error; if (!create) continue; source = ''; }+ if (source.includes(pathMarker)) continue;+ await fs.mkdir(path.dirname(file), {recursive:true});+ await fs.appendFile(file, `\n${pathMarker}\n${line}\n`, {mode:0o600});+ }+}++async function installEngine(binary, home, {shell} = {}) {+ await fs.access(binary, require('node:fs').constants.X_OK);+ const directory = path.join(home, '.local/bin'), file = path.join(directory, 'graff');+ await fs.mkdir(directory, {recursive:true});+ let owned = true;+ try {+ const stat = await fs.lstat(file);+ owned = stat.isFile() && stat.size < 16384 && (await fs.readFile(file, 'utf8')).includes(marker);+ } catch (error) { if (error.code !== 'ENOENT') throw error; }+ if (!owned) return 'Existing graff command preserved';+ const source = `#!/bin/sh\n${marker}\nexec ${quote(binary)} "$@"\n`;+ const temporary = `${file}.${process.pid}.next`;+ try {+ await fs.writeFile(temporary, source, {mode:0o755, flag:'wx'});+ await fs.rename(temporary, file);+ } finally { await fs.rm(temporary, {force:true}); }+ await ensurePath(home, directory, shell);+ return `Installed graff in ${directory}. Open a new terminal to use it.`;+}+module.exports = {installEngine, ensurePath};diff --git a/apps/native/electron/engine-launcher.test.cjs b/apps/native/electron/engine-launcher.test.cjsnew file mode 100644index 00000000..d30db0a8--- /dev/null+++ b/apps/native/electron/engine-launcher.test.cjs@@ -0,0 +1,37 @@+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs/promises');+const os = require('node:os');+const path = require('node:path');+const {promisify} = require('node:util');+const execFile = promisify(require('node:child_process').execFile);+const {installEngine} = require('./engine-launcher.cjs');++test('bundled graff forwards arguments, updates with GUI and configures PATH once', async () => {+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'graff-engine-'));+ try {+ const first = path.join(home, "old ' bundle"), second = path.join(home, 'new bundle');+ await fs.writeFile(first, '#!/bin/sh\nprintf "%s\\n" "$@"\n', {mode:0o700});+ await fs.writeFile(second, '#!/bin/sh\necho updated\n', {mode:0o700});+ await installEngine(first, home, {shell:'/bin/zsh'});+ const launcher = path.join(home, '.local/bin/graff');+ assert.equal((await execFile(launcher, ['a b', '$(literal)'])).stdout, 'a b\n$(literal)\n');+ const rc = await fs.readFile(path.join(home, '.zshrc'), 'utf8');+ await installEngine(second, home, {shell:'/bin/zsh'});+ assert.equal((await execFile(launcher)).stdout, 'updated\n');+ assert.equal(await fs.readFile(path.join(home, '.zshrc'), 'utf8'), rc);+ const result = await execFile('/bin/zsh', ['-c', 'source "$HOME/.zshrc"; command -v graff'], {env:{HOME:home,PATH:'/usr/bin:/bin'}});+ assert.equal(result.stdout.trim(), launcher);+ } finally { await fs.rm(home, {recursive:true,force:true}); }+});++test('independent graff command is preserved', async () => {+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'graff-engine-'));+ try {+ const file = path.join(home,'.local/bin/graff');+ await fs.mkdir(path.dirname(file),{recursive:true});+ await fs.writeFile(file,'custom');+ assert.equal(await installEngine('/bin/echo',home),'Existing graff command preserved');+ assert.equal(await fs.readFile(file,'utf8'),'custom');+ } finally {await fs.rm(home,{recursive:true,force:true});}+});diff --git a/apps/native/electron/main.cjs b/apps/native/electron/main.cjsindex 7ca2b579..be348302 100644--- a/apps/native/electron/main.cjs+++ b/apps/native/electron/main.cjs@@ -75,6 +75,11 @@ process.on('SIGINT', () => app.quit());app.whenReady().then(async () => {await require('./shell-path.cjs').restoreShellPath();+ if (app.isPackaged && !process.env.GRAFF_ELECTRON_SMOKE) {+ void require('./engine-launcher.cjs').installEngine(path.join(resources, 'graff'), app.getPath('home'))+ .then(() => require('./mcp-install.cjs').installMcp(path.join(resources, 'graff'), app.getPath('home'), { once: true, version: app.getVersion() }))+ .catch(error => dialog.showErrorBox('Command setup incomplete', `${error.message}\nRetry from Tools → Install codegraff terminal command.`));+ }app.setAccessibilitySupportEnabled(true);const token = randomBytes(32).toString('hex');win = createWindow({ width: 1440, height: 920, minWidth: 900, minHeight: 600,@@ -173,10 +178,16 @@ app.whenReady().then(async () => {['Toggle terminal', 'CmdOrCtrl+J', 'terminal'], ['Open workspace…', 'CmdOrCtrl+O', 'workspace'], ['Split right', 'CmdOrCtrl+D', 'split-right'],['Split down', 'CmdOrCtrl+Shift+D', 'split-down'], ['Zoom split', 'CmdOrCtrl+Shift+Enter', 'split-zoom'],].map(([label, accelerator, action]) => ({ label, accelerator, click: () => win.webContents.send('desktop-action', action) })) },- { label: 'Tools', submenu: [{ label: 'Install codegraff terminal command…', enabled: app.isPackaged && process.platform === 'darwin', click: async () => {+ { label: 'Tools', submenu: [{ label: 'Configure MCP clients…', enabled: app.isPackaged, click: async () => {try {+ const detail = await require('./mcp-install.cjs').installMcp(path.join(resources, 'graff'), app.getPath('home'));+ await dialog.showMessageBox(win, { message: 'MCP clients configured', detail });+ } catch (error) { dialog.showErrorBox('MCP setup', error.message); }+ } }, { label: 'Install codegraff terminal command…', enabled: app.isPackaged && process.platform === 'darwin', click: async () => {+ try {+ await require('./engine-launcher.cjs').installEngine(path.join(resources, 'graff'), app.getPath('home'));const installed = await require('./cli-launcher.cjs').installLauncher(path.resolve(app.getPath('exe'), '../../..'), app.getPath('home'));- await dialog.showMessageBox(win, { message: 'Terminal command installed', detail: `Run codegraff . to open a project here. Ensure ${path.dirname(installed)} is on your PATH.` });+ await dialog.showMessageBox(win, { message: 'Terminal command installed', detail: `Run graff for the CLI or codegraff . for the GUI. Open a new terminal to load the PATH update (${path.dirname(installed)}).` });} catch (error) { dialog.showErrorBox('Terminal command', error.message); }} }] },{ role: 'editMenu' }, { label: 'View', submenu: [{ role: 'reload' }, { role: 'toggleDevTools' }, { role: 'togglefullscreen' }, { label: 'Release browser pages', click: () => { browser.closeAll(); win.webContents.send('browser-event', { type: 'released' }); } }] },diff --git a/apps/native/electron/mcp-install.cjs b/apps/native/electron/mcp-install.cjsnew file mode 100644index 00000000..42d80fa8--- /dev/null+++ b/apps/native/electron/mcp-install.cjs@@ -0,0 +1,19 @@+const { promisify } = require('node:util');+const { execFile } = require('node:child_process');+const fs = require('node:fs/promises');+const path = require('node:path');++async function installMcp(binary, home, { once = false, version = '1' } = {}) {+ if (process.env.GRAFF_NO_MCP === '1') return 'MCP setup skipped';+ const receipt = path.join(home, '.graff/mcp/gui-installed');+ if (once) {+ try { if ((await fs.readFile(receipt, 'utf8')).trim() === version) return 'MCP already configured'; } catch (error) { if (error.code !== 'ENOENT') throw error; }+ }+ const { stdout, stderr } = await promisify(execFile)(binary, ['mcp', 'install'], {+ env: { ...process.env, HOME: home }, timeout: 35000, maxBuffer: 32768,+ });+ await fs.mkdir(path.dirname(receipt), { recursive: true, mode: 0o700 });+ await fs.writeFile(receipt, version + '\n', { mode: 0o600 });+ return stdout + stderr;+}+module.exports = { installMcp };diff --git a/apps/native/electron/mcp-install.test.cjs b/apps/native/electron/mcp-install.test.cjsnew file mode 100644index 00000000..9859ac31--- /dev/null+++ b/apps/native/electron/mcp-install.test.cjs@@ -0,0 +1,27 @@+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs/promises');+const os = require('node:os');+const path = require('node:path');+const { installMcp } = require('./mcp-install.cjs');++test('GUI setup uses the bundled engine, records success and skips repeated first launch', async () => {+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'graff-mcp-gui-'));+ try {+ const binary = path.join(home, 'fake graff');+ await fs.writeFile(binary, '#!/bin/sh\n[ "$1" = mcp ] && [ "$2" = install ] || exit 3\necho registered\n', {mode:0o700});+ assert.match(await installMcp(binary, home, {once:true}), /registered/);+ assert.match(await installMcp(binary, home, {once:true, version:'2'}), /registered/);+ await fs.unlink(binary);+ assert.equal(await installMcp(binary, home, {once:true, version:'2'}), 'MCP already configured');+ await assert.rejects(installMcp(binary, home));+ } finally { await fs.rm(home, {recursive:true, force:true}); }+});++test('failed GUI setup leaves no success receipt', async () => {+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'graff-mcp-gui-'));+ try {+ await assert.rejects(installMcp(path.join(home, 'missing'), home, {once:true}));+ await assert.rejects(fs.access(path.join(home, '.graff/mcp/gui-installed')));+ } finally { await fs.rm(home, {recursive:true, force:true}); }+});diff --git a/apps/native/scripts/install-cli.mjs b/apps/native/scripts/install-cli.mjsindex 077b3f49..f86e6abb 100644--- a/apps/native/scripts/install-cli.mjs+++ b/apps/native/scripts/install-cli.mjs@@ -4,3 +4,9 @@ import path from 'node:path';const { installLauncher } = createRequire(import.meta.url)('../electron/cli-launcher.cjs');const file = await installLauncher(path.resolve(process.argv[2] || '/Applications/Codegraff.app'), homedir());console.log(`Installed ${file}. Ensure its directory is on your PATH.`);++const { installEngine } = createRequire(import.meta.url)('../electron/engine-launcher.cjs');+console.log(await installEngine(path.resolve(process.argv[2] || '/Applications/Codegraff.app', 'Contents/Resources/graff'), homedir()));++const { installMcp } = createRequire(import.meta.url)('../electron/mcp-install.cjs');+console.log(await installMcp(path.resolve(process.argv[2] || '/Applications/Codegraff.app', 'Contents/Resources/graff'), homedir()));diff --git a/build.zig b/build.zigindex 2486302e..36f8933f 100644--- a/build.zig+++ b/build.zig@@ -107,6 +107,8 @@ pub fn build(b: *std.Build) void {unit_tests.root_module.addImport("tui", tui_mod);// spec/ fixtures live outside src/; importing them here makes @embedFile// legal and rebuilds the suite when the exported semantics change.+ exe.root_module.addAnonymousImport("ui_theme", .{ .root_source_file = b.path("apps/native/app/ui-theme.css") });+ unit_tests.root_module.addAnonymousImport("ui_theme", .{ .root_source_file = b.path("apps/native/app/ui-theme.css") });unit_tests.root_module.addAnonymousImport("spec_tool_catalog", .{ .root_source_file = b.path("spec/kernels/tool_catalog.json") });unit_tests.root_module.addAnonymousImport("spec_transport", .{ .root_source_file = b.path("spec/kernels/transport.json") });unit_tests.root_module.addAnonymousImport("spec_providers", .{ .root_source_file = b.path("spec/kernels/providers.json") });@@ -133,6 +135,7 @@ pub fn build(b: *std.Build) void {// into a workspace so zero-configuration learning needs no repo checkout.// Embedded by name (src/learn_assets.zig `@embedFile`s these imports).for ([_]struct { import: []const u8, path: []const u8 }{+ .{ .import = "mcp_installer", .path = "scripts/install-mcp.py" },.{ .import = "learn_kit_mutator", .path = "examples/learn_graff_mutator.py" },.{ .import = "learn_kit_evaluator", .path = "examples/learn_graff_evaluator.py" },.{ .import = "learn_kit_case", .path = "examples/learn_graff_case.py" },diff --git a/docs/adr/0129-mcp-server-delegates-bounded-cli-tasks.md b/docs/adr/0129-mcp-server-delegates-bounded-cli-tasks.mdnew file mode 100644index 00000000..8d2bb386--- /dev/null+++ b/docs/adr/0129-mcp-server-delegates-bounded-cli-tasks.md@@ -0,0 +1,30 @@+# 0129: MCP server delegates bounded CLI tasks++## Context++MCP clients need to delegate small tasks to the harness. The existing MCP+CLI configures outbound servers; the existing one-shot command already owns+model selection, credentials, project instructions, tool policy, and cleanup.++## Decision++Expose `graff mcp serve` over stdio with one `run_task` tool. Each call spawns+the current executable as a fresh bounded one-shot. The server launch fixes+the workspace, optional model, and permission mode. Default children use+`--safe`; only a server launched with `--yolo` grants unattended execution.+Tool arguments cannot raise permissions or replace configuration.++Reuse the process runner for output caps, deadlines, and process-tree cleanup.+Preserve partial output and error status. Guard nested server launches with an+inherited recursion marker. Initialization and discovery require no model+credentials. Keep the outer protocol independent of child stdout/stderr.++## Consequences++There is one harness implementation and a narrow MCP adapter. Initial calls+are serial and bounded; there is no progress, live cancellation, or resumable+conversation. Client disconnects are observed after the current bounded call.+A successful child exit does not independently verify its answer, and failed+work may leave edits behind. Future asynchronous support needs explicit task+ownership and cancellation rather than extending this synchronous contract+implicitly.diff --git a/docs/adr/0130-mcp-task-app-is-an-optional-result-view.md b/docs/adr/0130-mcp-task-app-is-an-optional-result-view.mdnew file mode 100644index 00000000..9ef5a056--- /dev/null+++ b/docs/adr/0130-mcp-task-app-is-an-optional-result-view.md@@ -0,0 +1,32 @@+# 0130. MCP task app is an optional result view++## Context++A text-only task answer obscures process failure, limits, and truncated output.+MCP Apps hosts can present an interactive view alongside the conversation.++## Decision++Negotiate the UI MIME type from the client's extension capability. Attach a+static `ui://` resource to `run_task` only for compatible clients. Bundle the+HTML into the executable, request no external origins or device permissions,+and render all task text through textContent. Expose only the exact template+URI through resource reads.++Return schema-described status, text, truncation and limits alongside the+ordinary text content for every task outcome, including execution failures.+The view shares the desktop palette from `apps/native/app/ui-theme.css`,+embedded at compile time, and follows its conversation layout. It follows host+theme changes, filters output lines, and toggles wrapping.+It receives task input/results but grants no app-initiated execution authority.+Host-side tool calls retain the launch-time execution contract from ADR 0129.++## Consequences++A single binary serves both ordinary MCP clients and Apps hosts, with no UI+build chain or CDN requirement. Completion means the process exited cleanly,+not that its claims were independently verified. The view is a final-result+inspector, not a live task manager. Progress, cancellation and retries require+an explicit execution lifecycle design before being added to the view.++Reference: [MCP Apps specification](https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx).diff --git a/docs/adr/0131-mcp-http-and-managed-client-registration.md b/docs/adr/0131-mcp-http-and-managed-client-registration.mdnew file mode 100644index 00000000..f1c0c297--- /dev/null+++ b/docs/adr/0131-mcp-http-and-managed-client-registration.md@@ -0,0 +1,33 @@+# 0131. MCP HTTP shares task execution and installs additive client entries++## Decision++Offer `graff mcp serve --http` as a loopback-only Streamable HTTP adapter to+the same bounded task executor as stdio. Require a bearer token, validate Host+and Origin, cap request bodies, and keep each client's initialization state+separate. A bounded handshake table returns 404 for retired sessions. Task+execution remains serial; HTTP does not create shared model conversation state.++`graff mcp install` owns service setup and client registration for both the+shell installer and packaged GUI. Use launchd or user systemd, private token+and service files, and readiness verification before changing client configs.+Register detected HTTP-capable clients additively. A private ownership receipt+allows unchanged generated entries to refresh on upgrades; preserve user-edited+entries, unknown settings, comments in TOML, and malformed files. Serialize+installer runs with a local lock. An environment opt-out skips automatic setup.++The install default is the user's home workspace and approval-gated execution.+Explicit project/port choices persist across repeated installs. A service+restart can interrupt active work; installation is not a live-task migration.++## Consequences++Multiple clients share one listener with the same embedded app and task+contract. Installation needs Python and an available user service manager.+Unsupported clients keep the manual stdio path. Installer tests operate only+on temporary configurations and mock the service manager; transport tests use+an isolated loopback listener and scripted model.++GUI launches refresh the managed bundled-engine launcher and shell PATH.+MCP setup runs once per app version, so newer GUI downloads refresh the service+and client registration. Existing unmanaged launcher files are preserved.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex cf9f10c2..b7ce84c5 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -146,6 +146,10 @@ record only when you need the evidence or the edge cases.| [0128](0128-gui-context-meter-uses-harness-occupancy.md) | The GUI context ring uses last-reported harness occupancy; missing usage stays unknown. |+| [0129](0129-mcp-server-delegates-bounded-cli-tasks.md) | `graff mcp serve` exposes bounded fresh CLI tasks over stdio; launch-time permissions and workspace stay outside tool arguments. |+| [0130](0130-mcp-task-app-is-an-optional-result-view.md) | MCP task apps negotiate presentation only; structured results and text fallback share the same bounded task execution. |+| [0131](0131-mcp-http-and-managed-client-registration.md) | HTTP MCP shares bounded task execution; CLI and GUI installs register detected clients additively through a private local service. |+## When to write oneWrite an ADR when a decision is load-bearing and non-obvious: it was reacheddiff --git a/docs/mcp-server.md b/docs/mcp-server.mdnew file mode 100644index 00000000..c816edf6--- /dev/null+++ b/docs/mcp-server.md@@ -0,0 +1,188 @@+# Use Codegraff as an MCP tool and app++## Automatic HTTP setup++The packaged GUI installs its bundled `graff` command into `~/.local/bin` on+launch and adds that directory to shell startup files. Open a new terminal to+load the PATH change. GUI updates refresh this managed launcher; an existing+independently installed command is preserved. `HARNESS_NO_PATH=1` skips PATH edits.++The CLI installer and first launch of the packaged GUI run `graff mcp install`.+The GUI also offers **Tools → Configure MCP clients**. Setup requires Python 3+(Python 3.11+ to validate Codex TOML), and macOS launchd or Linux user systemd.++Setup starts a shared service at `http://127.0.0.1:7720/mcp`, creates a private+bearer token, and adds HTTP entries for detected Claude Code, Codex, Cursor,+Gemini CLI, Windsurf and VS Code installations. Installer-owned entries refresh on later installs while unrelated entries and+user-modified Codegraff entries are preserved. Malformed or JSON-with-comments files are+left unchanged with a diagnostic. Restart clients to load their new entry.+Clients that require stdio can use the manual configuration below.++The default workspace is your home directory; tasks remain approval-gated.+To choose a fixed project and optional port, run:++```sh+graff mcp install --directory /absolute/path/to/project --port 7720+```++Subsequent installs retain that directory and port. Changing the port refreshes installer-owned entries; user-modified entries+remain yours to update. Service+installation restarts the managed listener, so finish active tasks first.+The GUI runs setup once per app version after successful setup; the Tools action+can retry or configure clients installed later.++Set `GRAFF_NO_MCP=1` when installing or launching the GUI to skip automatic setup.+This does not stop a previously installed service. Stop/disable it using:++- macOS: `launchctl bootout gui/$(id -u)/dev.codegraff.mcp`, then remove+ `~/Library/LaunchAgents/dev.codegraff.mcp.plist` to prevent login startup.+- Linux: `systemctl --user disable --now codegraff-mcp.service`.++Remove the `codegraff` entry from client configs if it is no longer wanted.++## Run the HTTP listener yourself++```sh+export GRAFF_MCP_TOKEN="$(python3 -c 'import secrets; print(secrets.token_hex(32))')"+graff mcp serve --http --port 7720+```++Clients need that token in their `Authorization: Bearer …` header. The managed+service keeps its token in `~/.graff/mcp/token` and writes the matching headers+into private client config files. The listener binds only to 127.0.0.1, checks+the Host and Origin headers, and exposes only `/mcp`. There is no public bind+or browser CORS access. The embedded UI is delivered through the MCP host.++POST accepts JSON-RPC and returns JSON, or HTTP 202 for accepted notifications.+Initialization returns `Mcp-Session-Id`; later calls must send it. DELETE closes+a session, and GET returns 405 (no SSE stream). The service retains up to 64+client handshakes, replacing the oldest on overflow; an evicted client gets+404 and must initialize again. Each client negotiates Apps support separately.+Tasks across clients run serially and share the listener; each task still gets+a fresh bounded child. HTTP saves duplicate listener startup, not model tokens+or the per-task model startup. Existing task limits still apply.++++`graff mcp serve` exposes Codegraff's task runner to local MCP clients. The+client launches it over stdio, discovers `run_task`, and supplies a brief.+Each call runs a fresh Codegraff child in the server's launch directory and+returns its answer. Existing `graff mcp add`, `list`, and `login` commands+still configure the MCP tools Codegraff consumes.++## Manual stdio configuration++Use an absolute path to the built or installed `graff` executable in your+client's MCP server configuration. For clients using `mcpServers` JSON:++```json+{+ "mcpServers": {+ "codegraff": {+ "command": "/absolute/path/to/graff",+ "args": ["mcp", "serve"]+ }+ }+}+```++Set the server's working directory to the project using your client's cwd+setting, or launch the client from that project. Calls cannot override cwd,+credentials, permission mode, or arbitrary CLI flags.++Run `graff login` first for actual tasks. Initialization and tool discovery+work without credentials. Tasks inherit the launch environment and existing+Codegraff configuration. To pin a model, append `--model NAME` to the server+arguments; otherwise Codegraff uses its normal configured model selection.++By default tasks use `--safe`: permission-gated operations are denied when+there is no interactive approval channel. For unattended coding in a trusted+workspace, explicitly append `--yolo` to the **server launch arguments**.+This authorizes the ordinary Codegraff tools, including file edits, commands,+and configured MCP tools. It is not an OS sandbox; the client must approve+and scope task calls appropriately. Review resulting edits before integrating.++## Call the tool++```json+{+ "name": "run_task",+ "arguments": {+ "prompt": "Explain how the configuration parser handles missing values. Cite the relevant files. Do not change files.",+ "timeout_seconds": 120,+ "max_model_calls": 8+ }+}+```++A useful brief includes the concrete task, relevant context, permitted scope,+and acceptance criteria. There is no inherited client conversation. Prefer+small explanations, focused reviews, test runs, and narrowly scoped fixes.++- `prompt`: required, nonblank, at most 32 KiB of UTF-8 text.+- `timeout_seconds`: 1–300, default 120.+- `max_model_calls`: 1–32, default 8, shared across the child invocation.+- Root tool calls are capped at 64 per turn.++The MCP result contains text, `isError`, and schema-described `structuredContent`+with `text`, `status`, `output_truncated`, `timeout_seconds`, and `max_model_calls`.+Status is `completed`, `failed`, `timed_out`, or `cancelled`. Process failures and deadlines+return an error with partial output; changes made before failure are not+rolled back. Successful exit reports the harness answer, not independent+verification of its claims. Answers are capped at 64 KiB and failure+diagnostics at 16 KiB, with explicit truncation markers.++## Embedded task result++Hosts advertising `io.modelcontextprotocol/ui` with MIME type+`text/html;profile=mcp-app` receive UI metadata on `run_task`. The host reads+`ui://codegraff/task-result` and renders the bundled task panel in its sandbox.+It shows completion status, configured limits, truncation, the task brief, and+searchable output with a line-wrap control. Theme changes follow the host. The embedded conversation uses the desktop+palette from `apps/native/app/ui-theme.css`, compiled into the MCP resource,+with the same task chrome, user bubble and response layout.++No extra server, package install, or network access is needed for the view.+The panel is a result inspector: it does not run or retry tasks, stream progress,+or change permissions. Submit follow-up tasks through the host conversation.+Clients without the extension receive the ordinary tool with the same text and+structured result. UI support depends on the host; MCP tool support alone does+not imply embedded-app support.++The HTML requests no external domains or device permissions. Model output is+rendered as literal text. Resources list/read expose only the bundled template,+never workspace files or saved task data.++See the [MCP Apps specification](https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx).++## Lifecycle and limits++The server implements MCP initialization, `ping`, `tools/list`, and+`tools/call`, `resources/list`, `resources/read`, and an empty+`resources/templates/list` using newline-delimited JSON-RPC on stdin/stdout. It supports+protocol revisions 2024-11-05, 2025-03-26, and 2025-06-18, negotiating the+last of these for an unknown revision. See the+[MCP lifecycle specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle).++Calls run serially. This initial adapter has no progress stream, live+cancellation, session continuation, or background task handle.+Keep the client's tool timeout longer than `timeout_seconds` to receive the+terminal result. If a client disconnects during a call, the child can continue+until its deadline; the runner terminates its process tree on deadline.++The child inherits a recursion marker. A nested `graff mcp serve` launch is+refused, preventing a configured Codegraff server from recursively delegating+to itself. Each call starts fresh; unrelated environment and workspace+configuration still follow the ordinary harness behavior.++Run the offline integration check with `python3 scripts/test-mcp-server.py`+after `zig build`. It uses the local scripted model on port 1234.++For the embedded view regression, run `node scripts/test-mcp-task-app.cjs`+with the native app's Playwright dependencies and Chrome installed. It uses a+local opaque iframe and checks the handshake, presentation controls, themes,+mobile layout, text-only rendering, cancellation notification and teardown.++HTTP and setup checks: `python3 scripts/test-mcp-http.py`,+`python3 scripts/test-install-mcp.py`, and+`node --test apps/native/electron/mcp-install.test.cjs`.diff --git a/install.sh b/install.shindex df21c85d..8eb1f899 100644--- a/install.sh+++ b/install.sh@@ -267,6 +267,9 @@ main() {fiensure_path+ if [ "${GRAFF_NO_MCP:-}" != "1" ]; then+ "$INSTALL_DIR/$BIN" mcp install || printf 'MCP setup incomplete. Retry with: graff mcp install\n' >&2+ fiprintf "\n ${W}done!${N} run ${C}$BIN${N} to start, or ${C}$BIN --help${N}\n\n"}diff --git a/scripts/install-mcp.py b/scripts/install-mcp.pynew file mode 100644index 00000000..64fbb988--- /dev/null+++ b/scripts/install-mcp.py@@ -0,0 +1,245 @@+#!/usr/bin/env python3+"""Install a private local MCP service and merge detected client configs."""+import argparse+import fcntl+import json+import os+from pathlib import Path+import plistlib+import re+import secrets+import shutil+import subprocess+import sys+import tempfile+import time+import urllib.request++MARKER = '# Codegraff managed MCP service'+++def atomic(path, text):+ path.parent.mkdir(parents=True, exist_ok=True)+ if path.is_symlink():+ raise ValueError(f'Refusing symlink: {path.name}')+ fd, temporary = tempfile.mkstemp(dir=path.parent, prefix='.graff-')+ try:+ os.fchmod(fd, 0o600)+ with os.fdopen(fd, 'w') as stream:+ stream.write(text)+ os.replace(temporary, path)+ finally:+ if os.path.exists(temporary):+ os.unlink(temporary)+++def merge_json(path, entry, key='mcpServers', previous=None):+ data = json.loads(path.read_text()) if path.exists() else {}+ if not isinstance(data, dict) or not isinstance(data.get(key, {}), dict):+ raise ValueError('Unexpected config structure')+ servers = data.setdefault(key, {})+ if 'codegraff' in servers and (previous is None or servers['codegraff'] != previous):+ return 'existing entry preserved'+ if servers.get('codegraff') == entry:+ return 'up to date'+ servers['codegraff'] = entry+ atomic(path, json.dumps(data, indent=2) + '\n')+ return 'registered'+++def codex_entry(url, token):+ return {'url': url, 'http_headers': {'Authorization': 'Bearer ' + token}, 'tool_timeout_sec': 330}+++def codex_fragment(entry):+ return ('\n[mcp_servers.codegraff]\nurl = ' + json.dumps(entry['url']) + '\n' ++ 'http_headers = { Authorization = ' + json.dumps(entry['http_headers']['Authorization']) + ' }\n' ++ 'tool_timeout_sec = ' + str(entry['tool_timeout_sec']) + '\n')+++def merge_codex(path, url, token, previous=None):+ # Preserve the entire TOML document, including comments and unfamiliar tables.+ source = path.read_text() if path.exists() else ''+ try:+ import tomllib+ except ImportError:+ raise ValueError('Codex registration requires Python 3.11+ for TOML validation')+ data = tomllib.loads(source)+ if not isinstance(data.get('mcp_servers', {}), dict):+ raise ValueError('Unexpected MCP server table')+ entry = codex_entry(url, token)+ current = data.get('mcp_servers', {}).get('codegraff')+ if current is not None:+ if previous is None or current != previous:+ return 'existing entry preserved'+ if current == entry:+ return 'up to date'+ old = codex_fragment(previous)+ if source.count(old) != 1:+ return 'existing entry preserved'+ updated = source.replace(old, codex_fragment(entry), 1)+ else:+ updated = source + codex_fragment(entry)+ tomllib.loads(updated)+ atomic(path, updated)+ return 'registered'+++def register(home, url, token):+ receipt = home / '.graff/mcp/clients.json'+ owned = json.loads(receipt.read_text()) if receipt.exists() else {}+ if not isinstance(owned, dict):+ raise ValueError('Invalid client ownership receipt')+ changed = False+ headers = {'Authorization': 'Bearer ' + token}+ entries = [+ (home / '.claude.json', 'mcpServers', {'type': 'http', 'url': url, 'headers': headers}, (home / '.claude').exists()),+ (home / '.cursor/mcp.json', 'mcpServers', {'url': url, 'headers': headers}, False),+ (home / '.gemini/settings.json', 'mcpServers', {'httpUrl': url, 'headers': headers, 'timeout': 330000}, False),+ (home / '.codeium/windsurf/mcp_config.json', 'mcpServers', {'serverUrl': url, 'headers': headers}, False),+ ]+ vscode = home / ('Library/Application Support/Code/User' if sys.platform == 'darwin' else '.config/Code/User')+ entries.append((vscode / 'mcp.json', 'servers', {'type': 'http', 'url': url, 'headers': headers}, False))+ results = []+ for path, key, entry, detected in entries:+ if not (detected or path.exists() or (path.parent != home and path.parent.exists())):+ continue+ try:+ client = str(path.relative_to(home))+ result = merge_json(path, entry, key, owned.get(client))+ results.append((client, result))+ if result in ('registered', 'up to date'):+ owned[client] = entry+ changed = True+ except (ValueError, OSError) as error:+ results.append((str(path.relative_to(home)), f'skipped: {type(error).__name__}; original preserved'))+ codex = home / '.codex/config.toml'+ if codex.parent.exists():+ try:+ result = merge_codex(codex, url, token, owned.get('.codex/config.toml'))+ results.append(('.codex/config.toml', result))+ if result in ('registered', 'up to date'):+ owned['.codex/config.toml'] = codex_entry(url, token)+ changed = True+ except (ValueError, OSError) as error:+ results.append(('.codex/config.toml', f'skipped: {type(error).__name__}; original preserved'))+ if changed:+ atomic(receipt, json.dumps(owned, indent=2) + "\n")+ return results+++def rpc(url, token, method, sid=None):+ headers = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json',+ 'Accept': 'application/json, text/event-stream', 'MCP-Protocol-Version': '2025-06-18'}+ if sid:+ headers['Mcp-Session-Id'] = sid+ request = urllib.request.Request(url, data=json.dumps({'jsonrpc': '2.0', 'id': 1,+ 'method': method, 'params': {'protocolVersion': '2025-06-18', 'capabilities': {},+ 'clientInfo': {'name': 'codegraff-installer', 'version': '1'}}}).encode(), headers=headers)+ # Never route loopback credentials through ambient HTTP proxies.+ with urllib.request.build_opener(urllib.request.ProxyHandler({})).open(request, timeout=2) as response:+ body = json.load(response)+ session = response.headers.get('Mcp-Session-Id')+ if session:+ request = urllib.request.Request(url, headers={**headers, 'Mcp-Session-Id': session}, method='DELETE')+ with urllib.request.build_opener(urllib.request.ProxyHandler({})).open(request, timeout=2):+ pass+ return body+++def ready(url, token):+ try:+ return rpc(url, token, 'initialize')['result']['serverInfo']['name'] == 'codegraff'+ except (OSError, ValueError, KeyError):+ return False+++def service(home, executable, directory, port, token):+ state = home / '.graff/mcp'+ command = [str(executable), 'mcp', 'serve', '--http', '--port', str(port)]+ if sys.platform == 'darwin':+ target = home / 'Library/LaunchAgents/dev.codegraff.mcp.plist'+ if target.exists() and plistlib.loads(target.read_bytes()).get('CodegraffManaged') != 1:+ raise ValueError('Existing launch agent is not managed by Codegraff')+ config = {'Label': 'dev.codegraff.mcp', 'CodegraffManaged': 1, 'ProgramArguments': command,+ 'WorkingDirectory': str(directory), 'EnvironmentVariables': {'GRAFF_MCP_TOKEN': token},+ 'RunAtLoad': True, 'KeepAlive': True, 'ThrottleInterval': 10,+ 'StandardOutPath': str(state / 'service.log'), 'StandardErrorPath': str(state / 'service.log')}+ atomic(target, plistlib.dumps(config).decode())+ domain = f'gui/{os.getuid()}'+ subprocess.run(['launchctl', 'bootout', domain + '/dev.codegraff.mcp'], capture_output=True)+ subprocess.run(['launchctl', 'bootstrap', domain, str(target)], check=True, capture_output=True)+ elif sys.platform.startswith('linux') and shutil.which('systemctl'):+ target = home / '.config/systemd/user/codegraff-mcp.service'+ if target.exists() and MARKER not in target.read_text():+ raise ValueError('Existing service is not managed by Codegraff')+ quote = lambda value: json.dumps(str(value).replace('%', '%%').replace('$', '$$'))+ atomic(target, MARKER + '\n[Unit]\nDescription=Codegraff local MCP\n[Service]\n' ++ 'ExecStart=' + ' '.join(quote(part) for part in command) + '\n' ++ 'WorkingDirectory=' + quote(directory) + '\nEnvironment=GRAFF_MCP_TOKEN=' + token ++ '\nRestart=on-failure\nRestartSec=10\n[Install]\nWantedBy=default.target\n')+ subprocess.run(['systemctl', '--user', 'daemon-reload'], check=True, capture_output=True)+ subprocess.run(['systemctl', '--user', 'enable', '--now', 'codegraff-mcp.service'], check=True, capture_output=True)+ subprocess.run(['systemctl', '--user', 'restart', 'codegraff-mcp.service'], check=True, capture_output=True)+ else:+ raise ValueError('Automatic service setup needs macOS launchd or Linux user systemd')+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument('--binary', required=True)+ parser.add_argument('--directory')+ parser.add_argument('--port', type=int)+ args = parser.parse_args()+ if os.environ.get('GRAFF_NO_MCP') == '1':+ print('MCP setup skipped (GRAFF_NO_MCP=1)')+ return+ settings_path = Path.home() / '.graff/mcp/settings.json'+ settings = json.loads(settings_path.read_text()) if settings_path.exists() else {}+ args.port = args.port or settings.get('port', 7720)+ args.directory = args.directory or settings.get('directory', str(Path.home()))+ if not 1 <= args.port <= 65535:+ raise ValueError('Invalid port')+ home = Path.home()+ directory = Path(args.directory).resolve(strict=True)+ if not directory.is_dir():+ raise ValueError('Workspace must be a directory')+ binary = Path(args.binary).resolve(strict=True)+ state = home / '.graff/mcp'+ state.mkdir(parents=True, exist_ok=True, mode=0o700)+ if state.is_symlink():+ raise ValueError('Refusing symlinked service directory')+ os.chmod(state, 0o700)+ lock_path = state / 'install.lock'+ if lock_path.is_symlink():+ raise ValueError('Refusing symlinked installer lock')+ install_lock = open(lock_path, 'a')+ os.chmod(lock_path, 0o600)+ fcntl.flock(install_lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ token_path = state / 'token'+ if token_path.is_symlink():+ raise ValueError('Refusing symlinked token')+ token = token_path.read_text().strip() if token_path.exists() else secrets.token_hex(32)+ if not re.fullmatch('[0-9a-f]{64}', token):+ raise ValueError('Invalid stored service token')+ atomic(token_path, token + '\n')+ url = f'http://127.0.0.1:{args.port}/mcp'+ service(home, binary, directory, args.port, token)+ for _ in range(30):+ if ready(url, token):+ break+ time.sleep(.2)+ else:+ raise ValueError('Service did not become ready; client configs were not changed')+ atomic(settings_path, json.dumps({'port': args.port, 'directory': str(directory)}))+ for client, result in register(home, url, token):+ print(f'{client}: {result}')+ print(f'MCP ready at {url}; workspace: {directory}; approval-gated tasks. Restart clients to load it.')+++if __name__ == '__main__':+ try:+ main()+ except Exception as error:+ print(f'MCP setup failed: {type(error).__name__}: {error}', file=sys.stderr)+ sys.exit(1)diff --git a/scripts/test-install-mcp.py b/scripts/test-install-mcp.pynew file mode 100644index 00000000..e5611e49--- /dev/null+++ b/scripts/test-install-mcp.py@@ -0,0 +1,100 @@+#!/usr/bin/env python3+import importlib.util+import json+import os+from pathlib import Path+import plistlib+import tempfile+import sys+import unittest+from unittest.mock import patch++spec = importlib.util.spec_from_file_location('installer', Path(__file__).with_name('install-mcp.py'))+installer = importlib.util.module_from_spec(spec)+spec.loader.exec_module(installer)++class InstallTests(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.home = Path(self.tmp.name)+ self.url = 'http://127.0.0.1:7720/mcp'+ self.token = 'a' * 64++ def test_additive_idempotent_clients(self):+ cursor = self.home / '.cursor/mcp.json'+ cursor.parent.mkdir()+ cursor.write_text(json.dumps({'mcpServers': {'other': {'env': {'KEY': 'retained'}}}, 'setting': 1}))+ codex = self.home / '.codex/config.toml'+ codex.parent.mkdir()+ codex.write_text('# keep comment\nmodel = "local"\n')+ installer.register(self.home, self.url, self.token)+ before = (cursor.read_bytes(), codex.read_bytes())+ installer.register(self.home, self.url, self.token)+ self.assertEqual(before, (cursor.read_bytes(), codex.read_bytes()))+ self.assertEqual(json.loads(cursor.read_text())['mcpServers']['other']['env']['KEY'], 'retained')+ self.assertTrue(codex.read_text().startswith('# keep comment'))+ self.assertEqual(cursor.stat().st_mode & 0o777, 0o600)++ def test_owned_entries_refresh_but_user_edits_survive(self):+ cursor = self.home / '.cursor/mcp.json'+ cursor.parent.mkdir()+ codex = self.home / '.codex/config.toml'+ codex.parent.mkdir()+ installer.register(self.home, self.url, self.token)+ new_url = 'http://127.0.0.1:7721/mcp'+ installer.register(self.home, new_url, self.token)+ self.assertEqual(json.loads(cursor.read_text())['mcpServers']['codegraff']['url'], new_url)+ if sys.version_info >= (3, 11):+ self.assertIn(new_url, codex.read_text())+ data = json.loads(cursor.read_text())+ data['mcpServers']['codegraff']['custom'] = True+ cursor.write_text(json.dumps(data))+ before = cursor.read_bytes()+ installer.register(self.home, self.url, self.token)+ self.assertEqual(cursor.read_bytes(), before)+ if sys.version_info >= (3, 11):+ self.assertIn(self.url, codex.read_text())++ def test_malformed_config_unchanged(self):+ path = self.home / '.cursor/mcp.json'+ path.parent.mkdir()+ path.write_text('{ broken')+ result = installer.register(self.home, self.url, self.token)+ self.assertIn('skipped', result[0][1])+ self.assertEqual(path.read_text(), '{ broken')++ def test_custom_codegraff_preserved(self):+ path = self.home / '.claude.json'+ source = '{"mcpServers":{"codegraff":{"command":"custom"}}}'+ path.write_text(source)+ installer.register(self.home, self.url, self.token)+ self.assertEqual(path.read_text(), source)++ def test_absent_clients_not_created(self):+ self.assertEqual(installer.register(self.home, self.url, self.token), [])+ self.assertEqual(list(self.home.iterdir()), [])++ def test_launch_agent_private_and_quoted(self):+ with patch.object(installer.sys, 'platform', 'darwin'), patch.object(installer.subprocess, 'run') as run:+ installer.service(self.home, Path('/Applications/A B.app/graff'), self.home, 7720, self.token)+ path = self.home / 'Library/LaunchAgents/dev.codegraff.mcp.plist'+ data = plistlib.loads(path.read_bytes())+ self.assertEqual(data['ProgramArguments'][0], '/Applications/A B.app/graff')+ self.assertEqual(data['EnvironmentVariables']['GRAFF_MCP_TOKEN'], self.token)+ self.assertEqual(path.stat().st_mode & 0o777, 0o600)+ self.assertEqual(run.call_count, 2)++ def test_unmanaged_service_preserved(self):+ path = self.home / 'Library/LaunchAgents/dev.codegraff.mcp.plist'+ path.parent.mkdir(parents=True)+ original = plistlib.dumps({'Label': 'custom'})+ path.write_bytes(original)+ with patch.object(installer.sys, 'platform', 'darwin'), patch.object(installer.subprocess, 'run') as run:+ with self.assertRaises(ValueError):+ installer.service(self.home, Path('/bin/echo'), self.home, 7720, self.token)+ run.assert_not_called()+ self.assertEqual(path.read_bytes(), original)++if __name__ == '__main__':+ unittest.main()diff --git a/scripts/test-mcp-http.py b/scripts/test-mcp-http.pynew file mode 100644index 00000000..9d04bd48--- /dev/null+++ b/scripts/test-mcp-http.py@@ -0,0 +1,89 @@+#!/usr/bin/env python3+"""Offline HTTP MCP regression: isolated HOME, no service manager or user configs."""+import http.client+import json+import os+from pathlib import Path+import socket+import subprocess+import tempfile+import time+import sys+sys.path.insert(0, str(Path(__file__).parent / 'eval'))+from mock_model import ScriptedModel+++def main():+ exe = str(Path('zig-out/bin/graff').resolve())+ with socket.socket() as sock:+ sock.bind(('127.0.0.1', 0))+ port = sock.getsockname()[1]+ token = 'a' * 64+ with tempfile.TemporaryDirectory() as home:+ env = {'HOME': home, 'PATH': os.environ['PATH'], 'GRAFF_MCP_TOKEN': token,+ 'GRAFF_NO_PLUGINS': '1', 'GRAFF_NO_TELEMETRY': '1', 'GRAFF_FLEET': 'off',+ 'GRAFF_NO_SMOLIFY': '1', 'LMSTUDIO_API_KEY': 'local'}+ process = subprocess.Popen([exe, 'mcp', 'serve', '--http', '--port', str(port), '--model', 'lmstudio'],+ env=env, cwd=home, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)+ def post(method='POST', body=None, sid=None, extra=None):+ connection = http.client.HTTPConnection('127.0.0.1', port, timeout=30)+ headers = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json',+ 'Accept': 'application/json, text/event-stream', 'MCP-Protocol-Version': '2025-06-18'}+ if sid:+ headers['Mcp-Session-Id'] = sid+ headers.update(extra or {})+ connection.request(method, '/mcp', json.dumps(body).encode() if body is not None else b'', headers)+ response = connection.getresponse()+ data = response.read()+ result = (response.status, json.loads(data) if data else None, response.getheader('Mcp-Session-Id'))+ connection.close()+ return result+ initialize = {'jsonrpc': '2.0', 'id': 1, 'method': 'initialize', 'params': {+ 'protocolVersion': '2025-06-18', 'capabilities': {}, 'clientInfo': {'name': 'test', 'version': '1'}}}+ try:+ for _ in range(100):+ try:+ status, result, sid = post(body=initialize)+ break+ except ConnectionRefusedError:+ if process.poll() is not None:+ raise AssertionError(process.stderr.read().decode())+ time.sleep(.05)+ else:+ raise AssertionError('HTTP server did not start')+ assert status == 200 and len(sid) == 32+ assert result['result']['serverInfo']['name'] == 'codegraff'+ assert post(body=initialize, extra={'Authorization': 'wrong'})[0] == 401+ assert post(body=initialize, extra={'Origin': 'https://unrelated.example'})[0] == 403+ assert post(body=initialize, extra={'Host': 'unrelated.example'})[0] == 403+ assert post('GET')[0] == 405+ assert post(body=initialize, extra={'MCP-Protocol-Version': 'invalid'})[0] == 400+ assert post(body={'jsonrpc': '2.0', 'method': 'notifications/initialized'}, sid=sid)[:2] == (202, None)+ status, listing, _ = post(body={'jsonrpc': '2.0', 'id': 2, 'method': 'tools/list'}, sid=sid)+ assert status == 200 and '_meta' not in listing['result']['tools'][0]+ initialize['params']['capabilities'] = {'extensions': {'io.modelcontextprotocol/ui': {'mimeTypes': ['text/html;profile=mcp-app']}}}+ _, _, second = post(body=initialize)+ assert second != sid+ post(body={'jsonrpc': '2.0', 'method': 'notifications/initialized'}, sid=second)+ _, listing, _ = post(body={'jsonrpc': '2.0', 'id': 2, 'method': 'tools/list'}, sid=second)+ assert listing['result']['tools'][0]['_meta']['ui']['resourceUri'] == 'ui://codegraff/task-result'+ _, resource, _ = post(body={'jsonrpc': '2.0', 'id': 3, 'method': 'resources/read', 'params': {'uri': 'ui://codegraff/task-result'}}, sid=second)+ assert 'class="workspace"' in resource['result']['contents'][0]['text']+ model = ScriptedModel([{'text': 'HTTP_TASK_OK'}] * 8, exhausted_text='HTTP_TASK_OK')+ model.start(1234)+ try:+ status, result, _ = post(body={'jsonrpc': '2.0', 'id': 4, 'method': 'tools/call', 'params': {'name': 'run_task', 'arguments': {'prompt': 'Reply HTTP_TASK_OK. A greeting; no tools needed.', 'timeout_seconds': 20}}}, sid=sid)+ assert status == 200 and not result['result']['isError'], result+ assert 'HTTP_TASK_OK' in result['result']['structuredContent']['text']+ finally:+ model.stop()+ assert post('DELETE', sid=sid)[0] == 204+ assert post(body={'jsonrpc': '2.0', 'id': 5, 'method': 'ping'}, sid=sid)[0] == 404+ assert post(body={'jsonrpc': '2.0', 'id': 6, 'method': 'ping'}, sid=second)[0] == 200+ finally:+ process.terminate()+ process.wait(timeout=10)+ print('HTTP MCP: authentication, origins, methods, isolated sessions, app resource, real task and deletion passed')++if __name__ == '__main__':+ main()diff --git a/scripts/test-mcp-server.py b/scripts/test-mcp-server.pynew file mode 100644index 00000000..e9505d53--- /dev/null+++ b/scripts/test-mcp-server.py@@ -0,0 +1,121 @@+#!/usr/bin/env python3+"""Offline MCP smoke test: real stdio server and child, local scripted model."""+import json+import os+from pathlib import Path+import subprocess+import sys+import tempfile++sys.path.insert(0, str(Path(__file__).resolve().parent / "eval"))+from mock_model import ScriptedModel+++def request(method, params=None, ident=None):+ obj = {"jsonrpc": "2.0", "method": method}+ if params is not None:+ obj["params"] = params+ if ident is not None:+ obj["id"] = ident+ return json.dumps(obj) + "\n"+++def exchange(exe, env, cwd, messages, extra=()):+ run = subprocess.run(+ [exe, "mcp", "serve", *extra], input=messages, text=True,+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, cwd=cwd,+ timeout=45,+ )+ assert run.returncode == 0, run.stderr+ return [json.loads(line) for line in run.stdout.splitlines()]+++def main():+ exe = str(Path(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff").resolve())+ handshake = request("initialize", {+ "protocolVersion": "2025-06-18", "capabilities": {},+ "clientInfo": {"name": "offline-test", "version": "1"},+ }, 1) + request("notifications/initialized")+ with tempfile.TemporaryDirectory(prefix="graff-mcp-test-") as workspace:+ env = {+ "PATH": os.environ.get("PATH", ""), "HOME": workspace,+ "GRAFF_NO_TELEMETRY": "1", "GRAFF_FLEET": "off",+ "GRAFF_NO_PLUGINS": "1", "GRAFF_NO_SMOLIFY": "1", "NO_COLOR": "1",+ }+ replies = exchange(exe, env, workspace, handshake + request("tools/list", {}, 2))+ assert replies[0]["result"]["capabilities"]["tools"] == {}+ assert replies[1]["result"]["tools"][0]["name"] == "run_task"+ assert "_meta" not in replies[1]["result"]["tools"][0]+ app_handshake = request("initialize", {+ "protocolVersion": "2025-06-18",+ "capabilities": {"extensions": {"io.modelcontextprotocol/ui": {+ "mimeTypes": ["text/html;profile=mcp-app"],+ }}}, "clientInfo": {"name": "offline-app-test", "version": "1"},+ }, 1) + request("notifications/initialized")+ replies = exchange(exe, env, workspace, app_handshake ++ request("tools/list", {}, 2) + request("resources/list", {}, 3) ++ request("resources/read", {"uri": "ui://codegraff/task-result"}, 4) ++ request("resources/read", {"uri": "file:///unavailable"}, 5) ++ request("resources/templates/list", {}, 6))+ tool = replies[1]["result"]["tools"][0]+ assert tool["_meta"]["ui"]["resourceUri"] == "ui://codegraff/task-result"+ assert tool["_meta"]["ui"]["visibility"] == ["model"]+ resource = replies[3]["result"]["contents"][0]+ assert replies[2]["result"]["resources"][0]["uri"] == resource["uri"]+ assert resource["mimeType"] == "text/html;profile=mcp-app"+ assert resource["text"] == (Path(__file__).resolve().parent.parent / "src/mcp_task_app.html").read_text().replace("/* CODEGRAFF_THEME */", (Path(__file__).resolve().parent.parent / "apps/native/app/ui-theme.css").read_text())+ assert resource["_meta"]["ui"]["csp"]["connectDomains"] == []+ assert replies[4]["error"]["code"] == -32002+ assert replies[5]["result"]["resourceTemplates"] == []+ # The real one-shot may request a second final to reconcile a prose-only+ # first turn. Both scripted replies are deterministic and offline.+ model = ScriptedModel([{"text": "MCP_TASK_OK"}] * 8, exhausted_text="MCP_TASK_OK")+ model.start(1234)+ try:+ env["LMSTUDIO_API_KEY"] = "local"+ call = request("tools/call", {"name": "run_task", "arguments": {+ "prompt": "Reply with MCP_TASK_OK. This is a greeting; no files or tools are needed.",+ "timeout_seconds": 20, "max_model_calls": 8,+ }}, "task")+ replies = exchange(exe, env, workspace, handshake + call + request("ping", {}, 3), ("--model", "lmstudio"))+ assert replies[1]["id"] == "task"+ result = replies[1]["result"]+ assert not result["isError"], result+ assert "MCP_TASK_OK" in result["content"][0]["text"], result+ assert result["structuredContent"]["status"] == "completed"+ assert result["structuredContent"]["text"] == result["content"][0]["text"]+ assert result["structuredContent"]["timeout_seconds"] == 20+ assert replies[2]["result"] == {}+ assert model.requests, "task never reached the scripted model"+ finally:+ model.stop()+ for yolo in (False, True):+ target = Path(workspace) / "permission-check.txt"+ model = ScriptedModel([+ {"tool": "write_file", "arguments": {"path": "permission-check.txt", "content": "MCP_EDIT_OK"}},+ {"text": "Permission check complete."},+ ])+ model.start(1234)+ try:+ call = request("tools/call", {"name": "run_task", "arguments": {+ "prompt": "Write permission-check.txt containing MCP_EDIT_OK.",+ "timeout_seconds": 20,+ }}, 2)+ extra = ("--model", "lmstudio") + (("--yolo",) if yolo else ())+ exchange(exe, env, workspace, handshake + call, extra)+ assert target.exists() == yolo, f"server permission mode did not govern file writes (yolo={yolo})"+ assert model.requests, "permission fixture never reached the model"+ if yolo:+ assert target.read_text() == "MCP_EDIT_OK"+ finally:+ model.stop()+ nested = dict(env, GRAFF_MCP_TASK="1")+ run = subprocess.run([exe, "mcp", "serve"], input="", text=True,+ capture_output=True, env=nested, cwd=workspace, timeout=10)+ assert run.returncode != 0+ assert not run.stdout+ print("MCP server: discovery, app negotiation and resources, structured results, real task, permission modes, ping, recursion guard passed")+++if __name__ == "__main__":+ main()diff --git a/scripts/test-mcp-task-app.cjs b/scripts/test-mcp-task-app.cjsnew file mode 100644index 00000000..04d6b5ae--- /dev/null+++ b/scripts/test-mcp-task-app.cjs@@ -0,0 +1,58 @@+#!/usr/bin/env node+// Offline browser regression for the bundled app in an opaque sandbox.+const {chromium} = require('../apps/native/node_modules/@playwright/test');+const {readFileSync} = require('node:fs');+const assert = require('node:assert/strict');+(async () => {+ const browser = await chromium.launch({channel:'chrome',headless:true});+ try {+ const page = await browser.newPage({viewport:{width:820,height:800}});+ const errors=[];page.on('pageerror',error=>errors.push(error.message));+ await page.setContent('<iframe title="Task app" sandbox="allow-scripts" style="border:0;width:100%;height:760px"></iframe>');+ await page.evaluate(html=>{+ window.received=[];+ const frame=document.querySelector('iframe');+ window.deliver=params=>frame.contentWindow.postMessage({jsonrpc:'2.0',...params},'*');+ window.addEventListener('message',event=>{+ if(event.source!==frame.contentWindow)return;+ window.received.push(event.data);+ if(event.data.method==='ui/initialize')window.deliver({id:event.data.id,result:{protocolVersion:'2026-01-26',hostCapabilities:{},hostContext:{theme:'light'}}});+ });+ frame.srcdoc=html;+ },readFileSync(require('node:path').join(__dirname,'../src/mcp_task_app.html'),'utf8').replace('/* CODEGRAFF_THEME */',readFileSync(require('node:path').join(__dirname,'../apps/native/app/ui-theme.css'),'utf8')));+ await page.waitForFunction(()=>window.received.some(m=>m.method==='ui/notifications/initialized'));+ const app=page.frames()[1];+ await page.evaluate(()=>{+ window.deliver({method:'ui/notifications/tool-input',params:{arguments:{prompt:'Explain the configuration parser. Cite relevant files.',timeout_seconds:90,max_model_calls:6}}});+ window.deliver({method:'ui/notifications/tool-result',params:{content:[{type:'text',text:'fallback'}],structuredContent:{text:'Configuration parser review\n\nconfig.zig:42 — Missing keys retain defaults.\nconfig.zig:78 — Invalid values return a typed error.\n\nNo files changed.\n<img src=x onerror=alert(1)>',status:'completed',timeout_seconds:90,max_model_calls:6,output_truncated:false},isError:false}});+ });+ await app.locator('#status').filter({hasText:'Completed'}).waitFor();+ assert.equal(await app.locator('#output img').count(),0);+ assert.match(await app.locator('#output').innerText(),/<img src=x/);+ await app.locator('#search').fill('config.zig');+ assert.equal(await app.locator('#count').innerText(),'2 of 7 lines');+ assert.doesNotMatch(await app.locator('#output').innerText(),/<img/);+ await app.locator('#search').fill('');await app.locator('#wrap').uncheck();+ assert.match(await app.locator('#output').getAttribute('class'),/nowrap/);+ await app.locator('#wrap').check();await app.locator('summary').click();+ await page.screenshot({path:'/tmp/codegraff-mcp-task-app.png'});+ await page.evaluate(()=>window.deliver({method:'ui/notifications/tool-result',params:{content:[{type:'text',text:'Partial answer'}],isError:true,structuredContent:{text:'Partial answer',status:'timed_out',output_truncated:true}}}));+ await app.locator('#status').filter({hasText:'Timed out'}).waitFor();+ assert.equal(await app.locator('#clipped').isVisible(),true);+ await page.evaluate(()=>window.deliver({method:'ui/notifications/host-context-changed',params:{theme:'dark'}}));+ await app.waitForFunction(()=>document.documentElement.dataset.theme==='dark');+ await page.setViewportSize({width:380,height:760});+ assert.equal(await app.evaluate(()=>document.documentElement.scrollWidth<=window.innerWidth),true);+ await page.evaluate(()=>window.deliver({method:'ui/notifications/tool-cancelled',params:{}}));+ await app.locator('#status').filter({hasText:'Cancelled'}).waitFor();+ await page.evaluate(()=>window.deliver({method:'ui/notifications/tool-result',params:{content:[{type:'text',text:'Plain result fallback'}],isError:false}}));+ await app.locator('#output').filter({hasText:'Plain result fallback'}).waitFor();+ await app.evaluate(()=>window.postMessage({jsonrpc:'2.0',method:'ui/notifications/tool-result',params:{content:[{type:'text',text:'Unexpected sender'}]}},'*'));+ assert.equal(await app.locator('#output').innerText(),'Plain result fallback');+ await page.evaluate(()=>window.deliver({method:'ui/resource-teardown',id:99,params:{}}));+ await page.waitForFunction(()=>window.received.some(m=>m.id===99&&m.result));+ assert.deepEqual(errors,[]);+ assert.equal(await page.evaluate(()=>window.received.some(m=>m.method==='tools/call')),false);+ console.log('MCP task app: sandbox handshake, result, text rendering, filtering, wrapping, themes, mobile layout, cancellation and teardown passed');+ } finally {await browser.close();}+})().catch(error=>{console.error(error);process.exitCode=1;});diff --git a/src/cli.zig b/src/cli.zigindex 683465c0..7a43f1f1 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -328,6 +328,8 @@ pub const usage_text =\\ graff mcp add <name> --url <url> add a Streamable HTTP MCP server\\ graff mcp login <name> OAuth login for a remote MCP server\\ graff mcp list configured MCP servers+ \\ graff mcp install configure local HTTP service and MCP clients+ \\ graff mcp serve [--http] [--port N] expose run_task to MCP clients\\ graff plugins [load <name>] list Claude/Cursor/Grok/Codex plugin trees (in place)\\ graff learn [help] local mutate/evaluate/promote/rollback engine\\ graff worktree list list -w tabs and experiment-pool trees (tagged)diff --git a/src/main.zig b/src/main.zigindex a936d341..bd277b9c 100644--- a/src/main.zig+++ b/src/main.zig@@ -563,7 +563,7 @@ const workflow = @import("workflow_test.zig"); // the engine's tests live here (const exec = @import("exec.zig");test { // ── Unit tests (`zig build test`): pull in tests from imported modules (mcp.zig)_ = .{ @import("mcp_apps.zig"), @import("html_view.zig"), @import("providers_confirmation_tests.zig"), @import("repl_model_confirmation_tests.zig"), @import("repl_model_pick_tests.zig"), @import("engine_sink_citation_tests.zig"), @import("cite_markup_stream_tests.zig"), @import("oneshot_citation_tests.zig"), @import("tui_acp.zig") };- _ = .{ @import("main_test.zig"), @import("artifact_claim_command.zig"), @import("cli_path_hint.zig"), @import("run_budget.zig") };+ _ = .{ @import("mcp_server_tests.zig"), @import("main_test.zig"), @import("artifact_claim_command.zig"), @import("cli_path_hint.zig"), @import("run_budget.zig") };_ = @import("session_catalog.zig");_ = @import("session_prompt.zig");_ = @import("prompt_astra.zig");diff --git a/src/mcp_cli.zig b/src/mcp_cli.zigindex e86c52d4..0dbf5a21 100644--- a/src/mcp_cli.zig+++ b/src/mcp_cli.zig@@ -141,6 +141,8 @@ pub fn persistMcpUrl(io: Io, arena: Allocator, name: []const u8, url: []const u8fn mcpCliUsage(w: *Io.Writer) !void {try w.writeAll(\\usage:+ \\ graff mcp install [--directory PATH] [--port N] install HTTP service and client entries+ \\ graff mcp serve [--http] [--port N] [--model NAME] [--yolo] expose run_task over stdio or HTTP\\ graff mcp list servers in .mcp.json + ~/.codegraff/mcp.json\\ graff mcp import copy Claude/Cursor MCP + skills into graff folders\\ graff mcp add <name> --url <https://...> [--header KEY=VALUE ...]@@ -159,6 +161,24 @@ fn mcpCliUsage(w: *Io.Writer) !void {}pub fn mcpCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, environ_map: anytype, args: []const []const u8) !void {+ if (args.len > 0 and std.mem.eql(u8, args[0], "install")) {+ const exe = try std.process.executablePathAlloc(io, arena);+ var argv: std.ArrayList([]const u8) = .empty;+ try argv.appendSlice(arena, &.{ "python3", "-c", @embedFile("mcp_installer"), "--binary", exe });+ try argv.appendSlice(arena, args[1..]);+ const result = try @import("process_runner.zig").runCappedWithOptions(arena, io, argv.items, 16384, 4096, 30000, .{ .environ_map = environ_map });+ var buffer: [4096]u8 = undefined;+ var writer = Io.File.stderr().writer(io, &buffer);+ try writer.interface.writeAll(result.stdout);+ try writer.interface.writeAll(result.stderr);+ try writer.interface.flush();+ if (!@import("process_runner.zig").ranOk(result)) return error.McpInstallFailed;+ return;+ }+ if (args.len > 0 and std.mem.eql(u8, args[0], "serve")) {+ try @import("mcp_server.zig").run(io, gpa, environ_map, args[1..]);+ return;+ }var obuf: [4096]u8 = undefined;var out = Io.File.stdout().writer(io, &obuf);// Reads (list/login) see project + global; writes stay project-local.diff --git a/src/mcp_server.zig b/src/mcp_server.zignew file mode 100644index 00000000..5cb920cd--- /dev/null+++ b/src/mcp_server.zig@@ -0,0 +1,216 @@+//! Local stdio MCP task adapter. Each call owns a bounded, fresh CLI child.+const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const Value = std.json.Value;+const app = @import("mcp_server_app.zig");+const runner = @import("process_runner.zig");++pub const Task = struct {+ prompt: []const u8,+ timeout_seconds: u64 = 120,+ max_model_calls: u64 = 8,+};+pub const Result = struct { text: []const u8, isError: bool = false, timed_out: bool = false, cancelled: bool = false, output_truncated: bool = false };+pub const Execute = *const fn (?*anyopaque, Allocator, Task) anyerror!Result;++pub const Server = struct {+ initialized: bool = false,+ ready: bool = false,+ apps: bool = false,+ execute: Execute,+ context: ?*anyopaque = null,++ pub fn handle(self: *Server, a: Allocator, out: *Io.Writer, line: []const u8) !void {+ const request = std.json.parseFromSliceLeaky(Value, a, line, .{}) catch+ return failure(out, .null, -32700, "Parse error");+ if (request != .object) return failure(out, .null, -32600, "Invalid Request");+ const id = request.object.get("id") orelse Value.null;+ if (id != .null and id != .string and id != .integer)+ return failure(out, .null, -32600, "Invalid request id");+ const version = string(request, "jsonrpc") orelse "";+ const method = string(request, "method") orelse "";+ if (!std.mem.eql(u8, version, "2.0") or method.len == 0)+ return failure(out, id, -32600, "Invalid Request");+ if (!request.object.contains("id")) {+ if (self.initialized and std.mem.eql(u8, method, "notifications/initialized")) self.ready = true;+ return;+ }+ const params = request.object.get("params") orelse Value.null;+ if (std.mem.eql(u8, method, "ping")) return reply(out, id, struct {}{});+ if (std.mem.eql(u8, method, "initialize")) {+ if (self.initialized) return failure(out, id, -32600, "Already initialized");+ const requested = string(params, "protocolVersion") orelse+ return failure(out, id, -32602, "protocolVersion is required");+ const protocol = if (std.mem.eql(u8, requested, "2024-11-05") or std.mem.eql(u8, requested, "2025-03-26") or std.mem.eql(u8, requested, "2025-06-18")) requested else "2025-06-18";+ self.apps = app.supported(params);+ self.initialized = true;+ return reply(out, id, .{+ .protocolVersion = protocol,+ .capabilities = .{ .tools = struct {}{}, .resources = struct {}{} },+ .serverInfo = .{ .name = "codegraff", .title = "Codegraff", .version = @import("main.zig").harness_version },+ .instructions = "Delegate a small, self-contained task with run_task. Tasks run serially in the server launch directory with fresh context. Include scope and acceptance criteria; inspect the result and changes before integrating.",+ });+ }+ if (!self.ready) return failure(out, id, -32000, "Initialize the server first");+ if (std.mem.eql(u8, method, "tools/list")) {+ const catalog = try app.catalog(a, tool_catalog, self.apps);+ return reply(out, id, catalog);+ }+ if (std.mem.eql(u8, method, "resources/list")) return reply(out, id, .{ .resources = .{app.resource} });+ if (std.mem.eql(u8, method, "resources/templates/list")) return reply(out, id, .{ .resourceTemplates = [0]struct {}{} });+ if (std.mem.eql(u8, method, "resources/read")) {+ const uri = string(params, "uri") orelse return failure(out, id, -32602, "Resource URI is required");+ if (!std.mem.eql(u8, uri, app.uri)) return failure(out, id, -32002, "Resource not found");+ return reply(out, id, app.contents());+ }+ if (!std.mem.eql(u8, method, "tools/call")) return failure(out, id, -32601, "Method not found");+ const name = string(params, "name") orelse return failure(out, id, -32602, "Tool name is required");+ if (!std.mem.eql(u8, name, "run_task")) return failure(out, id, -32602, "Unknown tool");+ const input = params.object.get("arguments") orelse Value.null;+ const task = parseTask(input) catch return failure(out, id, -32602, "Expected prompt (1-32768 bytes), timeout_seconds (1-300), max_model_calls (1-32); no other arguments");+ const result = self.execute(self.context, a, task) catch |err| Result{+ .text = try std.fmt.allocPrint(a, "Task could not run: {s}", .{@errorName(err)}),+ .isError = true,+ };+ return reply(out, id, .{ .content = .{.{ .type = "text", .text = result.text }}, .isError = result.isError, .structuredContent = .{+ .text = result.text,+ .status = if (result.timed_out) "timed_out" else if (result.cancelled) "cancelled" else if (result.isError) "failed" else "completed",+ .output_truncated = result.output_truncated,+ .timeout_seconds = task.timeout_seconds,+ .max_model_calls = task.max_model_calls,+ } });+ }+};++fn string(value: Value, key: []const u8) ?[]const u8 {+ if (value != .object) return null;+ const v = value.object.get(key) orelse return null;+ return if (v == .string) v.string else null;+}++pub fn parseTask(input: Value) !Task {+ const prompt = string(input, "prompt") orelse return error.InvalidArguments;+ if (std.mem.trim(u8, prompt, " \r\n\t").len == 0 or prompt.len > 32768 or std.mem.indexOfScalar(u8, prompt, 0) != null) return error.InvalidArguments;+ var task: Task = .{ .prompt = prompt };+ var it = input.object.iterator();+ while (it.next()) |entry| {+ const key = entry.key_ptr.*;+ if (std.mem.eql(u8, key, "prompt")) continue;+ const v = entry.value_ptr.*;+ if (v != .integer or v.integer < 1) return error.InvalidArguments;+ if (std.mem.eql(u8, key, "timeout_seconds") and v.integer <= 300) {+ task.timeout_seconds = @intCast(v.integer);+ } else if (std.mem.eql(u8, key, "max_model_calls") and v.integer <= 32) {+ task.max_model_calls = @intCast(v.integer);+ } else return error.InvalidArguments;+ }+ return task;+}++fn reply(out: *Io.Writer, id: Value, result: anytype) !void {+ var json: std.json.Stringify = .{ .writer = out };+ try json.write(.{ .jsonrpc = "2.0", .id = id, .result = result });+ try out.writeByte('\n');+}+fn failure(out: *Io.Writer, id: Value, code: i32, message: []const u8) !void {+ var json: std.json.Stringify = .{ .writer = out };+ try json.write(.{ .jsonrpc = "2.0", .id = id, .@"error" = .{ .code = code, .message = message } });+ try out.writeByte('\n');+}++pub fn serve(gpa: Allocator, in: *Io.Reader, out: *Io.Writer, server: *Server) !void {+ var scratch = std.heap.ArenaAllocator.init(gpa);+ defer scratch.deinit();+ while (true) {+ const line = in.takeDelimiter('\n') catch |err| switch (err) {+ error.StreamTooLong => {+ _ = in.discardDelimiterInclusive('\n') catch |discard_err| switch (discard_err) {+ error.EndOfStream => return,+ else => return discard_err,+ };+ try failure(out, .null, -32600, "Request exceeds 64 KiB");+ try out.flush();+ continue;+ },+ else => return err,+ } orelse return;+ try server.handle(scratch.allocator(), out, line);+ try out.flush();+ _ = scratch.reset(.retain_capacity);+ }+}++const Context = struct {+ io: Io,+ exe: []const u8,+ env: *const std.process.Environ.Map,+ model: ?[]const u8 = null,+ yolo: bool = false,+};++fn execute(raw: ?*anyopaque, a: Allocator, task: Task) !Result {+ const ctx: *Context = @ptrCast(@alignCast(raw.?));+ var argv: std.ArrayList([]const u8) = .empty;+ try argv.appendSlice(a, &.{ ctx.exe, "--no-resume", if (ctx.yolo) "--yolo" else "--safe", "--max-model-calls", try std.fmt.allocPrint(a, "{d}", .{task.max_model_calls}), "--max-tool-calls", "64" });+ if (ctx.model) |model| try argv.appendSlice(a, &.{ "--model", model });+ try argv.appendSlice(a, &.{ "-p", task.prompt });+ const run_result = try runner.runCappedWithOptions(a, ctx.io, argv.items, 64 * 1024, 16 * 1024, task.timeout_seconds * 1000, .{ .environ_map = ctx.env, .kill_process_tree = true });+ return formatResult(a, run_result);+}++pub fn formatResult(a: Allocator, result: runner.CappedRun) !Result {+ const ok = runner.ranOk(result) and !result.cancelled and !result.timed_out;+ const suffix = if (result.timed_out) "\n[Task timed out; partial work may remain.]" else if (result.cancelled) "\n[Task cancelled; partial work may remain.]" else if (!ok) "\n[Task failed; partial work may remain.]" else "";+ return .{+ .text = try std.fmt.allocPrint(a, "{s}{s}{s}{s}{s}", .{+ result.stdout,+ if (result.stdout_truncated) "\n[Task output truncated at 64 KiB.]" else "",+ suffix,+ if (!ok) result.stderr else "",+ if (!ok and result.stderr_truncated) "\n[Diagnostics truncated at 16 KiB.]" else "",+ }),+ .isError = !ok,+ .timed_out = result.timed_out,+ .cancelled = result.cancelled,+ .output_truncated = result.stdout_truncated or (!ok and result.stderr_truncated),+ };+}++pub fn run(io: Io, gpa: Allocator, parent: *const std.process.Environ.Map, args: []const []const u8) !void {+ if (parent.get("GRAFF_MCP_TASK") != null) return error.NestedMcpTaskServer;+ const exe = try std.process.executablePathAlloc(io, gpa);+ defer gpa.free(exe);+ var env = std.process.Environ.Map.init(gpa);+ defer env.deinit();+ for (parent.keys(), parent.values()) |key, value| try env.put(key, value);+ try env.put("GRAFF_MCP_TASK", "1");+ var ctx: Context = .{ .io = io, .exe = exe, .env = &env };+ var port: ?u16 = null;+ var i: usize = 0;+ while (i < args.len) : (i += 1) {+ if (std.mem.eql(u8, args[i], "--http")) {+ port = 7720;+ } else if (std.mem.eql(u8, args[i], "--port") and i + 1 < args.len) {+ i += 1;+ port = try std.fmt.parseInt(u16, args[i], 10);+ if (port.? == 0) return error.InvalidMcpPort;+ } else if (std.mem.eql(u8, args[i], "--yolo")) {+ ctx.yolo = true;+ } else if (std.mem.eql(u8, args[i], "--model") and i + 1 < args.len) {+ i += 1;+ ctx.model = args[i];+ } else return error.InvalidMcpServeOption;+ }+ if (port) |http_port| return @import("mcp_server_http.zig").run(io, gpa, http_port, parent.get("GRAFF_MCP_TOKEN") orelse return error.McpHttpTokenRequired, .{ .execute = execute, .context = &ctx });+ var read_buf: [64 * 1024]u8 = undefined;+ var in = Io.File.stdin().reader(io, &read_buf);+ var write_buf: [4096]u8 = undefined;+ var out = Io.File.stdout().writer(io, &write_buf);+ var server: Server = .{ .execute = execute, .context = &ctx };+ try serve(gpa, &in.interface, &out.interface, &server);+}++const tool_catalog =+ \\{"tools":[{"name":"run_task","description":"Run a small, self-contained task with Codegraff in the server launch directory. Fresh context per call; include relevant context, scope and acceptance criteria. May edit files and execute commands when server permissions allow. Returns the answer or an explicit failure with partial output. Calls run serially; no continuation or cancellation handle.","inputSchema":{"type":"object","properties":{"prompt":{"type":"string","minLength":1,"maxLength":32768},"timeout_seconds":{"type":"integer","minimum":1,"maximum":300,"default":120},"max_model_calls":{"type":"integer","minimum":1,"maximum":32,"default":8}},"required":["prompt"],"additionalProperties":false},"annotations":{"readOnlyHint":false,"destructiveHint":true,"idempotentHint":false,"openWorldHint":true}}]}+;diff --git a/src/mcp_server_app.zig b/src/mcp_server_app.zignew file mode 100644index 00000000..0997525a--- /dev/null+++ b/src/mcp_server_app.zig@@ -0,0 +1,55 @@+//! Optional presentation for the stdio task tool; no execution authority.+const std = @import("std");+const Value = std.json.Value;+pub const uri = "ui://codegraff/task-result";+pub const mime = "text/html;profile=mcp-app";+pub const resource = .{ .uri = uri, .name = "task_result", .title = "Codegraff task result", .description = "Inspect task output, limits and completion status.", .mimeType = mime };++fn get(value: Value, key: []const u8) Value {+ return if (value == .object) value.object.get(key) orelse .null else .null;+}++pub fn supported(params: Value) bool {+ const types = get(get(get(get(params, "capabilities"), "extensions"), "io.modelcontextprotocol/ui"), "mimeTypes");+ if (types != .array) return false;+ for (types.array.items) |item| {+ if (item == .string and std.mem.eql(u8, item.string, mime)) return true;+ }+ return false;+}++pub fn catalog(a: std.mem.Allocator, source: []const u8, apps: bool) !Value {+ const value = try std.json.parseFromSliceLeaky(Value, a, source, .{});+ const tool = &value.object.get("tools").?.array.items[0];+ try tool.object.put(a, "title", .{ .string = "Run a Codegraff task" });+ if (apps) {+ const meta = try std.json.parseFromSliceLeaky(Value, a,+ \\{"ui":{"resourceUri":"ui://codegraff/task-result","visibility":["model"]}}+ , .{});+ try tool.object.put(a, "_meta", meta);+ }+ const schema = try std.json.parseFromSliceLeaky(Value, a,+ \\{"type":"object","properties":{"text":{"type":"string"},"status":{"type":"string","enum":["completed","failed","timed_out","cancelled"]},"output_truncated":{"type":"boolean"},"timeout_seconds":{"type":"integer"},"max_model_calls":{"type":"integer"}},"required":["text","status","output_truncated","timeout_seconds","max_model_calls"],"additionalProperties":false}+ , .{});+ try tool.object.put(a, "outputSchema", schema);+ return value;+}++const template = @embedFile("mcp_task_app.html");+const marker = "/* CODEGRAFF_THEME */";+const theme_offset = std.mem.indexOf(u8, template, marker).?;+const html = template[0..theme_offset] ++ @embedFile("ui_theme") ++ template[theme_offset + marker.len ..];++const payload = .{ .contents = .{.{+ .uri = uri,+ .mimeType = mime,+ .text = html,+ ._meta = .{ .ui = .{+ .csp = .{ .connectDomains = [0][]const u8{}, .resourceDomains = [0][]const u8{} },+ .prefersBorder = true,+ } },+}} };++pub fn contents() @TypeOf(payload) {+ return payload;+}diff --git a/src/mcp_server_http.zig b/src/mcp_server_http.zignew file mode 100644index 00000000..91260321--- /dev/null+++ b/src/mcp_server_http.zig@@ -0,0 +1,126 @@+//! Loopback Streamable HTTP adapter; task execution remains in mcp_server.+const std = @import("std");+const Io = std.Io;+const mcp = @import("mcp_server.zig");+const Value = std.json.Value;+const Session = struct { id: [32]u8, server: mcp.Server };+const State = struct {+ io: Io,+ allocator: std.mem.Allocator,+ token: []const u8,+ port: u16,+ prototype: mcp.Server,+ mutex: Io.Mutex = .init,+ sessions: [64]?Session = @splat(null),+ next: usize = 0,+};++pub fn run(io: Io, a: std.mem.Allocator, port: u16, token: []const u8, prototype: mcp.Server) !void {+ if (token.len < 32 or std.mem.indexOfAny(u8, token, "\r\n") != null) return error.InvalidMcpHttpToken;+ const addr = try Io.net.IpAddress.parse("127.0.0.1", port);+ var listener = try addr.listen(io, .{ .reuse_address = true });+ defer listener.deinit(io);+ var group: Io.Group = .init;+ defer group.cancel(io);+ var state: State = .{ .io = io, .allocator = a, .token = token, .port = port, .prototype = prototype };+ @import("serve.zig").serveLog(io, "Codegraff MCP listening at http://127.0.0.1:{d}/mcp", .{port});+ while (true) {+ const stream = try listener.accept(io);+ group.concurrent(io, connection, .{ &state, stream }) catch stream.close(io);+ }+}++fn connection(st: *State, stream: Io.net.Stream) void {+ defer stream.close(st.io);+ var rb: [16 * 1024]u8 = undefined;+ var wb: [4096]u8 = undefined;+ var reader = Io.net.Stream.Reader.init(stream, st.io, &rb);+ var writer = Io.net.Stream.Writer.init(stream, st.io, &wb);+ var http = std.http.Server.init(&reader.interface, &writer.interface);+ var request = http.receiveHead() catch return;+ handle(st, &request) catch return;+}++fn respond(req: *std.http.Server.Request, status: std.http.Status, body: []const u8, sid: ?[]const u8) !void {+ var headers = [_]std.http.Header{+ .{ .name = "content-type", .value = "application/json" },+ .{ .name = "cache-control", .value = "no-store" },+ .{ .name = "Mcp-Session-Id", .value = sid orelse "" },+ };+ try req.respond(body, .{ .status = status, .keep_alive = false, .extra_headers = headers[0..if (sid != null) 3 else 2] });+}++fn handle(st: *State, req: *std.http.Server.Request) !void {+ var arena = std.heap.ArenaAllocator.init(st.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ if (!std.mem.eql(u8, req.head.target, "/mcp")) return respond(req, .not_found, "{}", null);+ const host = try std.fmt.allocPrint(a, "127.0.0.1:{d}", .{st.port});+ const origin = try std.fmt.allocPrint(a, "http://{s}", .{host});+ const bearer = try std.fmt.allocPrint(a, "Bearer {s}", .{st.token});+ var authorized = false;+ var host_ok = false;+ var sid: ?[]const u8 = null;+ var json_type = false;+ var headers = req.iterateHeaders();+ while (headers.next()) |h| {+ if (std.ascii.eqlIgnoreCase(h.name, "host")) host_ok = std.mem.eql(u8, h.value, host);+ if (std.ascii.eqlIgnoreCase(h.name, "origin") and !std.mem.eql(u8, h.value, origin)) return respond(req, .forbidden, "{}", null);+ if (std.ascii.eqlIgnoreCase(h.name, "authorization")) authorized = equalToken(h.value, bearer);+ if (std.ascii.eqlIgnoreCase(h.name, "mcp-session-id")) sid = try a.dupe(u8, h.value);+ if (std.ascii.eqlIgnoreCase(h.name, "content-type")) json_type = std.mem.eql(u8, h.value, "application/json") or std.mem.startsWith(u8, h.value, "application/json;");+ if (std.ascii.eqlIgnoreCase(h.name, "mcp-protocol-version") and !std.mem.eql(u8, h.value, "2025-06-18") and !std.mem.eql(u8, h.value, "2025-03-26") and !std.mem.eql(u8, h.value, "2024-11-05")) return respond(req, .bad_request, "{}", null);+ }+ if (!host_ok) return respond(req, .forbidden, "{}", null);+ if (!authorized) return respond(req, .unauthorized, "{}", null);+ if (req.head.method != .POST and req.head.method != .DELETE) return respond(req, .method_not_allowed, "{}", null);+ try st.mutex.lock(st.io);+ defer st.mutex.unlock(st.io);+ var slot: ?*?Session = null;+ if (sid) |id| {+ for (&st.sessions) |*entry| if (entry.*) |s| {+ if (std.mem.eql(u8, &s.id, id)) {+ slot = entry;+ break;+ }+ };+ if (slot == null) return respond(req, .not_found, "{}", null);+ }+ if (req.head.method == .DELETE) {+ if (slot) |entry| entry.* = null else return respond(req, .bad_request, "{}", null);+ return respond(req, .no_content, "", null);+ }+ if (!json_type) return respond(req, .unsupported_media_type, "{}", null);+ if (req.head.content_length) |length| {+ if (length > 65536) return respond(req, .payload_too_large, "{}", null);+ }+ var buffer: [4096]u8 = undefined;+ const body_reader = try req.readerExpectContinue(&buffer);+ const body = body_reader.allocRemaining(a, .limited(65536)) catch return respond(req, .payload_too_large, "{}", null);+ const value = std.json.parseFromSliceLeaky(Value, a, body, .{}) catch return respond(req, .bad_request, "{}", null);+ if (value != .object) return respond(req, .bad_request, "{}", null);+ const method = value.object.get("method") orelse return respond(req, .bad_request, "{}", null);+ const initializing = method == .string and std.mem.eql(u8, method.string, "initialize");+ var fresh = st.prototype;+ const server = if (slot) |entry| &entry.*.?.server else &fresh;+ if (slot == null and !initializing) return respond(req, .bad_request, "{}", null);+ var output: Io.Writer.Allocating = .init(a);+ try server.handle(a, &output.writer, body);+ var new_id: ?[]const u8 = null;+ if (slot == null and fresh.initialized) {+ var bytes: [16]u8 = undefined;+ st.io.random(&bytes);+ const id = std.fmt.bytesToHex(bytes, .lower);+ st.sessions[st.next] = .{ .id = id, .server = fresh };+ new_id = &st.sessions[st.next].?.id;+ st.next = (st.next + 1) % st.sessions.len;+ }+ return respond(req, if (output.written().len == 0) .accepted else .ok, output.written(), new_id);+}++pub fn equalToken(a: []const u8, b: []const u8) bool {+ if (a.len != b.len) return false;+ var diff: u8 = 0;+ for (a, b) |x, y| diff |= x ^ y;+ return diff == 0;+}diff --git a/src/mcp_server_tests.zig b/src/mcp_server_tests.zignew file mode 100644index 00000000..67efe954--- /dev/null+++ b/src/mcp_server_tests.zig@@ -0,0 +1,154 @@+const std = @import("std");+const mcp = @import("mcp_server.zig");+const Value = std.json.Value;+const init = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\"}}\n" +++ "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n";++fn fake(_: ?*anyopaque, _: std.mem.Allocator, task: mcp.Task) !mcp.Result {+ if (std.mem.eql(u8, task.prompt, "fail")) return error.MockFailure;+ return .{ .text = task.prompt };+}+fn check(a: std.mem.Allocator, input: []const u8) ![]const u8 {+ var source = std.Io.Reader.fixed(input);+ var out: std.Io.Writer.Allocating = .init(a);+ var server: mcp.Server = .{ .execute = fake };+ try mcp.serve(a, &source, &out.writer, &server);+ return out.written();+}++test "MCP handshake discovery and tool call return newline framed JSON" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const result = try check(a, init +++ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\"}\n" +++ "{\"jsonrpc\":\"2.0\",\"id\":\"task\",\"method\":\"tools/call\",\"params\":{\"name\":\"run_task\",\"arguments\":{\"prompt\":\"hello\\nworld\"}}}\n");+ var lines = std.mem.tokenizeScalar(u8, result, '\n');+ const hello = try std.json.parseFromSliceLeaky(Value, a, lines.next().?, .{});+ try std.testing.expectEqualStrings("codegraff", hello.object.get("result").?.object.get("serverInfo").?.object.get("name").?.string);+ try std.testing.expect(hello.object.get("result").?.object.get("capabilities").?.object.get("tools").? == .object);+ const list = try std.json.parseFromSliceLeaky(Value, a, lines.next().?, .{});+ const tool = list.object.get("result").?.object.get("tools").?.array.items[0];+ try std.testing.expectEqualStrings("run_task", tool.object.get("name").?.string);+ const call = try std.json.parseFromSliceLeaky(Value, a, lines.next().?, .{});+ try std.testing.expectEqualStrings("task", call.object.get("id").?.string);+ try std.testing.expectEqualStrings("hello\nworld", call.object.get("result").?.object.get("content").?.array.items[0].object.get("text").?.string);+ try std.testing.expect(lines.next() == null);+}++test "MCP rejects malformed requests and recovers for ping" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const result = try check(arena.allocator(), "{bad\n[]\n{\"jsonrpc\":\"2.0\",\"id\":{},\"method\":\"ping\"}\n" +++ "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"ping\"}\n");+ try std.testing.expectEqual(@as(usize, 4), std.mem.count(u8, result, "\n"));+ try std.testing.expect(std.mem.indexOf(u8, result, "-32700") != null);+ try std.testing.expect(std.mem.indexOf(u8, result, "\"id\":4,\"result\":{}") != null);+}++test "MCP rejects calls before initialization and ignores notifications" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const result = try check(arena.allocator(), "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}\n" +++ "{\"jsonrpc\":\"2.0\",\"method\":\"tools/call\",\"params\":{\"name\":\"run_task\",\"arguments\":{\"prompt\":\"fail\"}}}\n");+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, result, "\n"));+ try std.testing.expect(std.mem.indexOf(u8, result, "Initialize the server first") != null);+}++test "MCP argument validation bounds work and rejects configuration injection" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ for ([_][]const u8{+ "null", "{}", "{\"prompt\":\" \"}", "{\"prompt\":2}",+ "{\"prompt\":\"x\",\"timeout_seconds\":0}", "{\"prompt\":\"x\",\"timeout_seconds\":301}", "{\"prompt\":\"x\",\"max_model_calls\":33}", "{\"prompt\":\"x\",\"max_model_calls\":1.5}",+ "{\"prompt\":\"x\",\"cwd\":\"/tmp\"}", "{\"prompt\":\"x\",\"yolo\":true}", "{\"prompt\":\"x\\u0000y\"}",+ }) |input| {+ const value = try std.json.parseFromSliceLeaky(Value, a, input, .{});+ try std.testing.expectError(error.InvalidArguments, mcp.parseTask(value));+ }+ const task = try mcp.parseTask(try std.json.parseFromSliceLeaky(Value, a, "{\"prompt\":\"x\",\"timeout_seconds\":300,\"max_model_calls\":32}", .{}));+ try std.testing.expectEqual(@as(u64, 300), task.timeout_seconds);+ try std.testing.expectEqual(@as(u64, 32), task.max_model_calls);+}++test "MCP execution errors are tool errors and server remains usable" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const result = try check(arena.allocator(), init +++ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"run_task\",\"arguments\":{\"prompt\":\"fail\"}}}\n" +++ "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"ping\"}\n");+ try std.testing.expect(std.mem.indexOf(u8, result, "\"isError\":true") != null);+ try std.testing.expect(std.mem.indexOf(u8, result, "MockFailure") != null);+ try std.testing.expect(std.mem.indexOf(u8, result, "\"id\":3,\"result\":{}") != null);+}++test "MCP failed task preserves partial output and truncation markers" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const result = try mcp.formatResult(a, .{+ .term = .{ .exited = 1 },+ .stdout = try a.dupe(u8, "partial"),+ .stderr = try a.dupe(u8, "diagnostic"),+ .stdout_truncated = true,+ .stderr_truncated = true,+ .timed_out = true,+ });+ try std.testing.expect(result.isError);+ try std.testing.expect(std.mem.startsWith(u8, result.text, "partial"));+ try std.testing.expect(std.mem.indexOf(u8, result.text, "timed out") != null);+ try std.testing.expect(std.mem.indexOf(u8, result.text, "Diagnostics truncated") != null);+}++test "MCP Apps negotiate metadata and serve only the declared resource" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const app = @import("mcp_server_app.zig");+ const params = try std.json.parseFromSliceLeaky(Value, a,+ \\{"capabilities":{"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}}}+ , .{});+ try std.testing.expect(app.supported(params));+ try std.testing.expect(!app.supported(.null));+ var server: mcp.Server = .{ .execute = fake, .initialized = true, .ready = true, .apps = true };+ var out: std.Io.Writer.Allocating = .init(a);+ try server.handle(a, &out.writer, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}");+ const listed = try std.json.parseFromSliceLeaky(Value, a, out.written(), .{});+ const tool = listed.object.get("result").?.object.get("tools").?.array.items[0];+ try std.testing.expectEqualStrings(app.uri, tool.object.get("_meta").?.object.get("ui").?.object.get("resourceUri").?.string);+ const result = try check(a, init +++ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"resources/read\",\"params\":{\"uri\":\"ui://codegraff/task-result\"}}\n" +++ "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"resources/read\",\"params\":{\"uri\":\"file:///private\"}}\n");+ var lines = std.mem.tokenizeScalar(u8, result, '\n');+ _ = lines.next();+ const read = try std.json.parseFromSliceLeaky(Value, a, lines.next().?, .{});+ const resource = read.object.get("result").?.object.get("contents").?.array.items[0];+ try std.testing.expectEqualStrings(app.mime, resource.object.get("mimeType").?.string);+ try std.testing.expect(std.mem.startsWith(u8, resource.object.get("text").?.string, "<!doctype html>"));+ const rejected = try std.json.parseFromSliceLeaky(Value, a, lines.next().?, .{});+ try std.testing.expectEqual(@as(i64, -32002), rejected.object.get("error").?.object.get("code").?.integer);+}++test "MCP plain clients keep text fallback and structured errors" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const result = try check(a, init +++ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\"}\n" +++ "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"run_task\",\"arguments\":{\"prompt\":\"fail\",\"timeout_seconds\":5}}}\n");+ var lines = std.mem.tokenizeScalar(u8, result, '\n');+ _ = lines.next();+ const list = try std.json.parseFromSliceLeaky(Value, a, lines.next().?, .{});+ const tool = list.object.get("result").?.object.get("tools").?.array.items[0];+ try std.testing.expect(!tool.object.contains("_meta"));+ try std.testing.expect(tool.object.contains("outputSchema"));+ const templates = try check(a, init ++ "{\"jsonrpc\":\"2.0\",\"id\":8,\"method\":\"resources/templates/list\"}\n");+ try std.testing.expect(std.mem.indexOf(u8, templates, "\"resourceTemplates\":[]") != null);+ const response = try std.json.parseFromSliceLeaky(Value, a, lines.next().?, .{});+ const call = response.object.get("result").?;+ const data = call.object.get("structuredContent").?;+ try std.testing.expectEqualStrings("failed", data.object.get("status").?.string);+ try std.testing.expectEqual(@as(i64, 5), data.object.get("timeout_seconds").?.integer);+ try std.testing.expectEqualStrings(call.object.get("content").?.array.items[0].object.get("text").?.string, data.object.get("text").?.string);+}diff --git a/src/mcp_task_app.html b/src/mcp_task_app.htmlnew file mode 100644index 00000000..d1899a6b--- /dev/null+++ b/src/mcp_task_app.html@@ -0,0 +1,97 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">+<title>Codegraff · Task result</title>+<style>/* CODEGRAFF_THEME */</style>+<style>+:root{color-scheme:light dark}*{box-sizing:border-box}+body{margin:0;padding:12px;background:var(--canvas);color:var(--ink);font:13px/1.6 Inter,ui-sans-serif,system-ui,sans-serif;-webkit-font-smoothing:antialiased;letter-spacing:-.01em}+.workspace{background:var(--page);border:1px solid var(--line-strong);border-radius:14px;overflow:hidden}+header{height:44px;display:flex;align-items:center;gap:12px;padding:0 14px;border-bottom:1px solid var(--line);background:var(--page)}.brand{font-size:13px;font-weight:650;letter-spacing:-.3px}.brand span{color:#059669}.tab{font-size:12px;padding:3px 12px;border-radius:7px;background:var(--hover-2);color:var(--ink)}+#status{margin-left:auto;font-size:11px;color:var(--ink-2);display:flex;align-items:center;gap:6px}#status:before{content:'';width:6px;height:6px;border-radius:50%;background:var(--green)}#status[data-error=true]{color:var(--red)}#status[data-error=true]:before{background:var(--red)}+main{max-width:760px;margin:auto;padding:26px 24px 18px}.user-row{display:flex;justify-content:flex-end;padding-left:40px;margin-bottom:30px}.user-bubble{max-width:100%;border-radius:12px;padding:10px 14px;background:color-mix(in oklab,var(--accent) 12%,var(--surface));box-shadow:var(--shadow-hairline)}+#prompt{white-space:pre-wrap;overflow-wrap:anywhere}summary{cursor:pointer;color:var(--ink-2);font-size:11px;margin-top:8px}.limits{display:flex;flex-wrap:wrap;gap:8px;margin-top:6px;color:var(--ink-2);font-size:11px}.limits span{border-radius:6px;background:var(--surface);padding:2px 7px}+.assistant-label{display:flex;align-items:center;gap:8px;font-weight:600;font-size:12px;margin-bottom:10px}.mark{width:22px;height:22px;display:grid;place-items:center;border:1px solid var(--line-strong);border-radius:7px;color:#059669;background:var(--surface)}+.toolbar{display:flex;align-items:center;gap:14px;margin:14px 0 10px}input[type=search]{flex:1;min-width:0;max-width:320px;border:1px solid var(--line-strong);border-radius:8px;background:var(--surface);color:var(--ink);padding:7px 10px;font:inherit;font-size:12px}label{white-space:nowrap;color:var(--ink-2);font-size:11px}input:focus-visible,summary:focus-visible,button:focus-visible{outline:2px solid var(--accent);outline-offset:3px}+pre{margin:0;padding:0;background:transparent;color:var(--ink);font:13px/1.8 ui-monospace,'SF Mono',monospace;max-height:420px;min-height:100px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere}pre.nowrap{white-space:pre;overflow-wrap:normal}#count{font-size:11px;min-height:20px;margin:6px 0;color:var(--ink-3)}footer{margin-top:14px;padding-top:12px;border-top:1px solid var(--line);font-size:11px;color:var(--ink-2)}+@media(max-width:420px){body{padding:6px}main{padding:18px 14px}.toolbar{gap:8px}.tab{display:none}.user-row{padding-left:20px}}+</style>+</head>+<body>+<section class="workspace" aria-label="Codegraff task">+<header><div class="brand">codegraff<span> /</span></div><span class="tab">Task</span><span id="status" role="status">Connecting</span></header>+<main>+<div class="user-row"><div class="user-bubble"><div id="prompt">Waiting for task details.</div>+<details><summary>Task limits</summary><div class="limits"><span id="deadline">Time limit —</span><span id="budget">Model call limit —</span></div></details></div></div>+<div class="assistant-label"><span class="mark" aria-hidden="true">/</span>Codegraff <span id="clipped" hidden>· Output truncated</span></div>+<pre id="output" tabindex="0" aria-label="Task output">Waiting for the host to deliver a result.</pre>+<div class="toolbar"><input id="search" type="search" aria-label="Filter output lines" placeholder="Find in response…"><label><input id="wrap" type="checkbox" checked> Wrap lines</label></div>+<p id="count" aria-live="polite"></p>+<footer id="note">Results appear when the task finishes. Review any changes before integrating.</footer>+</main></section>+<script>+'use strict';+const el = id => document.getElementById(id);+let output = '', ready = false, closed = false;+const send = message => { if (!closed) window.parent.postMessage({jsonrpc:'2.0',...message}, '*'); };+const notify = (method, params={}) => send({method,params});+function state(label, error=false){el('status').textContent=label;el('status').dataset.error=String(error);}+function filter(){+ const query=el('search').value.toLocaleLowerCase();+ const lines=output.split('\n'), matches=query ? lines.filter(line=>line.toLocaleLowerCase().includes(query)) : lines;+ el('output').textContent=matches.join('\n') || (query ? 'No matching lines.' : 'No text output.');+ el('count').textContent=query ? `${matches.length} of ${lines.length} lines` : '';+}+function context(value){+ if(value?.theme==='dark'||value?.theme==='light'){document.documentElement.dataset.theme=value.theme;document.documentElement.classList.toggle('dark',value.theme==='dark');}+}+function limits(value){+ if(Number.isInteger(value?.timeout_seconds)) el('deadline').textContent=`Time limit ${value.timeout_seconds}s`;+ if(Number.isInteger(value?.max_model_calls)) el('budget').textContent=`Model call limit ${value.max_model_calls}`;+}+function receive(event){+ if(event.source!==window.parent || closed) return;+ const msg=event.data;+ if(!msg || msg.jsonrpc!=='2.0') return;+ if(msg.id==='codegraff-init'){+ if(msg.error){state('View unavailable',true);return;}+ if(!msg.result || ready) return;+ if(msg.result.protocolVersion!=='2026-01-26'){state('Unsupported app protocol',true);return;}+ ready=true;clearTimeout(connectTimer);context(msg.result.hostContext);+ state('Waiting for result');notify('ui/notifications/initialized');resize();return;+ }+ if(msg.method==='ui/resource-teardown'){+ send({id:msg.id,result:{}});closed=true;clearTimeout(connectTimer);observer.disconnect();window.removeEventListener('message',receive);return;+ }+ if(!ready) return;+ const value=msg.params||{};+ switch(msg.method){+ case 'ui/notifications/host-context-changed':context(value);break;+ case 'ui/notifications/tool-input':+ el('prompt').textContent=typeof value.arguments?.prompt==='string' ? value.arguments.prompt : 'Task brief unavailable.';+ limits({timeout_seconds:120,max_model_calls:8,...value.arguments});state('Waiting for result');break;+ case 'ui/notifications/tool-result':{+ const data=value.structuredContent||{};+ output=typeof data.text==='string' ? data.text : (Array.isArray(value.content) ? value.content.filter(item=>item.type==='text'&&typeof item.text==='string').map(item=>item.text).join('\n') : '');+ const labels={completed:'Completed',failed:'Failed',timed_out:'Timed out',cancelled:'Cancelled'};+ state(value.isError ? (labels[data.status]==='Completed' ? 'Failed' : labels[data.status]||'Failed') : labels[data.status]||'Completed',Boolean(value.isError)||['failed','timed_out','cancelled'].includes(data.status));+ limits(data);el('clipped').hidden=!data.output_truncated;+ el('note').textContent=value.isError ? 'Partial work may remain. Inspect the output and workspace before retrying.' : 'The task process finished. Review its answer and any changes before integrating.';+ filter();break;+ }+ case 'ui/notifications/tool-cancelled':state('Cancelled',true);el('note').textContent='The host cancelled this call. Partial work may remain.';break;+ case 'ping':send({id:msg.id,result:{}});break;+ default:if(msg.id!==undefined) send({id:msg.id,error:{code:-32601,message:'Method not supported'}});+ }+}+function resize(){if(ready) notify('ui/notifications/size-changed',{height:document.documentElement.scrollHeight});}+const observer=new ResizeObserver(resize);observer.observe(document.body);+el('search').addEventListener('input',filter);+el('wrap').addEventListener('change',()=>el('output').classList.toggle('nowrap',!el('wrap').checked));+window.addEventListener('message',receive);+const connectTimer=setTimeout(()=>{if(!ready)state('Open in an MCP Apps host');},10000);+send({id:'codegraff-init',method:'ui/initialize',params:{protocolVersion:'2026-01-26',appInfo:{name:'Codegraff task result',version:'1.0.0'},appCapabilities:{availableDisplayModes:['inline']}}});+</script>+</body>+</html>