Use MCP Apps with agentproto: serve a screen from your tool and see it in a session
Serve a tappable screen from your MCP server, let the agentproto daemon read it, and mount it yourself. Run against the published packages.
· Jeremy

A tool that answers with text is a function. A tool that answers with a floor plan you can tap is a small program. Here is how to make the second kind and see it in agentproto.
I wrote MCP Apps explained to say what the extension is. This guide is the hands-on follow-up: a small MCP server that serves a screen, the agentproto daemon reading that screen, and a page of your own that draws it and sends taps back. I ran every step below against the published packages on 2 December 2026: @agentproto/cli 1.41.0, @agentproto/mcp-server 0.9.2 and @agentproto/mcp-app-host 0.2.1.
What you get
- An MCP server (the Model Context Protocol, the standard way for outside software to hand tools to an assistant) with two tools and one
ui://page:find_tablesreturns free restaurant tables, and the page shows a button per table. - A daemon (the background agentproto program) that finds your server through a session's MCP config and hands the page to whoever draws it.
- A host page of about fifty lines that draws the view in an iframe, a web page embedded in another with strict limits, and routes its taps back to your server.
Here is the whole chain. Steps 2 to 5 build it from left to right.

The daemon is the MCP client. The host never talks to your server directly.
1. Prerequisites
You need Node (I used v24.21.0) and a global install of the CLI, as the README says:
npm i -g @agentproto/cli
agentproto serve # the daemon, http://127.0.0.1:18790 by defaultFor the server code, in an empty folder:
npm i @agentproto/[email protected] @modelcontextprotocol/sdk zodI tested on a separate daemon with its own home folder and its own port (agentproto serve --port 18911), so nothing here touched my everyday daemon. Use --port if you want the same.
2. Write the server
registerUiResource from @agentproto/mcp-server serves a page as a ui:// resource. Its options are name, uri, html (a string, or a function run on every read), and optionally description, csp, prefersBorder (default true) and meta. It sets the MIME type text/html;profile=mcp-app for you. meta is for namespaced vendor hints; passing a ui key throws, because _meta.ui belongs to the helper.
The tool side is plain SDK code: put _meta.ui.resourceUri on the tool definition. (@agentproto/mcp-server also has toMcpTool with a ui option that does the same for its tool contracts.)
server.mjs:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"
import { registerUiResource } from "@agentproto/mcp-server"
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
import { readFileSync } from "node:fs"
import { z } from "zod"
const held = new Set()
const server = new McpServer({ name: "tables", version: "1.0.0" })
const uri = "ui://tables/floor-plan.html"
const tables = [
{ id: 4, seats: 2 }, { id: 7, seats: 4 }, { id: 9, seats: 6 },
]
registerUiResource(server, {
name: "floor-plan",
uri,
description: "Tap a table to hold it.",
prefersBorder: true,
csp: { connectDomains: [], resourceDomains: [] },
meta: { "acme/display": { height: 320 } },
html: () => readFileSync(new URL("./floor-plan.html", import.meta.url), "utf8"),
})
server.registerTool("find_tables", {
description: "List free tables for a party size.",
inputSchema: { partySize: z.number().int().min(1) },
_meta: { ui: { resourceUri: uri } },
}, async ({ partySize }) => {
const free = tables.filter(t => t.seats >= partySize && !held.has(t.id))
return {
content: [{ type: "text", text: `Free tables: ${free.map(t => t.id).join(", ") || "none"}.` }],
structuredContent: { tables: free },
}
})
server.registerTool("hold_table", {
description: "Hold a table for 10 minutes.",
inputSchema: { tableId: z.number().int() },
_meta: { ui: { resourceUri: uri, visibility: ["app"] } },
}, async ({ tableId }) => {
held.add(tableId)
return { content: [{ type: "text", text: `Table ${tableId} held for 10 minutes.` }] }
})
server.registerTool("clear_holds", {
description: "Release every held table.",
_meta: { ui: { resourceUri: uri, visibility: ["model"] } },
}, async () => {
held.clear()
return { content: [{ type: "text", text: "All holds released." }] }
})
await server.connect(new StdioServerTransport())The page, floor-plan.html. It speaks the MCP Apps messages by hand over postMessage (the browser's way for an embedded page to talk to the page around it), so you can see exactly what crosses the wire. In a real project you would use the App class from @modelcontextprotocol/ext-apps instead.
<!doctype html>
<html><head><meta charset="utf-8"><title>Floor plan</title></head>
<body>
<h3>Free tables</h3>
<ul id="list"></ul>
<script>
let nextId = 1
const pending = new Map()
function rpc(method, params) {
const id = nextId++
parent.postMessage({ jsonrpc: "2.0", id, method, params }, "*")
return new Promise(r => pending.set(id, r))
}
function note(method, params) { parent.postMessage({ jsonrpc: "2.0", method, params }, "*") }
function draw(tables) {
const ul = document.getElementById("list"); ul.innerHTML = ""
for (const t of tables) {
const li = document.createElement("li")
const b = document.createElement("button")
b.textContent = "Hold table " + t.id + " (" + t.seats + " seats)"
b.onclick = async () => {
const res = await rpc("tools/call", { name: "hold_table", arguments: { tableId: t.id } })
b.textContent = res.result ? res.result.content[0].text : "error: " + JSON.stringify(res.error || res.result)
}
li.appendChild(b); ul.appendChild(li)
}
}
window.addEventListener("message", e => {
const m = e.data
if (m && m.id !== undefined && pending.has(m.id)) { pending.get(m.id)(m); pending.delete(m.id); return }
if (m && m.method === "ui/notifications/tool-result") draw(m.params.structuredContent.tables)
})
rpc("ui/initialize", {
appInfo: { name: "Floor plan", version: "1.0.0" },
appCapabilities: {},
protocolVersion: "2026-01-26",
}).then(() => note("ui/notifications/initialized", {}))
</script></body></html>Three things to notice. find_tables has no visibility, so both the model and the page may call it. hold_table has visibility: ["app"]: only the page. clear_holds has ["model"]: only the model, which matters in step 3.
Check it with an MCP client
A short probe with the SDK's own client, run with node client.mjs:
import { Client } from "@modelcontextprotocol/sdk/client/index.js"
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
const client = new Client({ name: "probe", version: "0.0.1" })
await client.connect(new StdioClientTransport({ command: "node", args: ["server.mjs"] }))
for (const t of (await client.listTools()).tools) console.log("tool", t.name, JSON.stringify(t._meta))
console.log("resources", JSON.stringify((await client.listResources()).resources))
const read = await client.readResource({ uri: "ui://tables/floor-plan.html" })
console.log("read", read.contents[0].mimeType, JSON.stringify(read.contents[0]._meta))
console.log("call", JSON.stringify(await client.callTool({ name: "find_tables", arguments: { partySize: 3 } })))
await client.close()What I saw (abridged):
tool find_tables {"ui":{"resourceUri":"ui://tables/floor-plan.html"}}
tool hold_table {"ui":{"resourceUri":"ui://tables/floor-plan.html","visibility":["app"]}}
tool clear_holds {"ui":{"resourceUri":"ui://tables/floor-plan.html","visibility":["model"]}}
resources [{"name":"floor-plan","uri":"ui://tables/floor-plan.html","mimeType":"text/html;profile=mcp-app",
"_meta":{"ui":{"prefersBorder":true,"csp":{"connectDomains":[],"resourceDomains":[]}},"acme/display":{"height":320}}}]
read text/html;profile=mcp-app {"ui":{"prefersBorder":true,"csp":{...}},"acme/display":{"height":320}}
call {"content":[{"type":"text","text":"Free tables: 7, 9."}],"structuredContent":{"tables":[{"id":7,"seats":4},{"id":9,"seats":6}]}}The _meta.ui block is on the tool definitions, and on both the resources/list entry and the resources/read content. The helper writes it in both places because the spec has hosts read the policy from resources/read first. The tool still returns its text, so a client without MCP Apps support gets a usable answer.
3. Connect the server to a session, and read it as the daemon does
A session's harness (the coding agent CLI, such as Claude Code) is the MCP client in a session, and it keeps the screen to itself. So the daemon opens its own connection to your server and answers three questions for whoever draws the chat. It finds your server by the name the harness shows: tables in mcp__tables__find_tables. The lookup is per session, and the first match wins (mcp-app-resolve.ts):
- the session's own
mcpServers(for example fromagentproto sessions start ... --mcp-servers-json); - the project of the session's
cwd:.mcp.json, then~/.claude.jsonunderprojects[...], then.codex/config.tomland~/.codex/config.toml; - the user scope, the top-level
mcpServersof~/.claude.json; - servers imported into the daemon (
mcp_discovered_list, thenmcp_import).
The simplest route is a .mcp.json in the session's working folder:
{ "mcpServers": { "tables": { "command": "node", "args": ["/path/to/server.mjs"] } } }Each answer carries a source field. I checked all of these on the test daemon: with tables set in the project and also in ~/.claude.json, the project one won ("source":"project"). With the server only in ~/.claude.json it said "user". After mcp_import of that entry and removal from the file, it said "imported".
Calling the three tools
There is no CLI verb for them. They are MCP tools on the daemon's /mcp endpoint, so any JSON-RPC client works, curl included. The daemon answers as a server-sent event, so the JSON is on the data: line.
To get a session id without spending model tokens, I started a terminal session with the daemon's terminal_start tool, in the folder that holds the .mcp.json (the daemon first needs the command in <workspace>/.agentproto/allowed-commands.json). A real session works the same; take its id from agentproto sessions.
call() { curl -s localhost:18911/mcp \
-H 'content-type: application/json' -H 'accept: application/json, text/event-stream' \
-d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"$1\",\"arguments\":$2}}" \
| sed -n 's/^data: //p'; }
call mcp_app_ui_index '{"sessionId":"sess_a6eb173e","server":"tables"}'The tool result is a JSON string inside result.content[0].text. Unwrapped:
{ "server": "tables", "status": "ok",
"tools": [
{ "name": "find_tables", "resourceUri": "ui://tables/floor-plan.html", "appOnly": false },
{ "name": "hold_table", "resourceUri": "ui://tables/floor-plan.html", "appOnly": true },
{ "name": "clear_holds", "resourceUri": "ui://tables/floor-plan.html", "appOnly": false } ],
"appOnlyTools": ["hold_table"],
"allToolNames": ["find_tables", "hold_table", "clear_holds"],
"notAppVisibleTools": ["clear_holds"],
"source": "project" }appOnly marks hold_table. notAppVisibleTools lists the tools the page may not call. Failures are in the answer, never a tool error. I saw status: "unresolved" with no MCP server named "nope" in this session's scope and with unknown session, and status: "unreachable" for a server whose script did not exist (the message carried the Node error). The fourth status, auth_required, is returned for a 401 from a remote server. A failed server is not retried for 60 seconds.
Next, read the page:
call mcp_app_ui_read '{"sessionId":"sess_a6eb173e","server":"tables","resourceUri":"ui://tables/floor-plan.html"}'{ "resourceUri": "ui://tables/floor-plan.html", "html": "<!doctype html>...", "mimeType": "text/html;profile=mcp-app",
"csp": { "connectDomains": [], "resourceDomains": [] }, "prefersBorder": true }permissions and domain appear when the server sets them. Only a resourceUri that the index returned is accepted; ui://tables/other.html came back as {"error":"resourceUri ... is not declared by any tool of server \"tables\"","status":"ok"}.
Last, the call a tap would make:
call mcp_app_tool_call '{"sessionId":"sess_a6eb173e","server":"tables","tool":"hold_table","args":{"tableId":7},"originToolCallId":"toolu_1"}'
# {"content":[{"type":"text","text":"Table 7 held for 10 minutes."}]}
call mcp_app_tool_call '{"sessionId":"sess_a6eb173e","server":"tables","tool":"clear_holds","originToolCallId":"toolu_1"}'
# {"isError":true,"content":[{"type":"text","text":"mcp_app_tool_call: tool \"clear_holds\" is not callable from an app UI on server \"tables\" (its _meta.ui.visibility excludes \"app\"; ...)"}]}The first returns the upstream result as is. The second is the refusal: clear_holds is model-only. A tool that does not exist gets its own message. originToolCallId is the id of the transcript card that hosts the iframe; it also lets the tool that owns the screen be called even if it is marked model-only.
Each call is recorded in the session's events.jsonl, without arguments or results:
{"kind":"mcp_app_tool_call","server":"tables","tool":"hold_table","originToolCallId":"toolu_1","isError":false,"durationMs":2}One thing I hit: the daemon keeps its connection to your server. When I changed the server's tool list, the daemon kept answering with the old one until I restarted my test daemon.
4. Where a person sees the screen
What the VS Code extension (packages/vscode) does with it:
- An installed app's screen.
appPanel.tsopens an editor tab (view typeagentproto.appPanel) whose HTML comes from the daemon resourceui://app_ui_<slug>/view. The tab is a thin outer page with one full-sizesrcdociframe and a relay script;AppPanelControlleris the host half, built oncreateMcpAppHost. It gives the view one handler,callTool, which goes to the daemon under that app's own tool allowlist. It answersui/initialize,ui/request-display-mode,ui/message,ui/update-model-contextandtools/call, and refuses any other method, includingui/open-link. - The session chat.
chatPanel.tsopens a tab titledChat: <sessionId>with a full-size iframe of the session chat page that the daemon serves (?embed=1#session=<id>). The extension adds no MCP Apps bridge there; the page talks to the daemon itself.
The session chat is the client these daemon tools are written for: it reaches the daemon through tool calls on its own allowlist, and the mcp-app-host README says the VS Code extension and the session chat share one host library. If you want a screen in a place you control, build the host yourself (step 5).
5. Mount the view yourself
@agentproto/mcp-app-host is the host half, written with no framework. @agentproto/mcp-app-host/dom has mountMcpApp, which makes the iframe. The root export has createMcpAppHost(transport, opts), the core that works with any transport. Pure helpers buildCspPolicy, buildCspMeta and injectCsp are exported from /dom.
This page does what the chain in the first figure does: read the view from the daemon, mount it, feed it the tool result, and route taps back through mcp_app_tool_call. host.ts:
import { mountMcpApp, createDaemonSandboxResolver } from "@agentproto/mcp-app-host/dom"
const DAEMON = "http://127.0.0.1:18911"
const SESSION = new URLSearchParams(location.search).get("session")!
const SERVER = "tables"
const URI = "ui://tables/floor-plan.html"
// One daemon tool call over JSON-RPC; the daemon answers with a single SSE message.
async function daemonTool(name: string, args: Record<string, unknown>) {
const res = await fetch(`${DAEMON}/mcp`, {
method: "POST",
headers: { "content-type": "application/json", accept: "application/json, text/event-stream" },
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
})
const text = await res.text()
const data = text.split("\n").find(l => l.startsWith("data: "))!.slice(6)
return JSON.parse(JSON.parse(data).result.content[0].text)
}
const ui = await daemonTool("mcp_app_ui_read", { sessionId: SESSION, server: SERVER, resourceUri: URI })
const mounted = await mountMcpApp({
container: document.getElementById("app")!,
ui,
// ?restricted=1 forces the srcdoc fallback.
sandbox: new URLSearchParams(location.search).has("restricted")
? false
: createDaemonSandboxResolver({ baseUrl: DAEMON }),
hostInfo: { name: "my-host", version: "1.0.0" },
hostContext: { theme: "light", displayMode: "inline", availableDisplayModes: ["inline"] },
handlers: {
// The iframe never talks to the server: every tools/call lands here.
callTool: ({ name, arguments: args }) =>
daemonTool("mcp_app_tool_call", {
sessionId: SESSION, server: SERVER, tool: name, args: args ?? {},
originToolCallId: "toolu_demo",
}),
onSizeChanged: ({ height }) => { if (height) mounted.iframe.style.height = `${height}px` },
},
})
mounted.iframe.style.width = "100%"
mounted.iframe.style.height = "260px"
document.title = `mounted:${mounted.mode}`
// Feed the view the result of the model's tool call.
const result = await daemonTool("mcp_app_tool_call", {
sessionId: SESSION, server: SERVER, tool: "find_tables", args: { partySize: 1 }, originToolCallId: "toolu_demo",
})
await mounted.host.sendToolInput({ partySize: 1 })
await mounted.host.sendToolResult(result)
;(window as any).__mounted = mountedBundle it and serve it from any static server on a different origin from the daemon (I used a tiny Node static server on port 18912):
npm i @agentproto/[email protected] && npm i -D esbuild
npx esbuild host.ts --bundle --format=esm --outfile=host.js --platform=browser --target=es2022
# index.html: <div id="app"></div><script type="module" src="/host.js"></script>I opened it in headless Chrome 158 and drove it over the DevTools protocol, with the test session from step 3:
host page title: mounted:sandbox-origin
iframe sandbox: allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox
iframe src: http://<token>.sandbox.localhost:18911/v/<token>
host origin: http://127.0.0.1:18912
view origin: http://<token>.sandbox.localhost:18911
buttons: Hold table 4 (2 seats) | Hold table 7 (4 seats) | Hold table 9 (6 seats)
after a click: Table 4 held for 10 minutes. | Hold table 7 (4 seats) | Hold table 9 (6 seats)The tap went iframe, host callTool, daemon mcp_app_tool_call, your server, and the answer came back as the button label. The session log gained a hold_table record. With ?restricted=1 (which makes my page pass sandbox: false) the same page ran in the other mode: title mounted:restricted, no src (a srcdoc iframe), view origin: null, and the click worked too.
mountMcpApp returns { mode, iframe, host, dispose }. On the host object, sendToolInput, sendToolResult and setHostContext queue until the view is ready. Handlers beyond callTool are optional, and the host advertises a capability only when you give the handler. I checked buildHostCapabilities: with only callTool it returns {"serverTools":{}}; adding sendMessage, openLink, updateModelContext and onLog adds message, openLinks, updateModelContext and logging. Without an openLink handler, a view's ui/open-link gets "Method not found".
The two isolation modes

Same view, same inputs. The difference is who serves the document and what origin it has.
Sandbox origin is the mode the spec asks for. The host registers the view with the daemon (POST /mcp-app-sandbox/views) and loads the returned URL in the iframe. The host page and the view have different origins, and mountMcpApp refuses a view whose origin matches the host's. The transport only accepts messages from that iframe's window and origin, and addresses its own to that origin.
Restricted is the fallback when no sandbox origin is available: an opaque-origin srcdoc iframe without allow-same-origin, with a CSP <meta> placed ahead of any author content. It is safe, but a view that needs IndexedDB, a real origin or an OAuth callback will not run.
The daemon picks the sandbox origin from daemon.mcpAppSandbox.mode, which is not writable through config_set: edit ~/.agentproto/config.json and restart.
mode | What you get | What I ran |
|---|---|---|
subdomain (default) | <token>.sandbox.localhost on the daemon's own port, one origin per view | Full run above |
port | a second listener on daemon.mcpAppSandbox.port, one origin shared by all views | {"daemon":{"mcpAppSandbox":{"mode":"port","port":18911}}} with the daemon on 18912: the registration answered "mode":"port","shared":true; /health on the sandbox port was a 404; a POST there was 405 |
off | no sandbox origin; hosts use the restricted mode | registration answered 501 {"error":"sandbox_disabled"} |
Limits from the package README: *.sandbox.localhost must resolve to loopback (Chrome and Firefox do), so use port where it does not. In port mode mountMcpApp mounts one view at a time per shared origin and the daemon wipes that origin's storage on each load. _meta.ui.domain is not honoured. There is no double-iframe sandbox proxy; the view is a document on its own origin instead.
6. What agentproto enforces
A default policy of nothing. With no csp, buildCspPolicy returns default-src 'none' with connect-src 'none', frame-src 'none', form-action 'none' and base-uri 'none', and allows inline scripts and styles, data: and blob: images, and data: fonts. Domains you declare in connectDomains and resourceDomains are added to the matching directives.
Local and private sources are dropped by the daemon. I registered a view with connectDomains of https://api.example.com, http://localhost:3000, http://192.168.1.5 and https://*.example.org, and resourceDomains of https://cdn.example.com and *. The header the daemon served had connect-src 'self' https://api.example.com https://*.example.org and the CDN only in the resource directives. The localhost address, the private address and * were gone. In the code (targetsDaemon) the dropped sources are loopback, private and link-local ranges, every IPv6 literal, local name suffixes, single-label names, the host page's own hostname, *, bare http: and ws:, and data:, about: and javascript:. The document also carries Cache-Control: no-store, Referrer-Policy: no-referrer, X-Content-Type-Options: nosniff, and a frame-ancestors pinned to the origin that registered it.
That filter is in the daemon's header. In restricted mode, the 0.2.1 builder passed the same declared sources straight into the <meta> (I printed it: connect-src https://api.example.com http://localhost:3000 http://192.168.1.5), so what the view's own origin can reach there depends on the browser.
The daemon refuses its own sandbox origin. A request to a daemon route that arrives with a sandbox origin as Origin or Referer gets a 403. A sandbox host serves only GET and HEAD on /v/<token>. Tokens are 128 bits, expire (default 15 minutes) and the store is bounded.
Handlers are advertised only when they exist, as shown in step 5.
App-only tools stay off the model's list and out of the model's hands. The page's tap goes through mcp_app_tool_call, which refuses tools whose visibility excludes app. It is a different tool from the model's mcp_imported_call. The tool documentation notes that, like mcp_imported_call, it has no other per-call permission check, and it is not offered on the daemon's scoped orchestrator gateway.
7. Package it as an app (optional)
An agentproto app (AIP-53, a bundle of agents, workflows and tools) can carry its own screen: an ui block in APP.md and a .agentproto/ui/index.html that receives a window.McpApp bridge, with every tool it calls named in ui.tools. The daemon serves that page as ui://app_ui_<slug>/view, which is what the VS Code app panel reads in step 4. agentproto app serve <dir> serves it standalone in a browser.
The repo's build-your-own-agent-app guide walks through building one.
There is a quicker preview for a server you already have. agentproto app serve has a remote mode: I ran my server over streamable HTTP (a stateless StreamableHTTPServerTransport, port 18912) and started
agentproto app serve --port 18911 --remote-mcp-url http://127.0.0.1:18912/mcp --remote-app-id ui://tables/floor-plan.htmlIt printed serving remote app 'ui://tables/floor-plan.html' ... MCP bridge -> http://127.0.0.1:18912/mcp, and the page came back from http://127.0.0.1:18911/ with a window.McpApp bridge injected. Its --help says every tool the remote server exposes is forwarded, and it was: /__agentproto/tool-call ran find_tables and also the model-only clear_holds. Treat it as a development convenience on loopback, not as an enforcement of visibility.
8. What can go wrong
- The session must exist and know the name. An unknown session id or a name that is in none of the four places gives
unresolved. The name is the harness's, not the server'snamefield. - A stale connection. The daemon pools its connection to your server (see the end of step 3).
- Resolution is cached. A failed server is not retried for a minute.
- Browser support.
subdomainmode needs*.sandbox.localhostto resolve. If your view falls into restricted mode, check the browser console for "view in restricted mode". - A view has no network by default. Declare the domains it needs in
csp; local addresses will not be allowed in sandbox mode.
Start here
- Write the text-only tool first, then add one
registerUiResourceand_meta.ui.resourceUri. Probe it with the SDK client. - Put screen-only actions behind
visibility: ["app"]and check the refusal withmcp_app_tool_call. - Put the server in the session's
.mcp.json, then callmcp_app_ui_indexandmcp_app_ui_readon the daemon's/mcp. - To draw it yourself, use
mountMcpAppwith the daemon's sandbox resolver and routecallTooltomcp_app_tool_call. - Declare only the domains the view needs. Keep
daemon.mcpAppSandbox.modeatsubdomainunless your browser cannot resolve*.localhost.
MCP Apps explained · AIP-53 · mcp-app-host README · registerUiResource source · MCP Apps specification