Articles · · 12 min read

MCP Apps From Scratch

AIPart 2

In part 1 of MCP Apps From Scratch, the view only displayed what it was given. The host called a tool, pushed structuredContent through ontoolresult, and a plain custom element rendered it. The view never called the server, and it never opened a link.

This post adds both. A Greet again button calls the same tool with callServerTool. An Open the spec button asks the host to open a URL with openLink. The host’s capabilities object is the security gate: the view is untrusted, and it can only do what the host listed when it created AppBridge.

The code lives in post-2-talks-back, in the same mcp-apps-series repo. The shared test host in host/ is reused, with one addition: you can turn a capability off by adding ?serverTools=0 or ?openLinks=0 to the host page’s URL.

Run it

You will need Node 20+ and npm.

git clone https://github.com/mdownes/mcp-apps-series.git
cd mcp-apps-series/post-2-talks-back
npm install
npm start

If you already cloned the repo for part 1, cd into post-2-talks-back and run the last two commands.

Open http://localhost:8080. npm start builds the view and the shared host, then starts the MCP server on port 3001 and the host together. The host calls the greet tool when the page loads, so you should see Hello, world!, an ISO timestamp, and the note “From the host, via ontoolresult.”

The two buttons start disabled and enable once the view has read the host’s capabilities. Type a name and press Greet again to call the tool from the view. Press Open the spec to ask the host to open the MCP Apps specification in a new tab.

The server: one tool, two callers

The server is the same shape as part 1. The tool is now named greet, the resource is ui://talks-back/view.html, and the server name is talks-back. The interesting change is who calls the tool.

// One tool. The host calls it to open the view. The view calls it again
// with callServerTool. Both paths hit this function; the difference is
// who receives the result (ontoolresult vs the returned promise).
registerAppTool(
  server,
  "greet",
  {
    title: "Greet",
    description: "Returns a greeting and the current server time.",
    inputSchema: z.object({
      name: z.string().optional().describe("Name to greet. Defaults to 'world'."),
    }),
    outputSchema: z.object({
      greeting: z.string(),
      time: z.string(),
    }),
    _meta: { ui: { resourceUri: RESOURCE_URI } },
  },
  async ({ name }) => {
    const who = name?.trim() || "world";
    const time = new Date().toISOString();
    const greeting = `Hello, ${who}!`;
    return {
      content: [{ type: "text", text: `${greeting} The time is ${time}.` }],
      structuredContent: { greeting, time },
    };
  },
);

There is still one implementation. When the host calls greet on load, the result is pushed into the view as ui/notifications/tool-result, and ontoolresult runs. When the view calls greet itself, the same function runs, but the result comes back as the return value of callServerTool. The server does not know which path was used.

The view: callServerTool and openLink

The view is a plain custom element, <talks-back>. It still imports App from @modelcontextprotocol/ext-apps, still registers ontoolresult before connect(), and still reads result.structuredContent. After connect() resolves, it also reads the host’s capabilities and enables the buttons the host granted.

import { App } from "@modelcontextprotocol/ext-apps";

connectedCallback() {
  // Register BEFORE connect() so a fast host cannot deliver the result first.
  this.app.ontoolresult = (result) => {
    this.data = result.structuredContent as Data;
    this.note = "From the host, via ontoolresult.";
    this.render();
  };
  void this.app.connect().then(() => {
    const caps = this.app.getHostCapabilities();
    this.canCall = Boolean(caps?.serverTools);
    this.canOpen = Boolean(caps?.openLinks);
    this.render();
  });
}

getHostCapabilities() is not a new round trip. Capabilities arrive in the host’s reply to ui/initialize, which is what connect() waits for. The getter reads that result.

Greet again calls the server tool from the view:

const result = await this.app.callServerTool({
  name: "greet",
  arguments: { name: this.name },
});
if (result.isError || !result.structuredContent) {
  throw new Error("The tool returned an error.");
}
this.data = result.structuredContent as Data;
this.note = "From callServerTool. ontoolresult did not run.";

callServerTool sends a tools/call JSON-RPC request to the host over postMessage. The host checks the serverTools capability, proxies the call to the MCP server, and returns the CallToolResult as the reply. That reply is what the await resolves to. It does not go through ontoolresult. If you watch the note under the buttons, it changes from “From the host, via ontoolresult.” to “From callServerTool. ontoolresult did not run.”

That is the detail this post exists to show. The host’s own tool call is a notification pushed into the view (ui/notifications/tool-result). The view’s own tool call is a request, and the result is the response to that request.

Open the spec never reaches the MCP server. It asks the host to open a URL:

const SPEC_URL =
  "https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx";

const result = await this.app.openLink({ url: SPEC_URL });
this.note = result.isError
  ? "The host refused to open the link."
  : "The host opened the spec.";

openLink sends a ui/open-link request. If the host granted openLinks, this test host runs window.open(url, "_blank", "noopener") and returns an empty result. A popup blocker can still stop the tab; the host has already accepted the request, so the note still says the host opened the spec.

Why an MCP Apps view has to ask: the sandboxed iframe

The view does not run in the host page. The host renders it inside an <iframe> with a sandbox attribute.

Adding sandbox to an iframe, with no value, applies every restriction at once. The framed page cannot run scripts, submit forms, open popups or new tabs, navigate the top-level page, or show modal dialogs such as alert(). It also loses its own origin. The browser gives it a unique opaque origin, so it can’t read its own cookies or localStorage, and it is treated as cross-origin to everything.

