}`. Pages perform file operations through the server; they do not access the main application's source or Node APIs directly.
## Page API Reference
The current host implementation and pinned SDK types define the supported behavior. Register event handlers before `connect()`, then read `getHostCapabilities()` after connecting and enable features based on the result. The official API documentation covers the full SDK; the tables below describe what this host supports.
### Official MCP Apps API
| API / event | Purpose | ZCode behavior and usage notes |
| --------------------------------------------------------------- | -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `new App(info, capabilities, options)`, `connect()` | Create the page connection and complete the handshake | Create one App per live page; do not also access `window.zcode`, which can trigger another connection |
| `getHostVersion()`, `getHostCapabilities()`, `getHostContext()` | Read host information, capabilities, theme, locale, and display mode | Use after connecting; do not infer capabilities from the host version alone |
| `ontoolinput`, `ontoolresult`, `ontoolcancelled` | Receive complete input, results, and cancellation | Retain the initial result for UIs that load later so they do not miss the notification |
| `onhostcontextchanged` | Respond to theme, locale, size, or mode changes | Update presentation without repeating application operations |
| `callServerTool({ name, arguments }, options)` | Call a tool on the current plugin server | Uses the Agent's permissions and approvals; supports cancellation through `options.signal`; returns the actual `CallToolResult` |
| `readServerResource({ uri })` | Read resources from the current server | Returns MCP `contents`, with binary data as base64; does not grant access to other plugins or arbitrary local files |
| `listServerResources({ cursor })` | List server resources with pagination | For resource templates, use the `resources/templates/list` request in the next table |
| `sendMessage({ role: "user", content })` | Send a follow-up message to the main conversation | Requires the `message` capability; sends with a user gesture and enters confirmation without one |
| `updateModelContext({ content, structuredContent })` | Attach a selection or other context to the next turn | Requires `updateModelContext`; context is visible and removable in the composer, does not immediately send a message, and is not persistent storage |
| `createSamplingMessage(params, { signal })` | Call the current task's model from the App | Requires `sampling`; accepts text and images within supported limits and returns text; the App supplies conversation history |
| `registerTool(name, config, handler)` | Expose page tools for model calls | Register before the handshake and declare the App's `tools` capability; tools are registered/revoked with the live page and follow existing approvals |
| `onlisttools`, `oncalltool`, `sendToolListChanged()` | Manage the page tool catalogue manually | An alternative way to implement page tools; the callback's cancellation signal is `extra.mcpReq?.signal`; Showcase has a complete example |
| `requestDisplayMode({ mode })` | Request a change of display location | `inline` is inline and `fullscreen` uses the side panel; use the returned mode; `pip` currently keeps the existing mode |
| `sendSizeChanged({ height })` | Report content height | SDK automatic measurement is available; for manual measurement, measure the content container to avoid feeding viewport height back to the host |
| `openLink({ url })` | Open an external link through the host | Allows only `http:` / `https:` |
| `downloadFile({ contents })` | Open a native save dialog | Requires `downloadFile`; accepts embedded resources or resource links from the current server; cancellation or write failure returns `isError: true` |
| `sendLog({ level, data })` | Send observable page diagnostics | Keep debug logs out of a stdio server's stdout; do not log secrets or user content |
| `onteardown` | Release page listeners and other resources | Host teardown has a time limit; do not leave the only save operation until teardown |
| `requestTeardown()` | Ask the host to release the page | ZCode currently only logs the request; actual lifecycle follows the card/panel, so this is not a close button |
Sampling uses the task model selected when the request is accepted. It does not read the main conversation history; only history explicitly supplied by the App enters the request. Unsupported parameters such as `temperature`, `tools`, and native audio are rejected, and `includeContext` only supports `none`. Responses and cancellations should not automatically be appended as main conversation turns.
### ZCode Extensions and Low-Level MCP Requests
The `app.request()` calls below use the official App's low-level interface. Validate results with the corresponding schema from `@modelcontextprotocol/core`.
| Interface / field | Request or declaration | Scope |
| ----------------------------- | ------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Session view state | `ui/set-widget-state`, parameters `{ widgetState }`, result `EmptyResultSchema` | Check `experimental["zcode/widgetState"]` first; the initial value comes from the same key in hostContext. Stored in host memory only; can restore views within the session, with no guarantee across application restarts |
| Resource template list | `resources/templates/list`, result `ListResourceTemplatesResultSchema` | Lists the current server's MCP templates; do not assume the App has a `listServerResourceTemplates()` helper |
| Resource subscriptions | `resources/subscribe` / `resources/unsubscribe`, parameters `{ uri }`, result `EmptyResultSchema` | Check `experimental["zcode/resourceSubscribe"]` first; the server must also support subscriptions |
| Resource change notifications | `notifications/resources/updated` / `notifications/resources/list_changed` | Register handlers with `setNotificationHandler()` first; reread the resource when its URI is reported |
| Current side panel | `app.getHostCapabilities()?.experimental?.["zcode/surface"]` returns `{ id }` | Keep manifest `ui.surfaces[].id` aligned with tool `_meta.ui.surface` |
| CSP relaxation | `unsafeEval` and `wasmUnsafeEval` in resource `_meta["zcode/csp"]` | Check the support flags returned by `experimental["zcode/csp"]`; this does not grant file or network permissions |
### Existing `window.zcode` Pages
Existing compatibility pages can continue using these aliases. Prefer the official App for new pages, and use only one of the two connection approaches.
| Category | Available members |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| Connection and observation | `ready()`, `subscribe(listener)`; the latter returns an unsubscribe function |
| Input and host information | `toolInput`, `toolOutput`, `toolResponseMetadata`, `toolCancelled`, `hostInfo`, `hostCapabilities`, `hostContext`, `protocolVersion` |
| Display information | `theme`, `locale`, `displayMode`, `maxHeight`, `safeArea`, `userAgent` |
| Tools and resources | `callTool(name, args)`, `readResource(uri)`, `listResources()`, `listResourceTemplates()` |
| Resource subscriptions | `subscribeResource(uri)`, `unsubscribeResource(uri)`, `onResourceUpdated(listener)`, `onResourceListChanged(listener)` |
| Session view state | `widgetState`, `setWidgetState(state)` |
| Conversation collaboration | `sendFollowUpMessage({ prompt, structuredContent })`, `updateModelContext({ content, structuredContent })` |
| Display and files | `requestDisplayMode({ mode })`, `notifyIntrinsicHeight(height)`, `openExternal({ href })`, `downloadFile(contents)` |
The aliases do not provide sampling or page-tool helpers; use the official App for those capabilities. `openExternal` takes `href`, while the official `openLink` takes `url`; do not interchange these parameter names.
### Minimal Page Connection Example
Bundle this page code into the plugin HTML. It is not a script that can connect to the host from an ordinary browser tab.
```ts
import { App } from "@modelcontextprotocol/ext-apps";
import { EmptyResultSchema } from "@modelcontextprotocol/core";
const app = new App(
{ name: "my-panel", version: "0.1.0" },
{ availableDisplayModes: ["inline", "fullscreen"] },
);
let latestResult: unknown;
app.ontoolresult = (result) => {
latestResult = result.structuredContent;
document.querySelector("pre")!.textContent = JSON.stringify(latestResult);
};
function applyTheme() {
document.documentElement.dataset.theme = app.getHostContext()?.theme ?? "light";
}
app.onhostcontextchanged = applyTheme;
await app.connect();
applyTheme();
async function saveViewState(state: unknown) {
if (!app.getHostCapabilities()?.experimental?.["zcode/widgetState"]) return;
await app.request(
{ method: "ui/set-widget-state", params: { widgetState: state } },
EmptyResultSchema,
);
}
```
The page HTML must provide the `` element used in the example. Real components should consume any `latestResult` already received when they mount. This code only handles communication; document saving still goes through the plugin server.
## Platform, Data, and Capability Boundaries
| Data / capability | Where it belongs or how to use it |
| ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Application documents, cleanup plans, and scene revisions | Owned by the plugin server; write files or databases to the plugin data directory and apply application-specific confirmation and recovery rules |
| Input, scroll position, and pending requests in a live page | Retained when the same page moves between inline and side panel views; do not reconnect or resend requests |
| `widgetState` | A temporary UI snapshot; recreation, manual retry, and process restart have different semantics, so do not promise permanent storage |
| localStorage / IndexedDB | Browser storage under a stable origin can survive process restarts; isolated by plugin identity, workspace, and account. Clearing browser data does not clear plugin documents |
| Network, fonts, WASM, and scripts | Prefer bundling resources; external access is constrained by resource CSP. Pages have no Node or arbitrary filesystem access |
| Native permissions | camera / microphone / geolocation / clipboardWrite require resource declarations and host/system authorization; they are not available by default |
HTML resources currently have a **16 MiB** limit, and page resource reads have an **8 MiB** limit; split large pages into resources. Initial tool results also have limits: `structuredContent` 64 KiB, page metadata 16 KiB, and `content` 32 KiB. Oversized fields are omitted and marked; the page should reread complete data from the server.
**Not yet implemented:** full message-content extensions for image-only/resource-link messages, and bidirectional App tool progress (Showcase SC51/SC52). Existing text-with-image messages, resource reads, and model tool row progress do not establish full support for those capabilities.
See the [MCP Apps API](https://apps.extensions.modelcontextprotocol.io/api/) and [Quickstart](https://apps.extensions.modelcontextprotocol.io/api/documents/quickstart.html) for official SDK concepts and interfaces. Host behavior is determined by the current source covered by this guide and actual capability negotiation; this guide does not promise compatibility with a particular released version.
## Host Source Navigation
| Area to inspect | Current source entry point |
| ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Capability declarations | [buildPluginUiHostCapabilities.ts](packages/ui/src/plugin-ui/domain/buildPluginUiHostCapabilities.ts) |
| Session messages, context, and widgetState | [pluginUiInteractionPorts.ts](packages/ui/src/plugin-ui/app/pluginUiInteractionPorts.ts) |
| Tools, external links, and display modes | [pluginUiHostAppHandlers.ts](packages/ui/src/plugin-ui/app/pluginUiHostAppHandlers.ts) |
| Resource subscriptions | [pluginUiResourceSubscriptions.ts](packages/ui/src/plugin-ui/app/pluginUiResourceSubscriptions.ts) |
| Page retention, eviction, and restoration | [plugin-ui/CONTRACT.md](packages/ui/src/plugin-ui/CONTRACT.md) |
| HTML, resources, and the Host boundary | [plugin-ui-bridge/CONTRACT.md](packages/services/src/plugin-ui-bridge/CONTRACT.md) |
| Electron sandbox and browser storage | [pluginSandbox/CONTRACT.md](packages/desktop/src/main/pluginSandbox/CONTRACT.md) |
| API limits, sampling parameters, and alias types | [MCP Apps contract](packages/shared/src/mcp-apps/contract.ts), [sampling.ts](packages/shared/src/mcp-apps/sampling.ts), [aliasApi.ts](packages/desktop/src/renderer/src/plugin-sandbox/aliasApi.ts) |
| Desktop integration tests | [mcp-apps-host-e2e.mjs](packages/desktop/scripts/mcp-apps-host-e2e.mjs) |
The five plugins' application source lives in the separate `zcode-plugins` repository, which also provides a root `UI_PLUGIN.en.md`. This repository owns the host and does not copy plugin products into its tree. When host APIs change, update the capability and API tables in both repositories and both languages.