Articles · · 22 min read

MCP Apps From Scratch

AIPart 3

In part 2 of MCP Apps From Scratch, the view asked the host to do things for it. callServerTool asked the host to call a tool, openLink asked it to open a tab, and the host’s capabilities decided whether to say yes. The view had to ask because it runs in a sandboxed iframe, and postMessage to its parent is the only channel it has.

This post looks at that box from the inside. The view is a page of buttons that each try something the sandbox or the Content-Security-Policy (CSP) header should stop: open a tab, navigate the host page, read the host page, and fetch from an origin the server did not declare. One fetch is allowed, so you can see the difference. Every other button fails, and each one fails for a different reason.

The code is in post-3-inside-the-host, in the same mcp-apps-series repo. The shared test host in host/ is reused again, with one addition: ?log=1 shows the AppBridge traffic on the host page. If you are new to the series, part 1 sets up the server, the ui:// resource and the view.

Background: what the host actually does

In real life you never build any of the host code in this post. ChatGPT, Claude, VS Code or whichever chat app shows your MCP App is the host, and it does all of this for you:

  • Runs the sandbox. It loads a sandbox proxy page from a separate origin, and that page puts your view in a second, inner iframe.
  • Builds the CSP header. It reads _meta.ui.csp from your ui:// resource and turns those domain lists into a real Content-Security-Policy header, using its own template.
  • Runs AppBridge. It handles the postMessage traffic: initialising the view, sending tool input and results, and deciding whether to allow requests like callServerTool and openLink.

As an app developer you write only the MCP server, its ui:// resource with _meta.ui.csp, and the view. The small host in this repo copies what real hosts do so you can watch it happen. Each host follows the spec but uses its own sandbox setup and CSP template, so the same app can behave a little differently from one host to another.

Run it

You will need Node 20+ and npm.

git clone https://github.com/mdownes/mcp-apps-series.git
cd mcp-apps-series/post-3-inside-the-host
npm install
npm start

If you already cloned the repo for an earlier part, pull the latest main, cd into post-3-inside-the-host 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 inspect tool when the page loads.

As soon as the view loads, the This frame section shows where the view is running, and the CSP header section shows the policy it was given. The buttons under What the sandbox blocks and What the CSP header blocks don’t do anything until you press them. Each result line says Click to try., and a button runs only its own check, so the console only shows the error for the button you pressed.

The post 3 view in the test host, just after it loads: This frame and CSP header are filled in, and every result line says Click to try.
The view just after it loads. Nothing has been clicked yet.

The examples in this post use Chrome, and the error text quoted below is Chrome’s. Other browsers block the same things with different wording.

Two iframes, two origins

Part 2 said the view runs in a sandboxed iframe. That is true, but there are two of them. The host page on port 8080 loads a sandbox proxy from port 8081. The proxy then creates a second iframe and writes the view’s HTML into it.

The host sets the sandbox on the outer frame and points it at the proxy, passing the resource’s CSP along in the query string:

const sandboxUrl = `http://localhost:${Number(location.port) + 1}/sandbox.html`;
iframe.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms");
iframe.src = `${sandboxUrl}?csp=${encodeURIComponent(JSON.stringify(csp ?? {}))}`;

The proxy, host/sandbox.ts, does two jobs. When the host sends the view’s HTML, it writes it into the inner iframe. Every other message it relays, in both directions:

const HOST_ORIGIN = new URL(document.referrer).origin;
const inner = document.createElement("iframe");
inner.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms");
document.body.appendChild(inner);

window.addEventListener("message", (event) => {
  if (event.source === window.parent && event.origin === HOST_ORIGIN) {
    if (event.data?.method === "ui/notifications/sandbox-resource-ready") {
      const doc = inner.contentDocument!; // inherits this page's CSP
      doc.open();
      doc.write(event.data.params.html);
      doc.close();
    } else {
      inner.contentWindow?.postMessage(event.data, "*");
    }
  } else if (event.source === inner.contentWindow) {
    window.parent.postMessage(event.data, HOST_ORIGIN);
  }
});

The proxy only accepts host messages from its parent window on HOST_ORIGIN, and it only posts upward to HOST_ORIGIN. Messages from the view go up, messages from the host go down, and the view’s HTML never travels as a URL.