The value is a space-separated list of tokens. Each allow-* token lifts one restriction. These are the ones that matter most:

TokenWhat it allows
allow-scriptsRun JavaScript.
allow-same-originKeep the frame’s real origin, so cookies and storage work.
allow-formsSubmit forms.
allow-popupsOpen new windows or tabs with window.open or target="_blank".
allow-modalsShow alert(), confirm(), prompt() and print().
allow-top-navigationNavigate the top-level page.
allow-downloadsStart file downloads.

This host uses three of them:

iframe.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms");
  • allow-scripts lets the view’s JavaScript run.
  • allow-same-origin keeps the frame’s own origin, localhost:8081, so storage works. The host is on localhost:8080, a different origin, so the view still can’t touch the host page’s DOM or storage. Never combine allow-scripts and allow-same-origin on a frame that shares the parent’s origin, because its script could reach up and remove its own sandbox attribute.
  • allow-forms lets the view submit forms.

allow-popups and allow-top-navigation are left off, so the view can’t open a tab or redirect the page by itself. What it can still do is postMessage to its parent. That is the only channel, and it is why openLink and callServerTool are requests to the host, not things the view does directly. Part 3 covers the sandbox, the second iframe, and the CSP header in detail.

MCP Apps host capabilities are the security gate

The view can disable its buttons, but that is only the polite check. The host decides. In host/host.ts, the capabilities object is passed into AppBridge. It reads the page’s URL query string, so ?openLinks=0 leaves openLinks out, and ?serverTools=0 leaves serverTools out:

const caps = client.getServerCapabilities();
const query = new URLSearchParams(location.search);
const hostCapabilities = {
  ...(query.get("openLinks") === "0" ? {} : { openLinks: {} }),
  ...(query.get("serverTools") === "0" || !caps?.tools ? {} : { serverTools: caps.tools }),
};
bridge = new AppBridge(
  client,
  { name: "mcp-apps-test-host", version: "0.1.0" },
  hostCapabilities,
  { hostContext: { theme: theme(), platform: "web", displayMode: "inline" } },
);

serverTools gates the view calling tools through the host. It does not stop the host calling greet itself on load. Reload with ?serverTools=0 and you still see the first greeting; Greet again is disabled.

The host also enforces the gate if the view tries anyway. When serverTools is missing, this host replaces the AppBridge tool handler with one that throws "This host has not granted serverTools." When openLinks is missing, it never registers onopenlink, so a ui/open-link request is refused. Try http://localhost:8080/?serverTools=0 or http://localhost:8080/?openLinks=0. If the view does not reload itself, press Call on the host page.

With serverTools granted, the view can ask for any tool on its own server, but only that server. It can’t reach other MCP servers connected to the host. A tool can also declare who may call it, the model, the app or both, and a host should refuse an app call to a model-only tool. Real hosts can go further and confirm with the user, rate-limit, or allow only some tools. Treat serverTools as permission to ask, not a guarantee.

Two directions

The sequence below is the same page load you already saw in part 1, then the two new paths. Notice who starts tools/call, and how the result gets back to the view.

sequenceDiagram
    participant V as View (iframe)
    participant H as Host (AppBridge)
    participant S as MCP Server
    participant B as Browser

    rect rgb(230, 242, 255)
    Note over V,S: Host calls
    H->>S: tools/call greet
    V->>H: ui/initialize
    H-->>V: hostCapabilities (serverTools, openLinks)
    V->>H: ui/notifications/initialized
    H->>V: ui/notifications/tool-input
    S-->>H: CallToolResult
    H->>V: ui/notifications/tool-result
    Note over V,H: ontoolresult reads structuredContent
    end

    rect rgb(255, 243, 224)
    Note over V,S: View calls greet
    V->>H: tools/call greet
    Note over H: AppBridge checks serverTools
    H->>S: tools/call greet
    S-->>H: CallToolResult
    H-->>V: JSON-RPC reply
    Note over V,S: callServerTool promise resolves, ontoolresult does not run
    end

    rect rgb(232, 245, 233)
    Note over V,B: View calls openLink
    V->>H: ui/open-link
    Note over H: AppBridge checks openLinks
    H->>B: window.open
    H-->>V: empty result
    end

A few things are easy to miss.

The host can start its tools/call before the view has connected. It still waits for ui/notifications/initialized before sending ui/notifications/tool-input and ui/notifications/tool-result. That is the path that fires ontoolresult.

The view’s tools/call is a different message on the same channel. AppBridge receives it, checks serverTools, and only then forwards it to the MCP server. The JSON-RPC reply travels back along that request and resolves the promise inside callServerTool. This host does not also send ui/notifications/tool-result for that call, so ontoolresult stays quiet.

ui/open-link stops at the host. There is no server hop. The host checks openLinks and, if it agrees, opens the tab.

Next up

The view can now call a tool and ask the host to open a link, and the host can refuse either. What it cannot do is talk to the MCP server directly. Every message still goes through the host, and the view still runs in a sandboxed iframe on a different origin.

In part 3, we go inside that host: the sandbox iframe, the CSP header, and AppBridge.

The code for this post is in post-2-talks-back. Clone it, run it, then change it. That is the point of the series.