Get Started

MCP Apps on the Stateless Protocol

An interactive result is still an MCP tool and resource exchange. The 2026-07-28 core makes that exchange self-contained, while the Apps extension adds the sandboxed browser surface.

75 minutesBuildPythonFree lesson

Learning Objectives

  • Advertise MCP Apps through server/discover and per-request extension capabilities.
  • Declare a ui:// resource on a tool before the tool is called.
  • Return complete tool and resource results on the 2026-07-28 stateless wire.
  • Separate the Apps ui/initialize bridge message from the removed MCP core handshake.
  • Apply origin validation, sandboxing, CSP, and least-privilege permissions.

The Problem

A text result can describe a timeline. It cannot give the user a timeline they can filter, inspect, or act on.

MCP Apps solves the presentation problem with an optional extension. A tool definition points to a ui:// resource. The host can fetch and review that resource before the tool runs, render it in a sandboxed iframe, and mediate all app actions through a JSON-RPC bridge.

The core protocol changed in 2026-07-28. Do not wrap an App in the old connection lifecycle:

  • There is no core initialize request or notifications/initialized notification.
  • There is no Mcp-Session-Id header.
  • Every request carries protocol version and client capabilities in params._meta.
  • A server implements server/discover so clients can inspect versions, core capabilities, and extensions.
  • Every successful result has a resultType discriminator.
  • Streamable HTTP uses one POST per request. Modern GET and DELETE entrypoints return 405.

The Apps bridge still has a method named ui/initialize. It belongs to the iframe postMessage dialect. It does not recreate a core MCP session.

The Concept

Two protocols, one feature

Keep the layers explicit:

  1. The MCP core carries server/discovertools/listtools/callresources/listand resources/read.
  2. The MCP Apps extension declares the UI and defines the iframe-to-host bridge.
  3. Browser sandbox rules limit what the UI can reach.

The extension identifier is io.modelcontextprotocol/ui. Both peers opt in. A client sends extension support inside the capabilities object on each request:

JSON
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "server/discover",
  "params": {
    "_meta": {
      "io.modelcontextprotocol/protocolVersion": "2026-07-28",
      "io.modelcontextprotocol/clientCapabilities": {
        "extensions": {
          "io.modelcontextprotocol/ui": {}
        }
      },
      "io.modelcontextprotocol/clientInfo": {
        "name": "timeline-host",
        "version": "1.0.0"
      }
    }
  }
}

clientInfo is recommended for diagnostics. It is self-reported data, not an authorization identity.

Discover before rendering

The server's discovery result advertises the extension:

JSON
{
  "resultType": "complete",
  "supportedVersions": ["2026-07-28"],
  "capabilities": {
    "tools": {},
    "resources": {},
    "extensions": {
      "io.modelcontextprotocol/ui": {}
    }
  },
  "ttlMs": 300000,
  "cacheScope": "public",
  "_meta": {
    "io.modelcontextprotocol/serverInfo": {
      "name": "timeline-app-server",
      "version": "2.0.0"
    }
  }
}

The server must support discovery. A client is not forced to call discovery before every action because each action carries its own capabilities.

Declare the UI on the tool definition

The modern Apps contract binds a UI to the tool in tools/list:

JSON
{
  "name": "notes_timeline",
  "description": "Render a timeline of notes.",
  "inputSchema": {
    "type": "object",
    "properties": {}
  },
  "_meta": {
    "ui": {
      "resourceUri": "ui://notes/timeline.html"
    }
  }
}

This is deliberately pre-call metadata. The host can preload, cache, and security-review the HTML before a result asks to display it. Older flat metadata keys may be accepted by compatibility code, but new servers should emit the nested _meta.ui.resourceUri form.

tools/list is cacheable in the current core. Include deterministic ordering, ttlMsand cacheScope. Use private when the visible tools vary by user or token.

Return data, then let the host bind the view

The tool call returns ordinary content plus structured data:

JSON
{
  "resultType": "complete",
  "content": [
    {"type": "text", "text": "Timeline ready."}
  ],
  "structuredContent": {
    "notes": [
      {"id": "note-1", "title": "Discover", "created": "2026-07-28"}
    ]
  },
  "isError": false
}

The host already knows which view belongs to the tool. Avoid inventing a new content block just to repeat the URI.

Serve the app as a resource

The server advertises resources in discovery, so it also implements the mandatory resources/list operation. Its deterministic list entry includes the canonical URI, a stable name, description, and MIME type. The list result includes resultTypeserver identity metadata, ttlMsand cacheScopejust like the deterministic tool list.

The host sends resources/read. On Streamable HTTP, the request has:

Text
POST /mcp
MCP-Protocol-Version: 2026-07-28
Mcp-Method: resources/read
Mcp-Name: ui://notes/timeline.html

The header values and JSON-RPC body must match. A mismatch is protocol error -32020.

The result contains the HTML resource and cache hints:

JSON
{
  "resultType": "complete",
  "contents": [
    {
      "uri": "ui://notes/timeline.html",
      "mimeType": "text/html;profile=mcp-app",
      "text": "<!doctype html>...",
      "_meta": {
        "ui": {
          "csp": {
            "connectDomains": [],
            "resourceDomains": [],
            "frameDomains": [],
            "baseUriDomains": []
          },
          "permissions": {}
        }
      }
    }
  ],
  "ttlMs": 60000,
  "cacheScope": "public"
}

Cache UI resources as executable content

An App resource is not interchangeable with ordinary prose. Its cache entry can execute bridge code, render tool data, and request host-mediated actions. Key it by canonical ui:// URI, admitted server identity and version, resource content digest, and authorization context when cacheScope is private. Never reuse a private App resource across principals because the HTML or its policy metadata may differ even when the URI is identical.

Invalidate the entry when its ttlMs expires, the tool's _meta.ui.resourceUri binding changes, the server version or admitted descriptor pin changes, or an acknowledged resource-change subscription names the URI. Refetch and reapply CSP and permission review before remounting. A stale iframe must not keep broader permissions merely because a new resource version has not loaded yet.

Reject wire ambiguity before feature policy

Validation has a deliberate order. First validate the JSON-RPC shape and require string protocol metadata plus an object client capability map. Next compare routing headers with the body. Only then decide whether the matched protocol version is supported. This order prevents a proxy and server from interpreting different requests.

ConditionHTTPJSON-RPC error
Header and body version, method, or name disagree400-32020
Header and body agree on an unsupported version400-32022with data exactly {"supported":["2026-07-28"],"requested":"<actual>"}
resources/read lacks the Apps extension capability400-32021with data.requiredCapabilities.extensions.io.modelcontextprotocol/ui
Method is unknown404-32601

A JSON-RPC notification has no idso the server never emits a JSON-RPC response for it. An accepted HTTP notification returns 202 with an empty body. An error can change the HTTP status, but it still cannot create a JSON-RPC error body for a notification.

The sandbox is a boundary, not a trust verdict

A host controls the iframe. The App cannot directly read host cookies, local storage, or page DOM. All privileged work must cross the bridge.

Use these defaults:

  • Leave all CSP domain lists empty, then add only the origins the App needs. Use connectDomains for fetch, XHR, and WebSocket; use resourceDomains for scripts, styles, images, and fonts.
  • Bundle code and data when practical.
  • Request no camera, microphone, or location permission unless a visible feature needs it.
  • Pin postMessage to the exact peer origin and reject events from every other origin.
  • Treat tool arguments, tool results, resource text, and bridge messages as untrusted input.
  • Keep user consent in the host. The iframe cannot approve its own consequential action.

Do not copy a fixed sandbox attribute from a tutorial into every host. The host must choose flags based on the App's origin model and its own isolation design.

An allowed domain is still an exfiltration path. connectDomains: ["https://api.example.com"] means any script that executes inside the App can send permitted data there. Exact origin matching prevents destination confusion, but it does not decide whether the payload is appropriate. Keep connect access empty by default, avoid placing bearer tokens in the iframe, proxy narrow operations through the host when practical, limit response and request sizes, and audit which user action caused each outbound request. Treat resourceDomains separately from connectDomains; permission to load a font or script should not grant arbitrary data upload.