Why two frames? The outer frame gives the view a different origin from the host, and the proxy page is where the CSP header is applied. The view’s HTML arrives as a string inside a JSON-RPC message, not from a URL, so there is no response for a header to ride on. Writing it into a frame inside the proxy is how it picks up the proxy’s origin and the proxy’s header.

What the view can see

The This frame panel comes from one method, run when the element connects:

private readFrame() {
  this.origin = window.origin;
  // document.write keeps the writer's URL, so this is the proxy's path.
  this.url = window.location.pathname;
  this.parentIsTop = window.parent === window.top ? "yes" : "no";
  this.sandboxAttr = window.frameElement?.getAttribute("sandbox") ?? "(no frame element)";
  try {
    // The sandbox proxy is the parent, and it is the same origin as this view.
    this.proxyOrigin = window.parent.location.origin;
  } catch (err) {
    this.proxyOrigin = err instanceof Error ? `${err.name}: ${err.message}` : String(err);
  }
}

You should see:

  • Origin http://localhost:8081. The view shares the proxy’s origin, not the host’s.
  • Path /sandbox.html. The view has no URL of its own. A document written with document.write keeps the URL of the document that wrote it.
  • Parent is the top window: no. The parent is the proxy. The top window is the host page on port 8080.
  • Sandbox proxy http://localhost:8081. The view can read its parent’s location because they share an origin.
  • sandbox= allow-scripts allow-same-origin allow-forms. This is the inner frame’s attribute, read through window.frameElement. That also works only because the view and the proxy share an origin.

What the sandbox blocks

The first row of buttons tests the sandbox flags from part 2’s table. A click handler on the shadow root sends each button to its own probe and nothing else:

root.addEventListener("click", (event) => {
  const id = (event.target as HTMLElement).id;
  if (id === "open") this.openResult = tryOpen();
  else if (id === "navigate") this.navResult = tryNavigate();
  else if (id === "read") this.readResult = tryReadHost();
  else if (id === "allowed" || id === "blocked") {
    void this.runFetch(id);
    return;
  } else return;
  this.render();
});

Open a tab

function tryOpen(): string {
  const popup = window.open("https://example.org/", "_blank", "noopener,noreferrer");
  if (popup) {
    popup.close();
    return "Not blocked. window.open returned a window.";
  }
  return "Blocked. window.open returned null (no allow-popups).";
}

The result line says Blocked. window.open returned null (no allow-popups). The console says the request was made in a sandboxed frame whose allow-popups permission is not set.

This is the same restriction that made openLink necessary in part 2. The view cannot open a tab, so it asks the host, and the host checks openLinks and calls window.open from its own page, where no sandbox applies.

Navigate the host

function tryNavigate(): string {
  try {
    // location.assign() is not this check. Chrome refuses to read assign on a
    // cross-origin Location even when allow-top-navigation is set, and the host
    // does not navigate. Setting href is the navigation that flag gates.
    window.top!.location.href = "https://example.org/mcp-apps-sandbox-test";
    return "Not blocked. The view set window.top.location.";
  } catch (err) {
    return expectSecurityError(err, /navigate/, "No allow-top-navigation, so the view cannot navigate the host.");
  }
}

Setting window.top.location.href throws a SecurityError: Failed to set a named property ‘href’ on ‘Location’: The current window does not have permission to navigate the target frame. The result line says Blocked (SecurityError). No allow-top-navigation, so the view cannot navigate the host. The host page stays on port 8080.

The console also shows a message saying the frame attempting the navigation is sandboxed, and that neither allow-top-navigation nor allow-top-navigation-by-user-activation is set. That message is the browser’s own report of the blocked navigation, so it appears even though the code catches the exception.

The comment explains why the probe sets href rather than calling location.assign(). A cross-origin frame is allowed to set href on another window’s Location, so the only thing stopping it here is the sandbox. assign is not readable cross-origin, so calling it would fail for a different reason and would not test the sandbox flag.

Read the host page

function tryReadHost(): string {
  try {
    const title = window.top!.document.title;
    return `Not blocked. Host title is "${title}".`;
  } catch (err) {
    return expectSecurityError(err, /cross-origin/, "The host page is a different origin, so the view cannot read it.");
  }
}

Reading window.top.document throws a SecurityError: Blocked a frame with origin “http://localhost:8081” from accessing a cross-origin frame. The result line says Blocked (SecurityError). The host page is a different origin, so the view cannot read it.

This one does not add anything to the console. The try/catch catches the exception, and unlike the navigation, there is no separate browser report. The error is shown on the result line instead. That is expected, not a bug.

