Skip to content

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

Python

feat: add isolated MCP app result views and regression coverage

Rach Pradhan696a954be44a
diff --git a/apps/native/.gitignore b/apps/native/.gitignore
index d9424ee3..d1d3d453 100644
--- a/apps/native/.gitignore
+++ b/apps/native/.gitignore
@@ -6,3 +6,6 @@ next-env.d.ts
.env
.env.local
.DS_Store
+
+/test-results/
+/playwright-report/
diff --git a/apps/native/app/api/mcp-apps/route.ts b/apps/native/app/api/mcp-apps/route.ts
new file mode 100644
index 00000000..950785f2
--- /dev/null
+++ b/apps/native/app/api/mcp-apps/route.ts
@@ -0,0 +1,19 @@
+import {readMcpApp} from "@/lib/mcp-app-store";
+import {validAppId} from "@/lib/mcp-apps";
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const origin = request.headers.get("origin");
+ if (request.headers.get("sec-fetch-site") === "cross-site" || (origin && origin !== url.origin))
+ return new Response("Forbidden", {status:403});
+ const id = url.searchParams.get("id");
+ if (!validAppId(id)) return new Response("Invalid app id", {status:400});
+ try {
+ return new Response(await readMcpApp(id), {headers:{
+ "Content-Type":"text/html; charset=utf-8", "Cache-Control":"no-store", "X-Content-Type-Options":"nosniff",
+ "Referrer-Policy":"no-referrer", "Content-Security-Policy":"frame-ancestors 'self'; sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox",
+ }});
+ } catch { return new Response("This app result is no longer available.", {status:404}); }
+}
diff --git a/apps/native/app/visual-tests/mcp-apps/page.tsx b/apps/native/app/visual-tests/mcp-apps/page.tsx
new file mode 100644
index 00000000..e49d1265
--- /dev/null
+++ b/apps/native/app/visual-tests/mcp-apps/page.tsx
@@ -0,0 +1,8 @@
+import {notFound} from "next/navigation";
+import McpAppResult from "@/components/site/McpAppResult";
+export const dynamic = "force-dynamic";
+export default async function Page({searchParams}: {searchParams:Promise<{id?:string}>}) {
+ if (process.env.GRAFF_VISUAL_TESTS !== "1") notFound();
+ const {id} = await searchParams;
+ return <main style={{maxWidth:900,margin:"30px auto"}}><h1>Simulated MCP app</h1><McpAppResult id={id ?? ""} /></main>;
+}
diff --git a/apps/native/bun.lock b/apps/native/bun.lock
index 27574d99..55eee9c7 100644
--- a/apps/native/bun.lock
+++ b/apps/native/bun.lock
@@ -22,6 +22,7 @@
},
"devDependencies": {
"@electron/osx-sign": "2.7.0",
+ "@playwright/test": "^1.63.0",
"@tailwindcss/postcss": "^4.1.8",
"@types/node": "^22",
"@types/react": "^19",
@@ -139,6 +140,8 @@
"@next/swc-win32-x64-msvc": ["@next/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-vvBzwu1pYQCp92maZCFCIw/XgOTMR5tur9GjakwIo2cmwRTMKajRZZDS9+e4KsUZWKu1E007WUeAFXRRjZeuzw=="],
+ "@playwright/test": ["@playwright/[email protected]", "", { "dependencies": { "playwright": "1.63.0" }, "bin": { "playwright": "cli.js" } }, "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ=="],
+
"@shikijs/core": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.23.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-NSWQz0riNb67xthdm5br6lAkvpDJRTgB36fxlo37ZzM2yq0PQFFzbd8psqC2XMPgCzo1fW6cVi18+ArJ44wqgA=="],
"@shikijs/engine-javascript": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.23.0", "@shikijs/vscode-textmate": "^10.0.2", "oniguruma-to-es": "^4.3.4" } }, "sha512-aHt9eiGFobmWR5uqJUViySI1bHMqrAgamWE1TYSUoftkAeCCAiGawPMwM+VCadylQtF4V3VNOZ5LmfItH5f3yA=="],
@@ -643,6 +646,10 @@
"picocolors": ["[email protected]", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
+ "playwright": ["[email protected]", "", { "dependencies": { "playwright-core": "1.63.0" }, "bin": { "playwright": "cli.js" } }, "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg=="],
+
+ "playwright-core": ["[email protected]", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg=="],
+
"plist": ["[email protected]", "", { "dependencies": { "@xmldom/xmldom": "^0.9.10", "base64-js": "^1.5.1", "xmlbuilder": "^15.1.1" } }, "sha512-ZIfcLJC+7E7FBFnDxm9MPmt7D+DidyQ26lewieO75AdhA2ayMtsJSES0iWzqJQbcVRSrTufQoy0DR94xHue0oA=="],
"points-on-curve": ["[email protected]", "", {}, "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A=="],
diff --git a/apps/native/components/site/ChatBubbles.tsx b/apps/native/components/site/ChatBubbles.tsx
index 543a19f1..aa3f57ee 100644
--- a/apps/native/components/site/ChatBubbles.tsx
+++ b/apps/native/components/site/ChatBubbles.tsx
@@ -5,6 +5,7 @@ import Markdown from "@/components/primitives/Markdown";
import ThinkingState from "@/components/primitives/ThinkingState";
import ToolChips, { type LiveDiff } from "@/components/primitives/ToolChips";
import TurnActivity from "./TurnActivity";
+import McpAppResult from "./McpAppResult";
import { pinScrollerTail } from "@/lib/follow-scroll";
import { turnBlocks, type AssistantTurn } from "@/lib/acp";
import { createSmoothStream } from "@/lib/smooth-stream";
@@ -52,7 +53,8 @@ const ToolGroup = memo(function ToolGroup({ tools, diffs, onOpenPath }: {
detailMono: tool.icon === "run" || tool.icon === "write", detail: tool.detail,
path: tool.path, status: tool.status, startedAt: tool.startedAt, elapsedMs: tool.elapsedMs,
}));
- return <ToolChips rows={rows} diffs={diffs} onOpenPath={onOpenPath} />;
+ return <><ToolChips rows={rows} diffs={diffs} onOpenPath={onOpenPath} />
+ {tools.filter(tool=>tool.mcpAppId).map(tool=><McpAppResult key={tool.id} id={tool.mcpAppId!} />)}</>;
}, (previous, next) => previous.diffs === next.diffs && previous.onOpenPath === next.onOpenPath &&
previous.tools.length === next.tools.length && previous.tools.every((tool, index) => tool === next.tools[index]));
diff --git a/apps/native/components/site/McpAppResult.tsx b/apps/native/components/site/McpAppResult.tsx
new file mode 100644
index 00000000..3f135799
--- /dev/null
+++ b/apps/native/components/site/McpAppResult.tsx
@@ -0,0 +1,16 @@
+"use client";
+import {useState} from "react";
+import {validAppId} from "@/lib/mcp-apps";
+
+export default function McpAppResult({id}: {id: string}) {
+ const [visible, setVisible] = useState(true);
+ if (!validAppId(id)) return null;
+ return <section className="my-3 overflow-hidden rounded-lg border border-ink/10" aria-label="MCP app result">
+ <div className="flex items-center justify-between px-3 py-2 text-xs text-ink-3">
+ <span>Interactive MCP result</span><button type="button" onClick={()=>setVisible(!visible)} aria-expanded={visible}>{visible ? "Close view" : "Open view"}</button>
+ </div>
+ {visible && <iframe title="Interactive MCP tool result" src={`/api/mcp-apps?id=${id}`}
+ sandbox="allow-scripts allow-popups allow-popups-to-escape-sandbox" allow="clipboard-write"
+ referrerPolicy="no-referrer" className="block h-[620px] w-full border-0" />}
+ </section>;
+}
diff --git a/apps/native/e2e/mcp-apps.pw.ts b/apps/native/e2e/mcp-apps.pw.ts
new file mode 100644
index 00000000..b7584560
--- /dev/null
+++ b/apps/native/e2e/mcp-apps.pw.ts
@@ -0,0 +1,50 @@
+import {test,expect} from "@playwright/test";
+import {mkdir,readFile,writeFile,unlink} from "node:fs/promises";
+import {randomBytes} from "node:crypto";
+import {homedir} from "node:os";
+import path from "node:path";
+
+const ids:string[]=[];
+const root=path.join(homedir(),".graff","mcp-apps");
+const view=`<!doctype html><h1>Simulated references</h1><div id="answer"></div><button id="open">Open source</button><button id="bad">Invalid link</button><button id="tool">Run tool</button><button id="escape">Try escape</button><script>
+parent.postMessage({jsonrpc:'2.0',id:1,method:'ui/initialize',params:{protocolVersion:'2026-01-26',appInfo:{name:'Fixture',version:'1'},appCapabilities:{}}},'*');
+onmessage=e=>{const m=e.data;if(m.id===1&&m.result)parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/initialized',params:{}},'*');if(m.method==='ui/notifications/tool-result')document.querySelector('#answer').textContent=m.params.structuredContent.title;if(m.id===3)document.querySelector('#answer').textContent=m.error?'Tool blocked':'Unexpected execution';if(m.id===4)document.querySelector('#answer').textContent=m.result.isError?'Link blocked':'Unexpected navigation';};
+document.querySelector('#open').onclick=()=>parent.postMessage({jsonrpc:'2.0',id:2,method:'ui/open-link',params:{url:'https://example.com/design'}},'*');
+document.querySelector('#bad').onclick=()=>parent.postMessage({jsonrpc:'2.0',id:4,method:'ui/open-link',params:{url:'file:///etc/passwd'}},'*');
+document.querySelector('#tool').onclick=()=>parent.postMessage({jsonrpc:'2.0',id:3,method:'tools/call',params:{name:'write_file'}},'*');
+document.querySelector('#escape').onclick=()=>{try{top.document.body.innerHTML='escaped'}catch{document.querySelector('#answer').textContent='Isolated'}};
+</script>`;
+async function snapshot(resource:object,result:object={structuredContent:{title:"Delivered result"}}){
+ const id=randomBytes(16).toString('hex');await mkdir(root,{recursive:true});
+ const template=await readFile(new URL('../../../src/mcp_app_host.html',import.meta.url),'utf8');
+ const payload=Buffer.from(JSON.stringify({resource,arguments:{query:'fixture'},result})).toString('base64');
+ await writeFile(path.join(root,`${id}.html`),template.replace('GRAFF_APP_PAYLOAD',payload),{mode:0o600});ids.push(id);return id;
+}
+test.afterAll(async()=>{await Promise.all(ids.map(id=>unlink(path.join(root,`${id}.html`))));});
+test('GUI delivers results through isolated proxy, source navigation and explicit unsupported actions',async({page})=>{
+ const id=await snapshot({text:view});await page.goto(`/visual-tests/mcp-apps?id=${id}`);
+ const host=page.frameLocator('iframe').first();const app=host.frameLocator('iframe').frameLocator('iframe');
+ await expect(app.locator('#answer')).toHaveText('Delivered result');
+ await app.locator('#open').click();await expect(host.locator('#link')).toHaveAttribute('href','https://example.com/design');
+ await app.locator('#bad').click();await expect(app.locator('#answer')).toHaveText('Link blocked');
+ await app.locator('#tool').click();await expect(app.locator('#answer')).toHaveText('Tool blocked');
+ await app.locator('#escape').click();await expect(app.locator('#answer')).toHaveText('Isolated');
+ await page.screenshot({path:'/tmp/codegraff-mcp-apps-gui.png'});
+ await page.getByRole('button',{name:'Close view'}).click();await expect(page.locator('iframe')).toHaveCount(0);
+ await page.getByRole('button',{name:'Open view',exact:true}).click();await expect(app.locator('#answer')).toHaveText('Delivered result');
+});
+test('undeclared network requests are blocked by CSP and frames cannot impersonate host',async({page})=>{
+ let leaks=0;await page.route('https://blocked.example/**',route=>{leaks++;return route.abort();});
+ const hostile=view.replace('<h1>',`<img src="https://blocked.example/leak"><script>fetch('https://blocked.example/leak').catch(()=>{});parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-ready',params:{}},'*');</script><h1>`);
+ const id=await snapshot({text:hostile,_meta:{ui:{csp:{connectDomains:["https://safe.example; connect-src *","*"]}}}});
+ await page.goto(`/visual-tests/mcp-apps?id=${id}`);const app=page.frameLocator('iframe').frameLocator('iframe').frameLocator('iframe');
+ await expect(app.locator('#answer')).toHaveText('Delivered result');
+ expect(leaks).toBe(0);
+});
+test('REPL saved HTML works standalone and resource route rejects malformed ids',async({page,request})=>{
+ const id=await snapshot({text:view});await page.goto(`file://${path.join(root,`${id}.html`)}`);
+ const app=page.frameLocator('iframe').frameLocator('iframe');await expect(app.locator('#answer')).toHaveText('Delivered result');
+ expect((await request.get('/api/mcp-apps?id=../secret')).status()).toBe(400);
+ expect((await request.get(`/api/mcp-apps?id=${'f'.repeat(32)}`)).status()).toBe(404);
+ expect((await request.get(`/api/mcp-apps?id=${id}`,{headers:{Origin:'https://evil.example'}})).status()).toBe(403);
+});
diff --git a/apps/native/lib/acp.ts b/apps/native/lib/acp.ts
index 62c12263..64c90010 100644
--- a/apps/native/lib/acp.ts
+++ b/apps/native/lib/acp.ts
@@ -1,5 +1,6 @@
import { boundToolDetail } from "./tool-detail";
import { stripCiteMarkup } from "./cite-markup";
+import { mcpAppId } from "./mcp-apps";
/** ACP v1 session/update shapes the native harness renders. */
export type AcpContent = { type: "text"; text: string };
@@ -195,6 +196,7 @@ function upsertTool(turn: AssistantTurn, update: Extract<AcpUpdate, { toolCallId
chip: chipRaw === label || humanize(chipRaw) === label ? "" : chipRaw,
status,
detail: boundToolDetail(detail),
+ mcpAppId: mcpAppId(contentText) ?? prev?.mcpAppId,
path,
startedAt: prev?.startedAt ?? Date.now(),
atChars: prev?.atChars ?? turn.text.length,
diff --git a/apps/native/lib/graff-events.ts b/apps/native/lib/graff-events.ts
index 84bad6b5..d7d2767f 100644
--- a/apps/native/lib/graff-events.ts
+++ b/apps/native/lib/graff-events.ts
@@ -43,6 +43,7 @@ export type GraffEvent =
export type ToolIcon = "think" | "write" | "run" | "read";
export type ToolRow = {
+ mcpAppId?: string;
id: string;
name: string;
icon: ToolIcon;
diff --git a/apps/native/lib/mcp-app-store.ts b/apps/native/lib/mcp-app-store.ts
new file mode 100644
index 00000000..3b288f05
--- /dev/null
+++ b/apps/native/lib/mcp-app-store.ts
@@ -0,0 +1,16 @@
+import {open, lstat} from "node:fs/promises";
+import {constants} from "node:fs";
+import {homedir} from "node:os";
+import path from "node:path";
+import {validAppId} from "./mcp-apps";
+
+export async function readMcpApp(id: string, root = path.join(homedir(), ".graff", "mcp-apps")): Promise<string> {
+ if (!validAppId(id)) throw Error("Invalid app id");
+ if ((await lstat(root)).isSymbolicLink()) throw Error("Invalid app directory");
+ const file = await open(path.join(root, `${id}.html`), constants.O_RDONLY | constants.O_NOFOLLOW);
+ try {
+ const stat = await file.stat();
+ if (!stat.isFile() || stat.size > 18 * 1024 * 1024) throw Error("Invalid app snapshot");
+ return await file.readFile("utf8");
+ } finally { await file.close(); }
+}
diff --git a/apps/native/lib/mcp-apps.test.ts b/apps/native/lib/mcp-apps.test.ts
new file mode 100644
index 00000000..ac4b70db
--- /dev/null
+++ b/apps/native/lib/mcp-apps.test.ts
@@ -0,0 +1,26 @@
+import {test,expect} from "bun:test";
+import {mkdtemp,writeFile,symlink,rm} from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import {mcpAppId,validAppId} from "./mcp-apps";
+import {readMcpApp} from "./mcp-app-store";
+import {applyAcpUpdate,emptyTurn} from "./acp";
+const id="a".repeat(32);
+test("only opaque local app ids are recognized",()=>{
+ expect(mcpAppId(`[MCP app](/home/test/.graff/mcp-apps/${id}.html)`)).toBe(id);
+ expect(mcpAppId(`[MCP app](https://evil/${id}.html)`)).toBeUndefined();
+ for(const bad of ['../secret','a'.repeat(31),'A'.repeat(32),'a'.repeat(33)])expect(validAppId(bad)).toBe(false);
+});
+test("ACP retains app id before details are truncated",()=>{
+ const turn=applyAcpUpdate(emptyTurn(),{sessionUpdate:'tool_call_update',toolCallId:'t1',title:'mcp__test__search',status:'completed',content:[{type:'content',content:{type:'text',text:`[MCP app](/home/test/.graff/mcp-apps/${id}.html)\n`+'data'.repeat(50000)}}]});
+ expect(turn.tools[0].mcpAppId).toBe(id);
+});
+test("app store rejects traversal, oversized files and symlinks",async()=>{
+ const root=await mkdtemp(path.join(os.tmpdir(),'graff-app-test-'));
+ try{
+ await writeFile(path.join(root,`${id}.html`),'saved');expect(await readMcpApp(id,root)).toBe('saved');
+ await expect(readMcpApp('../secret',root)).rejects.toThrow();
+ const other='b'.repeat(32);await symlink(path.join(root,`${id}.html`),path.join(root,`${other}.html`));await expect(readMcpApp(other,root)).rejects.toThrow();
+ await writeFile(path.join(root,`${id}.html`),Buffer.alloc(19*1024*1024));await expect(readMcpApp(id,root)).rejects.toThrow();
+ }finally{await rm(root,{recursive:true,force:true});}
+});
diff --git a/apps/native/lib/mcp-apps.ts b/apps/native/lib/mcp-apps.ts
new file mode 100644
index 00000000..1a7c6a6d
--- /dev/null
+++ b/apps/native/lib/mcp-apps.ts
@@ -0,0 +1,8 @@
+/** Extract only our opaque snapshot id; never accept an arbitrary file URL. */
+export function mcpAppId(text: string): string | undefined {
+ return /\[MCP app\]\([^\r\n]*\/\.graff\/mcp-apps\/([a-f0-9]{32})\.html\)/.exec(text)?.[1];
+}
+
+export function validAppId(value: unknown): value is string {
+ return typeof value === "string" && /^[a-f0-9]{32}$/.test(value);
+}
diff --git a/apps/native/package.json b/apps/native/package.json
index 7a07aab1..a3fe3574 100644
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@ -28,7 +28,8 @@
"test:sessions": "GRAFF_VISUAL_SUITE=sessions bun scripts/test-visual.mjs",
"test:background": "bun scripts/test-background.mjs",
"test:performance": "GRAFF_PERFORMANCE_TESTS=1 bun scripts/test-visual.mjs",
- "benchmark:desktop": "bun scripts/benchmark-desktop.mjs"
+ "benchmark:desktop": "bun scripts/benchmark-desktop.mjs",
+ "test:mcp-apps": "bun test lib/mcp-apps.test.ts && playwright test -c playwright.mcp.config.ts"
},
"dependencies": {
"@streamdown/code": "^1.1.1",
@@ -48,6 +49,7 @@
},
"devDependencies": {
"@electron/osx-sign": "2.7.0",
+ "@playwright/test": "^1.63.0",
"@tailwindcss/postcss": "^4.1.8",
"@types/node": "^22",
"@types/react": "^19",
diff --git a/apps/native/playwright.mcp.config.ts b/apps/native/playwright.mcp.config.ts
new file mode 100644
index 00000000..c119dc17
--- /dev/null
+++ b/apps/native/playwright.mcp.config.ts
@@ -0,0 +1,2 @@
+import {defineConfig} from "@playwright/test";
+export default defineConfig({testDir:"./e2e",testMatch:"mcp-apps.pw.ts",workers:1,use:{channel:"chrome",baseURL:"http://localhost:3017",headless:true},webServer:{command:"GRAFF_VISUAL_TESTS=1 bunx next dev --port 3017",url:"http://localhost:3017",timeout:120000,reuseExistingServer:false},reporter:"list"});
diff --git a/docs/adr/0095-mcp-apps-are-isolated-result-views.md b/docs/adr/0095-mcp-apps-are-isolated-result-views.md
new file mode 100644
index 00000000..bd0c122f
--- /dev/null
+++ b/docs/adr/0095-mcp-apps-are-isolated-result-views.md
@@ -0,0 +1,23 @@
+# MCP Apps are isolated result views
+
+## Context
+
+Flattening tool output to text discards the UI resource and structured result that an MCP App needs. A desktop browser can display these results; a terminal needs a browser handoff. Rendering server-provided HTML inside the desktop's origin would grant it unrelated local application privileges.
+
+## Decision
+
+Keep an MCP App's declared UI resource URI during discovery, including the legacy metadata spelling. Exclude app-only tools from the model catalog. Advertise the UI extension on legacy and modern MCP connections.
+
+After an app-enabled tool returns, read its declared resource with a bounded request. Accept only matching `ui://` resources with the MCP Apps MIME type, either text or base64 HTML. Save the resource, arguments, and complete tool result as a private, size-bounded local snapshot. Only a snapshot link and ordinary result text enter model context; resource HTML and result `_meta` do not.
+
+The GUI recognizes the opaque snapshot id before bounding tool details and renders it in a sandbox. A different-origin proxy isolates the inner app, relays only messages from the expected windows, enforces declared CSP domains with restrictive defaults, and performs the MCP Apps handshake. `/mcp apps` opens the latest snapshot from the current REPL session. Nothing opens automatically in the terminal.
+
+This is a result-view host. It supports input/result delivery, resizing, and user-visible source navigation. It does not execute app-initiated tools, read further resources, send agent messages, or update model context. Unsupported requests receive explicit errors. External links are presented for a user click; unsafe schemes are rejected. Clipboard controls remain host/browser-dependent; opaque sandbox origins can require an app's copy-link/manual fallback.
+
+## Consequences
+
+Existing text and image output continues when an app resource is absent, invalid, oversized, or unavailable. Snapshots persist for transcript replay and contain tool data; users can remove them to reclaim disk space. There is no live connection or live tool authority in a saved view. Supporting app-initiated actions later requires routing to the originating MCP session through the existing approval path, not a generic renderer-to-tool proxy.
+
+Regression coverage includes metadata/visibility validation, native snapshot creation and private-metadata separation, ACP id retention, constrained file reads, actual GUI rendering, standalone browser rendering, source links, blocked tool requests, CSP, and iframe escape attempts. Fixtures are local and deterministic; no model API is needed.
+
+Reference: [MCP Apps stable specification](https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx).
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 5eaeeeeb..85852753 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -105,6 +105,7 @@ record only when you need the evidence or the edge cases.
| [0092](0092-codedb-context-is-local-first.md) | Bare `codedb context` is `--local`; `--hybrid` / `--semantic` are opt-in remote rerank (and still refused under ADR 0084 policy). |
| [0093](0093-project-layout-breadth-and-directory-hints.md) | Project layout favors breadth under its caps; missing directories offer bounded sibling hints without changing confinement or ADR 0090 constraint policy. |
| [0094](0094-subagent-interrupt-is-a-cancel-file.md) | GUI Stop writes `{id}.cancel` in the activity dir; the child finishes failed even if the model returns. Not `session/cancel`. |
+| [0095](0095-mcp-apps-are-isolated-result-views.md) | MCP Apps are private saved result views in isolated GUI/browser sandboxes; app tool calls require a future approval path. |
| [0096](0096-desktop-link-destination.md) | Persist the desktop link destination outside origin-scoped storage; validate once and reveal the focused chat's Browser without navigating the app. |
| [0097](0097-isolate-probe-clipboards.md) | Offline PTY probes get private clipboard commands per process; direct probe runs retain OS clipboard integration. |
| [0098](0098-orphan-listeners-are-not-stop-authority.md) | Legacy listener discovery is read-only; stop authority requires verified ownership, port preflight checks both families, and unknown browser visibility protects listening jobs. |
diff --git a/docs/mcp-apps.md b/docs/mcp-apps.md
new file mode 100644
index 00000000..ec1640ef
--- /dev/null
+++ b/docs/mcp-apps.md
@@ -0,0 +1,35 @@
+# MCP Apps in Codegraff
+
+Call a connected MCP tool that declares an MCP Apps UI. In the native GUI, its tool result includes an **Interactive MCP result** view. Close/reopen controls dispose and restore the view. Text and image output stays available in the transcript.
+
+In the REPL, run **`/mcp apps`** after the tool completes to open its latest saved view in the default browser. The link in the tool result also identifies the standalone HTML file. This works with the existing MCP server configuration and consent process; it does not install or authorize additional servers.
+
+Views can display results, scroll, resize, and offer source links. Clicking a source exposes an **Open source** link in trusted host chrome for a user click. Image-copy features depend on browser permissions; the isolated view may need the app's copy-link or manual-selection fallback. This version does not run app-initiated tool calls or inject messages into the agent conversation; those requests fail explicitly.
+
+Snapshots are stored in the user's `.graff/mcp-apps` directory with private file permissions and opaque ids. They include the tool result and its view metadata, remain available across transcript reloads, and can be deleted when no longer needed. The REPL shortcut tracks the latest view in its current session; old snapshots remain openable by their saved links.
+
+## Development and regression checks
+
+Build the engine and run its offline integration fixtures:
+
+```sh
+zig build
+zig build test --summary all
+python3 scripts/test-mcp-apps.py
+```
+
+The Python fixtures start local MCP and scripted-model servers. They verify text and base64 resources, saved results, exclusion of private UI metadata from model requests, private snapshot permissions, and invalid-resource fallback. The scripted model uses its established local test port; no provider API is called.
+
+Run simulated apps in Chrome against the actual native GUI component and API route:
+
+```sh
+cd apps/native
+bun install
+bun run test:mcp-apps
+```
+
+The browser tests start an isolated Next development server and clean up only their own snapshots. They exercise handshake/result delivery, close/reopen, source and unsafe links, blocked app tool calls, cross-frame access, CSP network blocking, and standalone REPL snapshots. Store tests cover path traversal, symlinks, and oversized files. The visual fixture route is available only when `GRAFF_VISUAL_TESTS=1`.
+
+For GUI development, run the native app with the rebuilt engine. Packaged desktop copies embed their own engine and frontend and need a new package before these changes appear there.
+
+See [the architecture decision](adr/0095-mcp-apps-are-isolated-result-views.md) for the isolation and capability boundary.
diff --git a/scripts/test-mcp-apps.py b/scripts/test-mcp-apps.py
new file mode 100644
index 00000000..30f12834
--- /dev/null
+++ b/scripts/test-mcp-apps.py
@@ -0,0 +1,85 @@
+#!/usr/bin/env python3
+"""Offline engine integration: MCP metadata -> bounded snapshot -> model-safe text."""
+import base64
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import sys
+import tempfile
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+sys.path.insert(0, str(Path(__file__).parent / "eval"))
+from mock_model import ScriptedModel
+
+VIEW = """<!doctype html><h1>Fixture app</h1><div id="result"></div><button id="open">Open source</button><button id="tool">Try tool</button><script>
+parent.postMessage({jsonrpc:'2.0',id:1,method:'ui/initialize',params:{protocolVersion:'2026-01-26',appInfo:{name:'Fixture',version:'1'},appCapabilities:{}}},'*');
+onmessage=e=>{const m=e.data;if(m.id===1&&m.result)parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/initialized',params:{}},'*');if(m.method==='ui/notifications/tool-result')document.querySelector('#result').textContent=m.params.structuredContent.title;if(m.id===3)document.querySelector('#result').textContent=m.error?'Tool blocked':'Unexpected execution';};
+document.querySelector('#open').onclick=()=>parent.postMessage({jsonrpc:'2.0',id:2,method:'ui/open-link',params:{url:'https://example.com/design'}},'*');
+document.querySelector('#tool').onclick=()=>parent.postMessage({jsonrpc:'2.0',id:3,method:'tools/call',params:{name:'write_file'}},'*');
+</script>"""
+
+class Fixture(BaseHTTPRequestHandler):
+ def log_message(self, *_): pass
+ methods = []
+ mode = "text"
+ def do_POST(self):
+ msg = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
+ method = msg['method']; self.methods.append(method)
+ if method == 'tools/list':
+ result = {'tools':[{'name':'show','description':'Show a fixture app','inputSchema':{'type':'object','properties':{}},'_meta':{'ui':{'resourceUri':'ui://fixture/view'}}}]}
+ elif method == 'initialize':
+ result = {'protocolVersion':'2025-03-26','capabilities':{'tools':{},'resources':{}},'serverInfo':{'name':'fixture','version':'1'}}
+ elif method == 'tools/call':
+ result = {'content':[{'type':'text','text':'Public fixture answer'}],'structuredContent':{'title':'Rendered fixture result'},'_meta':{'privateViewField':'not-for-model'}}
+ elif method == 'resources/read':
+ resource = {'uri':'ui://fixture/view','mimeType':'text/html;profile=mcp-app'}
+ if self.mode == 'blob': resource['blob'] = base64.b64encode(VIEW.encode()).decode()
+ else: resource['text'] = VIEW
+ if self.mode == 'invalid-mime': resource['mimeType'] = 'text/html'
+ result = {'contents':[resource]}
+ else: result = {}
+ body = json.dumps({'jsonrpc':'2.0','id':msg.get('id'),'result':result}).encode()
+ self.send_response(200);self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body)
+
+def run_case(graff, mode):
+ Fixture.mode=mode; Fixture.methods=[]
+ server=ThreadingHTTPServer(('127.0.0.1',0),Fixture);threading.Thread(target=server.serve_forever,daemon=True).start()
+ model=ScriptedModel([{'tool':'load_tool_schemas','arguments':{'server':'fixture'}},{'tool':'mcp__fixture__show','arguments':{}},{'text':'Fixture complete.'}]);model.start(1234)
+ artifact=None
+ try:
+ with tempfile.TemporaryDirectory(prefix='graff-app-fixture-') as temp:
+ root=Path(temp);(root/'.mcp.json').write_text(json.dumps({'mcpServers':{'fixture':{'url':f'http://127.0.0.1:{server.server_port}/mcp'}}}))
+ (root/'empty.json').write_text((root/'.mcp.json').read_text())
+ (root/'.harness').mkdir();(root/'.harness/settings.json').write_text('{"skills":{"codedbpro":false,"muonry":false}}')
+ env={k:v for k,v in os.environ.items() if not k.endswith('_API_KEY')}
+ env.update(LMSTUDIO_API_KEY='local',GRAFF_MCP_CONFIG=str(root/'empty.json'),GRAFF_NO_TELEMETRY='1',GRAFF_FLEET='off',GRAFF_NO_SMOLIFY='1',GRAFF_NO_CODEDB_GUARD='1',GRAFF_BEHAVIOR_TRACE='0')
+ run=subprocess.run([str(graff),'--json','--yolo','--old','--model','lmstudio'],input=json.dumps({'type':'user','text':'Call mcp__fixture__show, then finish.'})+'\n',cwd=root,env=env,text=True,capture_output=True,timeout=60)
+ assert run.returncode==0, run.stderr[-2000:]
+ match=re.search(r'\[MCP app\]\(([^\r\n]*?/\.graff/mcp-apps/[a-f0-9]{32}\.html)\)',run.stdout)
+ if mode == 'invalid-mime':
+ assert match is None
+ assert 'MCP app view unavailable' in run.stdout
+ assert 'Public fixture answer' in run.stdout
+ print('PASS engine: invalid resource MIME falls back to ordinary result')
+ return
+ assert match, 'App marker absent: '+run.stdout[-3000:]
+ artifact=Path(match.group(1));html=artifact.read_text();payload=re.search(r"atob\('([A-Za-z0-9+/=]+)'\)",html).group(1)
+ saved=json.loads(base64.b64decode(payload));assert saved['resource']['text']==VIEW
+ assert saved['result']['structuredContent']['title']=='Rendered fixture result'
+ assert saved['result']['_meta']['privateViewField']=='not-for-model'
+ assert artifact.stat().st_mode & 0o777 == 0o600
+ assert 'resources/read' in Fixture.methods
+ assert 'not-for-model' not in json.dumps(model.requests)
+ assert '<h1>Fixture app</h1>' not in json.dumps(model.requests)
+ Path('/tmp/graff-mcp-app-fixture.html').write_text(html)
+ print(f'PASS engine ({mode}): UI resource fetched, result preserved, private metadata excluded from model, snapshot mode 0600')
+ finally:
+ if artifact: artifact.unlink(missing_ok=True)
+ server.shutdown();server.server_close();model.stop()
+
+if __name__=='__main__':
+ graff=Path(sys.argv[1] if len(sys.argv)>1 else 'zig-out/bin/graff').resolve()
+ for mode in ('text','blob','invalid-mime'): run_case(graff,mode)
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index 4ddf182e..dd2b065c 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -225,6 +225,14 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
if (std.mem.startsWith(u8, line, "/mcp")) {
const arg = std.mem.trim(u8, line["/mcp".len..], " \t");
const reg = root.registry.?; // always present now
+ if (std.mem.eql(u8, arg, "apps")) {
+ if (reg.last_app_path) |path| {
+ @import("oauth_helpers.zig").openBrowser(root.io, path);
+ try out.print("MCP app: {s}\n", .{path});
+ } else try out.writeAll("No MCP app result yet. Call a tool that declares an MCP Apps view first.\n");
+ try out.flush();
+ return true;
+ }
if (@import("mcp_boot.zig").joinPending(reg)) {
root.invalidateRootTools();
try root.ensureRootTools(root.provider.kind);
diff --git a/src/main.zig b/src/main.zig
index 3afdc814..3fe54731 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -346,7 +346,6 @@ pub fn main(init: std.process.Init) !void {
traj.deinit();
}
traj.node(.{ .kind = "session", .version = harness_version, .unix_ms = unixMs(io) });
-
var telem = session_start.initTelemetry(io, gpa, client, init.environ_map, flags, default_telemetry_endpoint);
telemetry.g_telem = &telem;
if (init.environ_map.get("GRAFF_FLEET")) |fv| {
@@ -564,6 +563,7 @@ const agentJobsReap = subagent.agentJobsReap; // #276 P0-3: background subagents
const workflow = @import("workflow_test.zig"); // the engine's tests live here (workflow.zig hit the 600-line cap)
const exec = @import("exec.zig");
test { // ── Unit tests (`zig build test`): pull in tests from imported modules (mcp.zig)
+ _ = @import("mcp_apps.zig");
_ = @import("main_test.zig");
_ = @import("http_client.zig");
_ = @import("http_client_tests.zig");
diff --git a/src/mcp.zig b/src/mcp.zig
index ee6e8093..199fb359 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -40,6 +40,7 @@ const initializeServer = mcp_rpc.initializeServer;
const request = mcp_rpc.request;
pub const Tool = struct {
+ ui_resource_uri: ?[]const u8 = null,
server_index: usize,
original_name: []const u8, // name as the server knows it
qualified_name: []const u8, // "mcp__<server>__<tool>" shown to the model
@@ -48,6 +49,7 @@ pub const Tool = struct {
};
pub const Registry = struct {
+ last_app_path: ?[]const u8 = null,
gpa: Allocator,
io: Io,
home: []const u8,
@@ -408,6 +410,7 @@ pub const Registry = struct {
};
for (tools_v.array.items) |t| {
if (t != .object) continue;
+ if (!@import("mcp_apps.zig").modelVisible(t)) continue;
const name_v = t.object.get("name") orelse continue;
if (name_v != .string) continue;
const orig = try a.dupe(u8, name_v.string);
@@ -427,6 +430,7 @@ pub const Registry = struct {
.qualified_name = qualified,
.description = try a.dupe(u8, desc),
.input_schema = schema,
+ .ui_resource_uri = if (@import("mcp_apps.zig").resourceUri(t)) |uri| try a.dupe(u8, uri) else null,
});
}
try servers.append(a, server);
@@ -547,6 +551,14 @@ pub const Registry = struct {
var ow: Io.Writer.Allocating = .init(out_alloc);
errdefer ow.deinit();
+ if (tool.ui_resource_uri) |uri| {
+ const path = @import("mcp_apps.zig").snapshot(reg.io, response_alloc, reg.home, server, uri, input, result_val) catch null;
+ if (path) |p| {
+ reg.last_app_path = try reg.arena().dupe(u8, p);
+ try ow.writer.print("[MCP app]({s}) — saved interactive result; /mcp apps opens it in a browser.\n", .{p});
+ } else try ow.writer.writeAll("[MCP app view unavailable; ordinary tool output follows.]\n");
+ }
+ const prefix_len = ow.writer.buffered().len;
if (result.get("content")) |content| try renderContent(&ow.writer, content, .{
.arena = reg.arena(),
.slot = &reg.pending_image,
@@ -555,7 +567,7 @@ pub const Registry = struct {
});
// 2025-06-18+ structured tool output: if the server sent only
// structuredContent (no text blocks), surface it instead of "".
- if (ow.writer.buffered().len == 0) {
+ if (ow.writer.buffered().len == prefix_len) {
if (result.get("structuredContent")) |sc| {
var sw: std.json.Stringify = .{ .writer = &ow.writer };
try sw.write(sc);
diff --git a/src/mcp_app_host.html b/src/mcp_app_host.html
new file mode 100644
index 00000000..69e68c1f
--- /dev/null
+++ b/src/mcp_app_host.html
@@ -0,0 +1,53 @@
+<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>MCP app result</title>
+<style>body{margin:0;font:14px system-ui;background:#fafafa;color:#222}header{padding:10px 14px;display:flex;justify-content:space-between;gap:12px;border-bottom:1px solid #ddd}iframe{width:100%;height:560px;border:0;display:block}#link{color:#075;overflow-wrap:anywhere}#status{font-size:12px;color:#666}</style>
+<header><span>MCP app · saved result</span><span id="status">Loading…</span></header><a id="link" target="_blank" rel="noopener noreferrer" hidden></a>
+<script>
+'use strict';
+const snapshot = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob('GRAFF_APP_PAYLOAD'),c=>c.charCodeAt(0))));
+const status = document.querySelector('#status'), link = document.querySelector('#link');
+function domains(values){return Array.isArray(values)?values.filter(v=>typeof v==='string'&&/^https:\/\/(?:\*\.)?[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::[0-9]{1,5})?$/i.test(v)).slice(0,32):[];}
+const declared=snapshot.resource._meta?.ui||{}, csp=declared.csp||{};
+const approved={connectDomains:domains(csp.connectDomains),resourceDomains:domains(csp.resourceDomains),frameDomains:domains(csp.frameDomains),baseUriDomains:domains(csp.baseUriDomains)};
+const clipboard=Boolean(declared.permissions?.clipboardWrite);
+// The proxy has its own opaque data: origin, distinct from both the GUI and host.
+const proxy=document.createElement('iframe');proxy.title='MCP app';proxy.sandbox='allow-scripts allow-same-origin';if(clipboard)proxy.allow='clipboard-write';
+const proxyCode=()=>{
+ let view=null;
+ window.addEventListener('message',event=>{
+ const m=event.data;if(!m||m.jsonrpc!=='2.0')return;
+ if(event.source===parent){
+ if(m.method==='ui/notifications/sandbox-resource-ready'&&!view){
+ const p=m.params,c=p.csp;
+ const policy=`default-src 'none'; script-src 'unsafe-inline' ${c.resourceDomains.join(' ')}; style-src 'unsafe-inline' ${c.resourceDomains.join(' ')}; img-src data: blob: ${c.resourceDomains.join(' ')}; font-src data: ${c.resourceDomains.join(' ')}; media-src data: blob: ${c.resourceDomains.join(' ')}; connect-src ${c.connectDomains.join(' ')||"'none'"}; frame-src ${c.frameDomains.join(' ')||"'none'"}; base-uri ${c.baseUriDomains.join(' ')||"'none'"}; object-src 'none'; form-action 'none'`;
+ view=document.createElement('iframe');view.title='Interactive tool result';view.sandbox='allow-scripts';view.style='width:100%;height:100vh;border:0;display:block';if(p.permissions?.clipboardWrite)view.allow='clipboard-write';
+ view.srcdoc='<!doctype html><meta http-equiv="Content-Security-Policy" content="'+policy+'">'+p.html;document.body.style.margin='0';document.body.append(view);
+ }else if(!String(m.method||'').startsWith('ui/notifications/sandbox-'))view?.contentWindow.postMessage(m,'*');
+ }else if(view&&event.source===view.contentWindow&&!String(m.method||'').startsWith('ui/notifications/sandbox-'))parent.postMessage(m,'*');
+ });
+ parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-ready',params:{}},'*');
+};
+const proxyHtml='<!doctype html><script>('+proxyCode.toString()+')()<'+ '/script>';
+proxy.src='data:text/html;base64,'+btoa(proxyHtml);
+function send(value){proxy.contentWindow.postMessage({jsonrpc:'2.0',...value},'*');}
+let initialized=false;
+window.addEventListener('message',event=>{
+ if(event.source!==proxy.contentWindow)return;const m=event.data;if(!m||m.jsonrpc!=='2.0')return;
+ const reply=result=>send({id:m.id,result});
+ if(m.method==='ui/notifications/sandbox-proxy-ready'){send({method:'ui/notifications/sandbox-resource-ready',params:{html:snapshot.resource.text,csp:approved,permissions:clipboard?{clipboardWrite:{}}:{}}});return;}
+ if(m.method==='ui/initialize'){
+ if(m.params?.protocolVersion!=='2026-01-26'){send({id:m.id,error:{code:-32602,message:'Unsupported MCP Apps protocol version'}});return;}
+ reply({protocolVersion:'2026-01-26',hostInfo:{name:'Codegraff',version:'1'},hostCapabilities:{openLinks:{},sandbox:{csp:approved,permissions:{}}},hostContext:{theme:matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light',displayMode:'inline',availableDisplayModes:['inline']}});return;
+ }
+ if(m.method==='ui/notifications/initialized'&&!initialized){initialized=true;send({method:'ui/notifications/tool-input',params:{arguments:snapshot.arguments}});send({method:'ui/notifications/tool-result',params:snapshot.result});status.textContent='Result view · tool execution disabled';return;}
+ if(!initialized)return;
+ if(m.method==='ui/notifications/size-changed'){const h=m.params?.height;if(Number.isFinite(h))proxy.style.height=Math.min(1000,Math.max(240,h))+'px';return;}
+ if(m.method==='ui/open-link'){
+ try{const u=new URL(m.params.url);if(!['http:','https:'].includes(u.protocol)||u.username||u.password)throw Error('invalid');link.href=u.href;link.textContent='Open source: '+u.href;link.hidden=false;status.textContent='Click Open source to continue';reply({});}catch{reply({isError:true});}return;
+ }
+ if(m.method==='ping'){reply({});return;}
+ if(m.id!==undefined)send({id:m.id,error:{code:-32601,message:'This saved-result host does not execute tools, read additional resources, or send agent messages.'}});
+});
+document.body.append(proxy);
+setTimeout(()=>{if(!initialized)status.textContent='This app did not connect. The ordinary tool result is still available in the transcript.';},10000);
+window.addEventListener('pagehide',()=>{if(initialized)send({id:'teardown',method:'ui/resource-teardown',params:{}});});
+</script></html>
diff --git a/src/mcp_apps.zig b/src/mcp_apps.zig
new file mode 100644
index 00000000..4d99dc46
--- /dev/null
+++ b/src/mcp_apps.zig
@@ -0,0 +1,111 @@
+//! MCP Apps result snapshots. HTML and _meta stay out of model context.
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const Value = std.json.Value;
+const rpc = @import("mcp_rpc.zig");
+const mime = "text/html;profile=mcp-app";
+const max_snapshot = 12 * 1024 * 1024;
+
+pub fn modelVisible(tool: Value) bool {
+ if (tool != .object) return true;
+ const meta = tool.object.get("_meta") orelse return true;
+ if (meta != .object) return true;
+ const ui = meta.object.get("ui") orelse return true;
+ if (ui != .object) return true;
+ const visibility = ui.object.get("visibility") orelse return true;
+ if (visibility != .array) return true;
+ for (visibility.array.items) |v| if (v == .string and std.mem.eql(u8, v.string, "model")) return true;
+ return false;
+}
+
+pub fn resourceUri(tool: Value) ?[]const u8 {
+ if (tool != .object) return null;
+ const meta = tool.object.get("_meta") orelse return null;
+ if (meta != .object) return null;
+ const nested = if (meta.object.get("ui")) |ui| (if (ui == .object) ui.object.get("resourceUri") else null) else null;
+ const value = nested orelse meta.object.get("ui/resourceUri") orelse return null;
+ if (value != .string or value.string.len > 2048 or !std.mem.startsWith(u8, value.string, "ui://")) return null;
+ return value.string;
+}
+
+pub fn readResource(response: Value, uri: []const u8) ?Value {
+ if (response != .object) return null;
+ const result = response.object.get("result") orelse return null;
+ if (result != .object) return null;
+ const contents = result.object.get("contents") orelse return null;
+ if (contents != .array) return null;
+ for (contents.array.items) |item| {
+ if (item != .object) continue;
+ const u = item.object.get("uri") orelse continue;
+ const m = item.object.get("mimeType") orelse continue;
+ if (u != .string or !std.mem.eql(u8, u.string, uri) or m != .string or !std.mem.eql(u8, m.string, mime)) continue;
+ return item;
+ }
+ return null;
+}
+
+pub fn snapshot(io: Io, a: Allocator, home: []const u8, server: *rpc.Server, uri: []const u8, input: Value, result: Value) ![]const u8 {
+ if (home.len == 0 or !std.fs.path.isAbsolute(home)) return error.NoHomeDirectory;
+ const params = try std.json.Stringify.valueAlloc(a, .{ .uri = uri }, .{});
+ const response = try rpc.readAppResource(server, a, io, params);
+ var resource = readResource(response, uri) orelse return error.InvalidAppResource;
+ if (resource.object.get("text")) |text| {
+ if (text != .string or text.string.len > 3 * 1024 * 1024) return error.AppTooLarge;
+ } else {
+ const blob = resource.object.get("blob") orelse return error.InvalidAppResource;
+ if (blob != .string) return error.InvalidAppResource;
+ const decoder = std.base64.standard.Decoder;
+ const size = try decoder.calcSizeForSlice(blob.string);
+ if (size > 3 * 1024 * 1024) return error.AppTooLarge;
+ const text = try a.alloc(u8, size);
+ try decoder.decode(text, blob.string);
+ _ = resource.object.swapRemove("blob");
+ try resource.object.put(a, "text", .{ .string = text });
+ }
+ const payload = try std.json.Stringify.valueAlloc(a, .{ .resource = resource, .arguments = input, .result = result }, .{});
+ if (payload.len > max_snapshot) return error.AppTooLarge;
+ const encoder = std.base64.standard.Encoder;
+ const encoded = try a.alloc(u8, encoder.calcSize(payload.len));
+ _ = encoder.encode(encoded, payload);
+ const template = @embedFile("mcp_app_host.html");
+ const marker = "GRAFF_APP_PAYLOAD";
+ const split = std.mem.indexOf(u8, template, marker).?;
+ const html = try std.mem.concat(a, u8, &.{ template[0..split], encoded, template[split + marker.len ..] });
+ const dir = try std.fmt.allocPrint(a, "{s}/.graff/mcp-apps", .{home});
+ try Io.Dir.cwd().createDirPath(io, dir);
+ try Io.Dir.cwd().setFilePermissions(io, dir, @enumFromInt(0o700), .{});
+ var random: [16]u8 = undefined;
+ io.random(&random);
+ const id = std.fmt.bytesToHex(random, .lower);
+ const path = try std.fmt.allocPrint(a, "{s}/{s}.html", .{ dir, id });
+ try @import("credential_store.zig").replaceFile(io, Io.Dir.cwd(), path, html, @enumFromInt(0o600));
+ return path;
+}
+
+test "MCP app resource metadata supports nested and legacy keys, rejects non-ui URLs" {
+ const a = std.testing.allocator;
+ const modern = try std.json.parseFromSlice(Value, a, "{\"_meta\":{\"ui\":{\"resourceUri\":\"ui://test/app\"}}}", .{});
+ defer modern.deinit();
+ try std.testing.expectEqualStrings("ui://test/app", resourceUri(modern.value).?);
+ const legacy = try std.json.parseFromSlice(Value, a, "{\"_meta\":{\"ui/resourceUri\":\"ui://legacy\"}}", .{});
+ defer legacy.deinit();
+ try std.testing.expectEqualStrings("ui://legacy", resourceUri(legacy.value).?);
+ const bad = try std.json.parseFromSlice(Value, a, "{\"_meta\":{\"ui\":{\"resourceUri\":\"https://invalid\"}}}", .{});
+ defer bad.deinit();
+ try std.testing.expect(resourceUri(bad.value) == null);
+}
+
+test "MCP app resources require matching URI and app MIME type" {
+ const parsed = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"result\":{\"contents\":[{\"uri\":\"ui://a\",\"mimeType\":\"text/html;profile=mcp-app\",\"text\":\"<h1>ok</h1>\"}]}}", .{});
+ defer parsed.deinit();
+ try std.testing.expect(readResource(parsed.value, "ui://a") != null);
+ try std.testing.expect(readResource(parsed.value, "ui://b") == null);
+}
+
+test "app-only MCP tools stay out of the model catalog" {
+ const p = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"_meta\":{\"ui\":{\"visibility\":[\"app\"]}}}", .{});
+ defer p.deinit();
+ try std.testing.expect(!modelVisible(p.value));
+ try std.testing.expect(modelVisible(.{ .object = .empty }));
+}
diff --git a/src/mcp_elicitation.zig b/src/mcp_elicitation.zig
index 7db12577..c3588604 100644
--- a/src/mcp_elicitation.zig
+++ b/src/mcp_elicitation.zig
@@ -22,7 +22,7 @@ const util = @import("util.zig");
/// Legacy `initialize` `capabilities` object. `{form:{}}` is the 2025-11-25
/// form-only shape; an empty `elicitation` object is also form-only, but
/// node_repl checks the named form key before calling createElicitation.
-pub const client_capabilities = "{\"elicitation\":{\"form\":{}}}";
+pub const client_capabilities = "{\"elicitation\":{\"form\":{}},\"extensions\":{\"io.modelcontextprotocol/ui\":{\"mimeTypes\":[\"text/html;profile=mcp-app\"]}}}";
pub const initialize_params =
"{\"protocolVersion\":\"" ++ mcp_protocol.legacy_protocol ++
diff --git a/src/mcp_protocol.zig b/src/mcp_protocol.zig
index 9e82788f..80d2dc8b 100644
--- a/src/mcp_protocol.zig
+++ b/src/mcp_protocol.zig
@@ -70,7 +70,7 @@ pub fn negotiatedProtocol(response: Value, transport: Transport) ![]const u8 {
/// advertises form elicitation so Computer Use `node_repl` can confirm
/// (`elicitation/create`) instead of crashing (#768).
pub const modern_meta =
- \\"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"codegraff","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}
+ \\"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"codegraff","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}},"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}}}
;
/// Build a JSON-RPC request line. Modern era splices the `_meta` envelope
diff --git a/src/mcp_rpc.zig b/src/mcp_rpc.zig
index 56473276..4c0c187f 100644
--- a/src/mcp_rpc.zig
+++ b/src/mcp_rpc.zig
@@ -162,6 +162,11 @@ pub fn initializeServer(server: *Server, response_alloc: Allocator, session_allo
server.era = .legacy;
}
+/// A broken view resource must not indefinitely delay an otherwise complete tool.
+pub fn readAppResource(server: *Server, a: Allocator, io: Io, params: []const u8) !Value {
+ return handshakeRequest(server, a, io, params, "resources/read");
+}
+
/// JSON-RPC request/response over either transport. `params` is a raw JSON
/// object string; `name` is the tool name for a `tools/call` (rendered as
/// `Mcp-Name` on a modern request) and null for everything else. Result