The Apps bridge has its own lifecycle

The Apps bridge is a JSON-RPC dialect over postMessage. It can exchange ui/initialize and ui/* notifications and can proxy core-looking methods such as tools/call.

The View sends ui/initialize with appInfo and an appCapabilities object. The host returns its capabilities and host context. Only after that response does the View send ui/notifications/initialized. The host must wait for this Apps notification before sending messages to the View.

That local handshake creates a bridge between one iframe and one host frame. It does not negotiate the MCP protocol version, create server state, or mint a transport session. Notice the exact prefix: core notifications/initialized was removed, while Apps ui/notifications/initialized remains. A core request generated by a bridged tool call is a new self-contained request with a new JSON-RPC id and full request metadata.

Host context, actions, and revocation

The host remains the authority after bridge initialization. A View can request a tool action, navigation, clipboard use, or another privileged effect only through a capability the host advertised. The host validates the typed request, current user, target, and arguments, applies approval policy, and may refuse it. A button click and a valid bridge message express intent; neither grants authority.

Treat theme, size, and accessibility as changing host context rather than one-time render inputs:

  • Apply host-provided color and typography tokens, then react when theme or contrast preference changes.
  • Let the View report desired dimensions, but let the host cap and apply iframe size so content cannot escape its layout or create deceptive overlays.
  • Preserve keyboard order, visible focus, accessible names, screen-reader status, sufficient contrast, zoom, and reduced-motion behavior inside the iframe.
  • Re-test focus transfer between host controls and View controls after resize and rerender.

Capabilities can be revoked while the App is open because the user changes account, policy changes, a server is quarantined, or the host narrows consent. Check capability and authorization at action time, not only during ui/initialize. On revocation, reject pending privileged calls, stop network activity that no longer fits policy, clear sensitive rendered state, and remount or fall back to text when the UI resource itself is no longer admitted. A View must handle refusal as a normal result, not retry until the host gives in.

Fallback is part of the contract

An Apps-aware server can still serve hosts that do not advertise the UI extension:

  • Return the same tool without _meta.ui in tools/list.
  • Keep a useful text result for tools/call.
  • Refuse resources/read for the UI with a missing-capability error.
  • Never assume an iframe exists when deciding whether the tool completed.

Build It

code/main.py builds a small in-process protocol model without an SDK. It validates the current request envelope and Streamable HTTP routing values, advertises Apps through server/discoverlists tools and resources, executes the tool, and serves a self-contained HTML resource.

The model receives already parsed bodies and routing headers. It is not a complete HTTP adapter and does not parse Content-Type or Accept. Use Lesson 09 for the full Streamable HTTP adapter that requires Content-Type: application/json and an Accept value containing both application/json and text/event-stream.

Run it:

Terminal
cd phases/13-tools-and-protocols/14-mcp-apps
python3 code/main.py
python3 -m unittest discover code/tests -v

Inspect four things in the output:

  1. Every call is independent.
  2. Every request has _meta capabilities.
  3. resources/list returns a stable descriptor before any resource read.
  4. Every result has resultType and server identity metadata.
  5. No core session identifier appears.

Use It

Start with server/discover. Confirm io.modelcontextprotocol/ui appears in the server extension map. Then call tools/list twice, once with Apps capability and once without it. The first response declares the resource. The second remains a usable text-only tool.

Read ui://notes/timeline.html. Search the HTML for hostOrigin and the event.origin guard. Those two lines are the minimum visible proof that the bridge does not use a wildcard target.

Ship It

This lesson ships outputs/skill-mcp-apps-spec.md. Use it to review an App contract before writing framework code. It forces the author to state the current core envelope, extension negotiation, fallback, UI resource, cache policy, CSP, permissions, bridge methods, and consent boundary.

Exercises

  1. Change the client capability to an empty extension map. Confirm tools/list keeps the tool but removes the UI binding.
  2. Send Mcp-Name: ui://notes/other.html with a body that reads the timeline. Confirm error -32020.
  3. Change the resource to cacheScope: private. Describe the user-specific condition that justifies it.
  4. Move the script to https://static.example.com/app.js. Add that origin to resourceDomains and explain the new supply-chain risk.
  5. Add an notes_open tool and route the button click through the host. Keep user approval in the host.

Key Terms

TermMeaning
MCP AppsOptional extension for interactive HTML rendered by an MCP host
io.modelcontextprotocol/uiExtension identifier advertised by both peers
ui://Resource scheme for an App's UI template
text/html;profile=mcp-appMIME type for MCP App HTML
server/discoverCurrent RPC for protocol and capability discovery
resources/listMandatory resource listing method when the server advertises resources
resultTypeRequired discriminator for modern successful results
ui/initializeFirst Apps bridge request, separate from removed core initialization
ui/notifications/initializedApps View readiness notification sent after the host responds
CSPBrowser policy that restricts scripts, styles, images, and network origins
Text fallbackTool behavior retained for a host without Apps support

Further Reading

Check what you learned

6 questions. Answer each one to see why.

Question 1 of 60 correct

Where should a modern MCP App bind its UI resource to a tool?

The full code

Every file for this lesson. Copy it, run it, then change it.

main.py
"""Phase 13 Lesson 14: MCP Apps on the MCP 2026-07-28 wire.
Lesson: phases/13-tools-and-protocols/14-mcp-apps/docs/en.md
Spec: https://modelcontextprotocol.io/specification/2026-07-28
Models discovery, tools, resources, and a self-contained MCP Apps UI.
Lesson 09 owns the HTTP adapter; the UI pins its postMessage origin.
"""

from __future__ import annotations

import html
import json
from dataclasses import dataclass
from typing import Any


PROTOCOL_VERSION = "2026-07-28"
APPS_EXTENSION = "io.modelcontextprotocol/ui"
PROTOCOL_META = "io.modelcontextprotocol/protocolVersion"
CLIENT_CAPABILITIES_META = "io.modelcontextprotocol/clientCapabilities"
CLIENT_INFO_META = "io.modelcontextprotocol/clientInfo"
SERVER_INFO_META = "io.modelcontextprotocol/serverInfo"
SERVER_INFO = {"name": "timeline-app-server", "version": "2.0.0"}
RESOURCE_URI = "ui://notes/timeline.html"
RESOURCE_MIME = "text/html;profile=mcp-app"
HOST_ORIGIN = "https://host.example"

NOTES = [
    {"id": "note-1", "title": "Discover", "created": "2026-07-28"},
    {"id": "note-2", "title": "Per-request metadata", "created": "2026-07-29"},
    {"id": "note-3", "title": "MCP Apps", "created": "2026-07-30"},
]

APP_CSP = {
    "connectDomains": [],
    "resourceDomains": [],
    "frameDomains": [],
    "baseUriDomains": [],
}


@dataclass(frozen=True)
class ProtocolError(Exception):
    code: int
    message: str
    data: dict[str, Any] | None = None


def request_meta(*, apps: bool = True) -> dict[str, Any]:
    extensions = {APPS_EXTENSION: {}} if apps else {}
    return {
        PROTOCOL_META: PROTOCOL_VERSION,
        CLIENT_CAPABILITIES_META: {"extensions": extensions},
        CLIENT_INFO_META: {"name": "lesson-client", "version": "1.0.0"},
    }


def make_request(
    method: str,
    request_id: int,
    params: dict[str, Any] | None = None,
    *,
    apps: bool = True,
) -> tuple[dict[str, Any], dict[str, str]]:
    body_params = dict(params or {})
    body_params["_meta"] = request_meta(apps=apps)
    body = {"jsonrpc": "2.0", "id": request_id, "method": method, "params": body_params}
    headers = {"MCP-Protocol-Version": PROTOCOL_VERSION, "Mcp-Method": method}
    if method in {"tools/call", "resources/read", "prompts/get"}:
        headers["Mcp-Name"] = str(body_params.get("name") or body_params.get("uri") or "")
    return body, headers


def timeline_html(notes: list[dict[str, str]]) -> str:
    items = "".join(
        "<li><button data-note='{}'>{}</button><time>{}</time></li>".format(
            html.escape(note["id"]),
            html.escape(note["title"]),
            html.escape(note["created"]),
        )
        for note in notes
    )
    return f"""<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>Notes timeline</title>
<style>body{{font:16px system-ui;margin:1rem}}li{{display:flex;gap:1rem;margin:.5rem}}</style>
</head><body><h1>Notes timeline</h1><ol>{items}</ol>
<script>
const hostOrigin = {json.dumps(HOST_ORIGIN)};
let nextId = 0;
function callTool(name, args) {{
  const id = ++nextId;
  window.parent.postMessage({{
    jsonrpc: "2.0", id, method: "tools/call",
    params: {{name, arguments: args}}
  }}, hostOrigin);
}}
window.addEventListener("message", (event) => {{
  if (event.origin !== hostOrigin || !event.data || event.data.jsonrpc !== "2.0") return;
  if (event.data.id === 0 && event.data.result) {{
    document.body.dataset.bridgeReady = "true";
    window.parent.postMessage({{
      jsonrpc: "2.0", method: "ui/notifications/initialized"
    }}, hostOrigin);
  }}
}});
document.querySelectorAll("button").forEach((button) => {{
  button.addEventListener("click", () => callTool("notes_open", {{id: button.dataset.note}}));
}});
// ui/initialize belongs to the Apps postMessage dialect, not MCP core initialization.
window.parent.postMessage({{
  jsonrpc: "2.0", id: 0, method: "ui/initialize",
  params: {{
    appInfo: {{name: "notes-timeline", version: "1.0.0"}},
    appCapabilities: {{}}
  }}
}}, hostOrigin);
</script></body></html>"""


class McpAppServer:
    def _validate(self, body: dict[str, Any], headers: dict[str, str]) -> dict[str, Any]:
        if body.get("jsonrpc") != "2.0":
            raise ProtocolError(-32600, "Invalid Request")
        method = body.get("method")
        params = body.get("params")
        if not isinstance(method, str) or not isinstance(params, dict):
            raise ProtocolError(-32600, "Invalid Request")
        meta = params.get("_meta")
        if not isinstance(meta, dict):
            raise ProtocolError(-32602, "request params._meta is required")
        requested_version = meta.get(PROTOCOL_META)
        if not isinstance(requested_version, str):
            raise ProtocolError(-32602, "protocolVersion must be a string")
        if not isinstance(meta.get(CLIENT_CAPABILITIES_META), dict):
            raise ProtocolError(-32602, "clientCapabilities is required on every request")
        if headers.get("MCP-Protocol-Version") != requested_version:
            raise ProtocolError(-32020, "MCP-Protocol-Version header does not match body")
        if headers.get("Mcp-Method") != method:
            raise ProtocolError(-32020, "Mcp-Method header does not match body")
        expected_name = params.get("name") or params.get("uri")
        if method in {"tools/call", "resources/read", "prompts/get"}:
            if headers.get("Mcp-Name") != expected_name:
                raise ProtocolError(-32020, "Mcp-Name header does not match body")
        if requested_version != PROTOCOL_VERSION:
            raise ProtocolError(
                -32022,
                "Unsupported protocol version",
                {"supported": [PROTOCOL_VERSION], "requested": requested_version},
            )
        return meta

    @staticmethod
    def _apps_enabled(meta: dict[str, Any]) -> bool:
        caps = meta[CLIENT_CAPABILITIES_META]
        extensions = caps.get("extensions", {})
        return (
            isinstance(extensions, dict)
            and isinstance(extensions.get(APPS_EXTENSION), dict)
        )

    @staticmethod
    def _success(request_id: Any, result: dict[str, Any]) -> dict[str, Any]:
        result = dict(result)
        result.setdefault("resultType", "complete")
        result.setdefault("_meta", {})[SERVER_INFO_META] = SERVER_INFO
        return {"jsonrpc": "2.0", "id": request_id, "result": result}

    @staticmethod
    def _error(request_id: Any, error: ProtocolError) -> dict[str, Any]:
        payload: dict[str, Any] = {"code": error.code, "message": error.message}
        if error.data is not None:
            payload["data"] = error.data
        return {"jsonrpc": "2.0", "id": request_id, "error": payload}

    @staticmethod
    def _error_status(error: ProtocolError) -> int:
        return 404 if error.code == -32601 else 400

    def handle(
        self,
        body: dict[str, Any],
        headers: dict[str, str],
        *,
        http_method: str = "POST",
    ) -> tuple[int, dict[str, Any] | None]:
        if http_method != "POST":
            return 405, None
        is_notification = "id" not in body
        try:
            meta = self._validate(body, headers)
            method = body["method"]
            params = body["params"]
            if method == "server/discover":
                result = {
                    "supportedVersions": [PROTOCOL_VERSION],
                    "capabilities": {
                        "tools": {},
                        "resources": {},
                        "extensions": {APPS_EXTENSION: {}},
                    },
                    "ttlMs": 300_000,
                    "cacheScope": "public",
                }
            elif method == "tools/list":
                tool: dict[str, Any] = {
                    "name": "notes_timeline",
                    "description": "Render a timeline of notes.",
                    "inputSchema": {"type": "object", "properties": {}},
                }
                if self._apps_enabled(meta):
                    tool["_meta"] = {"ui": {"resourceUri": RESOURCE_URI}}
                result = {"tools": [tool], "ttlMs": 60_000, "cacheScope": "public"}
            elif method == "tools/call":
                if params.get("name") != "notes_timeline":
                    raise ProtocolError(-32602, "Unknown tool")
                result = {
                    "content": [{"type": "text", "text": "Timeline ready."}],
                    "structuredContent": {"notes": NOTES},
                    "isError": False,
                }
            elif method == "resources/list":
                result = {
                    "resources": [{
                        "uri": RESOURCE_URI,
                        "name": "notes-timeline",
                        "description": "Interactive notes timeline for MCP Apps hosts.",
                        "mimeType": RESOURCE_MIME,
                    }],
                    "ttlMs": 60_000,
                    "cacheScope": "public",
                }
            elif method == "resources/read":
                if params.get("uri") != RESOURCE_URI:
                    raise ProtocolError(-32602, "Unknown resource URI")
                if not self._apps_enabled(meta):
                    raise ProtocolError(
                        -32021,
                        "MCP Apps client capability is required",
                        {
                            "requiredCapabilities": {
                                "extensions": {APPS_EXTENSION: {}}
                            }
                        },
                    )
                result = {
                    "contents": [{
                        "uri": RESOURCE_URI,
                        "mimeType": RESOURCE_MIME,
                        "text": timeline_html(NOTES),
                        "_meta": {"ui": {"csp": APP_CSP, "permissions": {}}},
                    }],
                    "ttlMs": 60_000,
                    "cacheScope": "public",
                }
            else:
                raise ProtocolError(-32601, "Method not found")
            if is_notification:
                return 202, None
            return 200, self._success(body["id"], result)
        except ProtocolError as error:
            if is_notification:
                return self._error_status(error), None
            return self._error_status(error), self._error(body.get("id"), error)


def demo() -> None:
    server = McpAppServer()
    for request_id, (method, params) in enumerate(
        [
            ("server/discover", {}),
            ("tools/list", {}),
            ("tools/call", {"name": "notes_timeline", "arguments": {}}),
            ("resources/read", {"uri": RESOURCE_URI}),
        ],
        start=1,
    ):
        body, headers = make_request(method, request_id, params)
        status, response = server.handle(body, headers)
        summary = response.get("result", response.get("error"))
        print(f"{status} {method}: {json.dumps(summary)[:220]}")


if __name__ == "__main__":
    demo()