This block does not come from a sandbox flag. It comes from the second origin. The view has allow-same-origin, but that only keeps the origin it already has, localhost:8081, and the host is on localhost:8080. Part 2 warned against combining allow-scripts and allow-same-origin on a frame that shares its parent’s origin. The proxy on a different port is what makes that combination safe here.

All three probes share one helper. It only reports Blocked when the error is a SecurityError with the expected message, so a typo or a different failure shows up as Unexpected rather than passing quietly:

function expectSecurityError(err: unknown, pattern: RegExp, why: string): string {
  const name = err instanceof Error ? err.name : "Error";
  const message = err instanceof Error ? err.message : String(err);
  if (name === "SecurityError" && pattern.test(message)) return `Blocked (SecurityError). ${why}`;
  return `Unexpected ${name}: ${message}`;
}

What the CSP header blocks

The sandbox controls what the frame can do to the page around it. The CSP header controls where the view can load from and connect to. In MCP Apps, the server declares that list on the resource in _meta.ui.csp, and the host turns it into a header.

The server declares the origins

// connectDomains -> connect-src (fetch). resourceDomains -> script/style/img-src.
// localhost and 127.0.0.1 are different origins. Only localhost is listed,
// so a fetch to 127.0.0.1 is the one the header blocks.
const SERVER_ORIGIN = `http://localhost:${PORT}`;
const CONNECT_DOMAINS = [SERVER_ORIGIN];
const RESOURCE_DOMAINS = [SERVER_ORIGIN];
const ALLOWED_URL = `${SERVER_ORIGIN}/ping`;
const BLOCKED_URL = `http://127.0.0.1:${PORT}/ping`;

The resource carries them in its _meta:

// Read by the host, not by the view. serve.ts copies it onto sandbox.html.
_meta: {
  ui: {
    csp: {
      connectDomains: CONNECT_DOMAINS,
      resourceDomains: RESOURCE_DOMAINS,
    },
  },
},

The inspect tool returns the same values in structuredContent, so the view knows which URL is meant to work and which is meant to fail. The server also has a plain /ping route, and one process answers on both localhost and 127.0.0.1:

// Same process serves localhost and 127.0.0.1. CSP, not the server, decides
// which of those names the view is allowed to call.
app.get("/ping", (_req, res) => {
  res.json({ ok: true, from: "ping" });
});

The host builds the header

The host reads _meta.ui.csp from the resource and passes it to the proxy in the query string. host/serve.ts turns it into the header on sandbox.html:

const resources = clean(csp.resourceDomains);
const connect = clean(csp.connectDomains);
res.setHeader(
  "Content-Security-Policy",
  [
    "default-src 'self' 'unsafe-inline'",
    `script-src 'self' 'unsafe-inline' ${resources}`,
    `style-src 'self' 'unsafe-inline' ${resources}`,
    `img-src 'self' data: ${resources}`,
    `connect-src 'self' ${connect}`,
    "frame-src 'none'",
    "object-src 'none'",
    "base-uri 'none'",
  ].join("; "),
);

connectDomains ends up in connect-src, which covers fetch. resourceDomains ends up in script-src, style-src and img-src. clean drops any entry with a space, quote, semicolon or line break, so a domain cannot smuggle in an extra directive.

The inner iframe was written with document.write, so it inherits this header from the proxy. That is the comment // inherits this page's CSP in sandbox.ts.

The view reads the header

The CSP header panel fills in on load without any errors. The view fetches its parent’s URL, which is same-origin and allowed by 'self', and reads the header from the response:

const response = await fetch(window.parent.location.href);
const header = response.headers.get("content-security-policy") ?? "";
this.connectSrc = directive(header, "connect-src");
this.imgSrc = directive(header, "img-src");

You should see connect-src 'self' http://localhost:3001 and img-src 'self' data: http://localhost:3001, followed by the declared domains once the tool result arrives.

Fetch localhost:3001 and Fetch 127.0.0.1:3001

When the tool result arrives, ontoolresult only stores the two URLs. Each fetch waits for its own button:

// Register BEFORE connect() so a fast host cannot deliver the result first.
// The tool result only stores the URLs. A fetch waits for its own button.
this.app.ontoolresult = (result) => {
  const data = result.structuredContent;
  if (!isData(data)) {
    this.toolNote = "The tool result had no CSP urls.";
    this.render();
    return;
  }
  this.data = data;
  this.toolNote = "Tool result received, via ontoolresult.";
  this.render();
};

