graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Forward MCP App tools/call through ACP
justrach3cd0b021dee2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7a4c9f31..e408a10f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,7 +14,7 @@ current is part of cutting a release.- Desktop ACP workers can park after a quiet period (`GRAFF_ACP_IDLE_MS`, default 30s) and `--resume` with the saved cache id. Parking is skipped while a prompt or `session/idle` subscriber is live; tab close still reaps immediately.- Turn chrome shows local tok/s while writing (and at settle); MCP tools/Apps wait instead of looking like slow generation (#1017).-- MCP App frames answer `ui/initialize`; app-initiated `tools/call` still fails until the host forwards ACP (#1018).+- MCP App frames answer `ui/initialize`; app-initiated `mcp__` `tools/call` is forwarded through ACP (`session/mcp_call`). Native tools stay refused (#1018).- GUI usage replies show grouped metrics and plan limits; inline editing keeps the message bubble and grows with its text. Subtle transcript reveals respect reduced motion.- `#1013`: keep the first answer after a no-tool retry without allowing older turns to replace a later answer (ADR 0139).- GUI usage replies show grouped metrics and plan limits; inline editing keeps the message bubble and grows with its text. Subtle transcript reveals respect reduced motion.diff --git a/apps/native/components/site/SnapshotView.tsx b/apps/native/components/site/SnapshotView.tsxindex 027e6dec..031304ff 100644--- a/apps/native/components/site/SnapshotView.tsx+++ b/apps/native/components/site/SnapshotView.tsx@@ -2,7 +2,8 @@import {useState, useEffect, useRef} from "react";import {validAppId} from "@/lib/mcp-apps";-import {hostReply} from "@/lib/mcp-apps-host";+import {hostReply, parseToolCall, toolCallError, toolCallResult} from "@/lib/mcp-apps-host";+import {callMcpAppTool} from "@/lib/acp-client";import motion from "./transcript-motion.module.css";/** One saved HTML snapshot shown inside the transcript. The two kinds differ@@ -42,9 +43,17 @@ export default function SnapshotView({kind, id}: {kind: SnapshotKind; id: stringif (kind !== "mcp-app") return;const onMessage = (event: MessageEvent) => {if (event.source === null || event.origin !== window.location.origin) return;+ const source = event.source as Window;+ const tool = parseToolCall(event.data);+ if (tool) {+ void callMcpAppTool(tool.name, tool.arguments)+ .then(result => source.postMessage(toolCallResult(tool.id, result), event.origin))+ .catch(error => source.postMessage(toolCallError(tool.id, error instanceof Error ? error.message : String(error)), event.origin));+ return;+ }const reply = hostReply(event.data);if (!reply) return;- (event.source as Window).postMessage(reply, event.origin);+ source.postMessage(reply, event.origin);};window.addEventListener("message", onMessage);return () => window.removeEventListener("message", onMessage);diff --git a/apps/native/components/site/useHarnessSessions.ts b/apps/native/components/site/useHarnessSessions.tsindex 9fdad9b6..4092d557 100644--- a/apps/native/components/site/useHarnessSessions.ts+++ b/apps/native/components/site/useHarnessSessions.ts@@ -1,5 +1,5 @@import { useEffect, useRef, useState, type MutableRefObject, type Dispatch, type SetStateAction } from "react";-import { checkHealth, disposePage, ensureSession, fetchModels, type Health } from "@/lib/acp-client";+import { bindMcpAppChat, checkHealth, disposePage, ensureSession, fetchModels, type Health } from "@/lib/acp-client";import { pumpIdlePeerTurns } from "./idle-peer-turns";import type { AcpCommand } from "@/lib/acp";import type { PromptModel } from "@/components/primitives/PromptBar";@@ -65,6 +65,10 @@ export function useHarnessSessions({sessionsRef, sessionNamesRef, chatsRef, work};}, []);+ useEffect(() => {+ bindMcpAppChat(sessionsRef.current.has(activeId) ? handleOf(activeId) : undefined);+ }, [activeId, handleOf]);+const requireSession = async (chatId: number, reset = false, key?: string): Promise<string> => {if (chatsRef.current.find(c => c.id === chatId)?.snapshot) throw new Error("Continue here before resuming this saved snapshot.");const live = sessionsRef.current.get(chatId);@@ -84,6 +88,7 @@ export function useHarnessSessions({sessionsRef, sessionNamesRef, chatsRef, workmcp: ws?.mcp,});sessionsRef.current.set(chatId, id);+ bindMcpAppChat(handleOf(chatId));setSessionIds((current) => ({ ...current, [chatId]: id }));watchIdle(chatId, id);// Populate the command menu from this agent's advertisement.diff --git a/apps/native/lib/acp-client.ts b/apps/native/lib/acp-client.tsindex 3030e8af..1d9e7afa 100644--- a/apps/native/lib/acp-client.ts+++ b/apps/native/lib/acp-client.ts@@ -276,3 +276,20 @@ export const MODELS: ModelChoice[] = [{ key: "grok-4.6", name: "Grok 4.6", tag: "xAI" },{ key: "kimi-k2.6", name: "Kimi K2.6", tag: "Moonshot" },];++let mcpAppChat: ChatHandle | undefined;+export function bindMcpAppChat(chat?: ChatHandle): void {+ mcpAppChat = chat;+}++/** Host-mediated MCP App tools/call. Native engine tools are refused. */+export async function callMcpAppTool(name: string, args: unknown): Promise<unknown> {+ if (!name.startsWith("mcp__") || !name.slice(5).includes("__")) {+ throw new Error("MCP Apps can only call mcp__ tools");+ }+ if (!mcpAppChat) throw new Error("No live ACP session for this MCP App");+ const res = await rpc(mcpAppChat, "session/mcp_call", { name, arguments: args && typeof args === "object" ? args : {} });+ const body = await res.json() as { result?: unknown; error?: string };+ if (body.error) throw new Error(body.error);+ return body.result;+}diff --git a/apps/native/lib/mcp-apps-host.test.ts b/apps/native/lib/mcp-apps-host.test.tsindex 60c4122b..123c8de9 100644--- a/apps/native/lib/mcp-apps-host.test.ts+++ b/apps/native/lib/mcp-apps-host.test.ts@@ -1,5 +1,5 @@import { expect, test } from "bun:test";-import { hostReply, MCP_APPS_PROTOCOL } from "./mcp-apps-host";+import { hostReply, MCP_APPS_PROTOCOL, parseToolCall } from "./mcp-apps-host";test("ui/initialize answers with the extension protocol version", () => {expect(hostReply({ jsonrpc: "2.0", id: 1, method: "ui/initialize" })).toEqual({@@ -7,9 +7,17 @@ test("ui/initialize answers with the extension protocol version", () => {});});-test("app-initiated tools/call is refused until the host forwards ACP", () => {- const reply = hostReply({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "search" } });- expect(reply).toMatchObject({ jsonrpc: "2.0", id: 2, error: { code: -32000 } });+test("tools/call is parsed for ACP forwarding, not answered inline", () => {+ expect(hostReply({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "mcp__docs__search" } })).toBeNull();+ expect(parseToolCall({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "mcp__docs__search", arguments: { q: "x" } } }))+ .toEqual({ id: 2, name: "mcp__docs__search", arguments: { q: "x" } });+ expect(parseToolCall({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "write_file" } }))+ .toEqual({ id: 3, name: "write_file", arguments: undefined });+});++test("native engine tool names are not ACP MCP calls", async () => {+ const { callMcpAppTool } = await import("./acp-client");+ await expect(callMcpAppTool("write_file", { path: "/tmp/x" })).rejects.toThrow("mcp__");});test("non-RPC traffic is ignored", () => {diff --git a/apps/native/lib/mcp-apps-host.ts b/apps/native/lib/mcp-apps-host.tsindex 53cfeb25..2c89208b 100644--- a/apps/native/lib/mcp-apps-host.ts+++ b/apps/native/lib/mcp-apps-host.ts@@ -1,6 +1,4 @@-/** MCP Apps extension dialect (ui/* over postMessage). Snapshot HTML still- * renders without this; app-initiated tools stay refused until the host- * forwards them through ACP. Spec: 2026-01-26. */+/** MCP Apps extension dialect (ui/* over postMessage). Spec: 2026-01-26. */export const MCP_APPS_PROTOCOL = "2026-01-26";@@ -10,15 +8,35 @@ export type HostReply =| { jsonrpc: "2.0"; id: unknown; result: unknown }| { jsonrpc: "2.0"; id: unknown; error: { code: number; message: string } };+export type ToolCall = { id: unknown; name: string; arguments: unknown };++export function parseToolCall(data: unknown): ToolCall | null {+ if (!data || typeof data !== "object") return null;+ const msg = data as JsonRpc;+ if (msg.jsonrpc !== "2.0" || msg.method !== "tools/call" || msg.id === undefined) return null;+ const params = msg.params && typeof msg.params === "object" ? msg.params as { name?: unknown; arguments?: unknown } : {};+ if (typeof params.name !== "string" || !params.name) return null;+ return { id: msg.id, name: params.name, arguments: params.arguments };+}+export function hostReply(data: unknown): HostReply | null {if (!data || typeof data !== "object") return null;const msg = data as JsonRpc;if (msg.jsonrpc !== "2.0" || typeof msg.method !== "string" || msg.id === undefined) return null;+ if (msg.method === "tools/call") return null;if (msg.method === "ui/initialize") {return { jsonrpc: "2.0", id: msg.id, result: { protocolVersion: MCP_APPS_PROTOCOL } };}- if (msg.method === "tools/call" || msg.method.startsWith("ui/")) {+ if (msg.method.startsWith("ui/")) {return { jsonrpc: "2.0", id: msg.id, error: { code: -32000, message: "Host-mediated MCP App tool calls are not enabled yet." } };}return null;}++export function toolCallError(id: unknown, message: string): HostReply {+ return { jsonrpc: "2.0", id, error: { code: -32000, message } };+}++export function toolCallResult(id: unknown, result: unknown): HostReply {+ return { jsonrpc: "2.0", id, result };+}diff --git a/docs/mcp-apps.md b/docs/mcp-apps.mdindex 6107373f..a866cb7f 100644--- a/docs/mcp-apps.md+++ b/docs/mcp-apps.md@@ -4,7 +4,7 @@ Call a connected MCP tool that declares an MCP Apps UI. In the native GUI, its tIn 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. The framed app can send `ui/initialize` over postMessage (MCP Apps 2026-01-26). The host answers with the protocol version. App-initiated `tools/call` still fails explicitly until the host forwards those requests through ACP (#1018).+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. The framed app can send `ui/initialize` over postMessage (MCP Apps 2026-01-26). The host answers with the protocol version. App-initiated `tools/call` for `mcp__` tools is forwarded through ACP (`session/mcp_call`) on the live chat; native engine tools stay refused (#1018).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.diff --git a/src/acp.zig b/src/acp.zigindex 68de4c99..3ba543da 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -119,6 +119,7 @@ fn liveModels(ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Requeconst live: *LiveTurn = @ptrCast(@alignCast(ctx));if (try @import("acp_agents.zig").handle(arena, live.root.io, live.root.home, w, req)) return true;if (try @import("acp_changes.zig").handle(arena, live.root.io, w, req)) return true;+ if (try @import("acp_mcp_app.zig").handle(arena, w, req, live.root)) return true;if (!std.mem.eql(u8, req.method, "graff/models")) return false;if (req.id == null) return true;const keys = live.keys;diff --git a/src/acp_mcp_app.zig b/src/acp_mcp_app.zignew file mode 100644index 00000000..a0b1347c--- /dev/null+++ b/src/acp_mcp_app.zig@@ -0,0 +1,47 @@+//! Host-mediated MCP App `tools/call` over ACP (`session/mcp_call`).+//! Native engine tools are refused; only `mcp__` catalog entries run.++const std = @import("std");+const Allocator = std.mem.Allocator;+const proto = @import("acp_protocol.zig");+const Agent = @import("agent.zig").Agent;++fn strField(params: ?std.json.Value, key: []const u8) []const u8 {+ const p = params orelse return "";+ if (p != .object) return "";+ const v = p.object.get(key) orelse return "";+ return if (v == .string) v.string else "";+}++pub fn allowedMcpName(name: []const u8) bool {+ return std.mem.startsWith(u8, name, "mcp__") and std.mem.indexOf(u8, name["mcp__".len..], "__") != null;+}++pub fn handle(arena: Allocator, w: *std.Io.Writer, req: proto.Request, root: *Agent) !bool {+ if (!std.mem.eql(u8, req.method, "session/mcp_call")) return false;+ if (req.id == null) return true;+ const name = strField(req.params, "name");+ if (!allowedMcpName(name)) {+ try proto.writeError(w, req.id, proto.err_auth_required, "MCP Apps can only call mcp__ tools");+ return true;+ }+ const registry = root.registry orelse {+ try proto.writeError(w, req.id, proto.err_internal, "No MCP session is live");+ return true;+ };+ const empty: std.json.ObjectMap = .empty;+ const args: std.json.Value = if (req.params) |p| (if (p == .object) (p.object.get("arguments") orelse .{ .object = empty }) else .{ .object = empty }) else .{ .object = empty };+ const called = registry.call(arena, name, args) catch |err| {+ try proto.writeError(w, req.id, proto.err_internal, @errorName(err));+ return true;+ };+ try proto.writeResult(w, req.id, .{ .content = called.text, .isError = called.is_error });+ return true;+}++test "MCP Apps cannot invoke native engine tools" {+ try std.testing.expect(!allowedMcpName("write_file"));+ try std.testing.expect(!allowedMcpName("bash"));+ try std.testing.expect(!allowedMcpName("mcp__incomplete"));+ try std.testing.expect(allowedMcpName("mcp__docs__search"));+}diff --git a/src/main.zig b/src/main.zigindex 30b05441..50fdb3fb 100644--- a/src/main.zig+++ b/src/main.zig@@ -592,6 +592,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = @import("goal_pacing.zig");_ = .{ @import("presence_accord.zig"), @import("peer_idle.zig"), @import("acp_idle.zig"), @import("presence_chan.zig"), @import("presence_record.zig"), @import("peer_inbox_content_test.zig"), @import("peer_inbox_failure_test.zig"), @import("peer_inbox_storage_test.zig"), @import("peer_inbox_sequence_test.zig"), @import("peer_inbox_snapshot_test.zig") };_ = @import("acp_agents.zig");+ _ = @import("acp_mcp_app.zig");_ = @import("subagent_activity.zig");_ = @import("subagent_recovery.zig");_ = @import("acp_agent_activity.zig");diff --git a/src/mcp_app_host.html b/src/mcp_app_host.htmlindex 69e68c1f..41289f7f 100644--- a/src/mcp_app_host.html+++ b/src/mcp_app_host.html@@ -38,15 +38,21 @@ window.addEventListener('message',event=>{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(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 · MCP tools via ACP';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.method==='tools/call'){parent.postMessage(m,'*');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.'}});});+window.addEventListener('message',event=>{+ if(event.source!==parent)return;const r=event.data;if(!r||r.jsonrpc!=='2.0'||r.id===undefined)return;+ if(r.result!==undefined)send({id:r.id,result:r.result});+ else if(r.error)send({id:r.id,error:r.error});+});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:{}});});