Fetch localhost:3001 shows Allowed. {“ok”:true,”from”:”ping”}. That origin is in connectDomains, and the server sends Access-Control-Allow-Origin: *, so the console stays quiet.

Fetch 127.0.0.1:3001 calls the same path on the same server, but 127.0.0.1 is not the origin the server declared. The result line says Blocked (connect-src). http://127.0.0.1:3001/ping, and the console says connecting to http://127.0.0.1:3001/ping violates connect-src 'self' http://localhost:3001. The request never leaves the browser.

A blocked fetch only rejects with a generic TypeError, which does not say why. To name the directive, probeFetch also listens for the securitypolicyviolation event the browser fires on the document:

try {
  const response = await fetch(url);
  const body = await response.text();
  cleanup();
  return `Allowed. ${body}`;
} catch (err) {
  const event = await Promise.race([
    violation,
    new Promise<undefined>((resolve) => setTimeout(() => resolve(undefined), 300)),
  ]);
  cleanup();
  if (event) return `Blocked (${event.effectiveDirective}). ${event.blockedURI}`;
  const message = err instanceof Error ? err.message : String(err);
  return `Failed. ${message}`;
}

If no violation arrives within 300 ms, the line says Failed. instead. That usually means the server is not running, not that CSP blocked the call.

MCP Apps security: sandbox, CSP and host capabilities

Part 2 showed host capabilities as the security gate. This post shows the two walls behind that gate:

  • The sandbox stops the view from acting on the page around it: no popups, no top-level navigation. The second origin stops it reading the host page.
  • The CSP header stops the view from loading or fetching from anywhere the server did not declare in _meta.ui.csp.
  • Host capabilities decide which requests the host will carry out for the view over postMessage, such as openLinks and serverTools.

A view that wants a new tab cannot open one, so it asks for openLink. A view that wants a tool result asks for callServerTool, and the host runs it over its own MCP connection after checking serverTools. A view that wants to call an API can do so directly, but only if the server listed that origin in connectDomains. If you are building an MCP App, _meta.ui.csp is where that list lives, and it should be as short as possible.

Watching AppBridge

Open http://localhost:8080/?log=1. A panel under the view lists the postMessage traffic. The host swaps in a logging transport only when the flag is set:

// ?log=1 wraps the transport so outgoing postMessage is listed too.
// The default path is the plain transport posts 1 and 2 already use.
const frame = iframe.contentWindow!;
const transport = logEnabled ? new LoggingTransport(frame, frame) : new PostMessageTransport(frame, frame);
await bridge.connect(transport);

On load you should see sandbox-proxy-ready, sandbox-resource-ready, ui/initialize, the initialize result, initialized, tool-input and tool-result. A size-changed line is the SDK reporting the view’s size. The two sandbox-* messages stay between the host and the proxy. Everything else is the view talking to AppBridge, relayed through the proxy.

sequenceDiagram
    participant H as Host page (8080)
    participant P as Sandbox proxy (8081)
    participant V as View (inner iframe)

    H->>P: load sandbox.html?csp=... (CSP header set)
    P->>H: ui/notifications/sandbox-proxy-ready
    H->>P: ui/notifications/sandbox-resource-ready (html)
    Note over P,V: document.write into the inner iframe
    V->>P: ui/initialize
    P->>H: relay
    H-->>P: initialize result
    P-->>V: relay
    V->>H: ui/notifications/initialized (via proxy)
    H->>V: ui/notifications/tool-input (via proxy)
    H->>V: ui/notifications/tool-result (via proxy)

Without the flag, the panel stays hidden and the host uses the plain PostMessageTransport, which is how parts 1 and 2 use it. DevTools on the host page also has a frame dropdown with the same three frames: the host, the sandbox proxy on port 8081, and the inner view.

Next up

The view now knows what box it is in: two iframes, a second origin, a sandbox with three flags, and a CSP header built from what the server declared. Everything it does outside that box goes through the host.

The next part is planned to look at theming and host context: how a view follows the host’s light or dark theme. The repo’s post-4-theming folder is a placeholder for now.

The code for this post is in post-3-inside-the-host. Clone it, run it, then change it. Add http://127.0.0.1:3001 to CONNECT_DOMAINS in server.ts, restart, and watch the second fetch line change. That is the point of the series.