Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,9 @@ jobs:
- run: npm run test:dependency-isolation

e2e:
runs-on: ubuntu-latest
# Pinned: the Playwright version in package.json cannot install its
# browser on ubuntu-26.04, which ubuntu-latest now resolves to.
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v6

Expand Down
3 changes: 2 additions & 1 deletion .github/workflows/update-snapshots.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ jobs:
(github.event.issue.pull_request &&
contains(github.event.comment.body, '/update-snapshots') &&
contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.comment.author_association))
runs-on: ubuntu-latest
# Pinned to the same image as the e2e job in ci.yml
runs-on: ubuntu-24.04
steps:
- name: Get PR branch
if: github.event_name == 'issue_comment'
Expand Down
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ rm -fR package-lock.json node_modules && \
- `src/server/index.ts` - Helpers for MCP servers to register tools/resources with UI metadata
- `src/types.ts` - Protocol types re-exported from `spec.types.ts` and Zod schemas from `generated/schema.ts` (auto-generated during build)
- `src/message-transport.ts` - `PostMessageTransport` for iframe communication
- `src/react/` - React hooks: `useApp`, `useHostStyles`, `useAutoResize`, `useDocumentTheme`
- `src/react/` - React hooks: `useApp`, `useHostStyles`, `useAutoResize`, `useDocumentTheme`, `useViewState`

### Protocol Flow

Expand Down
32 changes: 28 additions & 4 deletions docs/migrate_from_openai_apps.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,10 +275,34 @@ Client-side migration involves replacing the implicit `window.openai` global wit

### State Persistence

| OpenAI | MCP Apps | Notes |
| ------------------------------------- | -------- | -------------------------------------------------------------------- |
| `window.openai.widgetState` | — | Not directly available in MCP |
| `window.openai.setWidgetState(state)` | — | Use alternative mechanisms (`localStorage`, server-side state, etc.) |
OpenAI's widget state is one snapshot that can carry UI-only state (`privateContent`), state for the model (`modelContent`) and file ids (`imageIds`). MCP Apps has a separate request for each purpose:

| OpenAI | MCP Apps | Notes |
| -------------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `window.openai.widgetState` | `app.getHostContext()?.viewState` | Read it after `connect()`. `null` means nothing is saved |
| `window.openai.setWidgetState(state)`, or its `privateContent` | `await app.setViewState(state)` | Kept by the host for this View instance and never shown to the model. Needs host support: check `app.getHostCapabilities()?.viewState`, and otherwise fall back to `localStorage` or server-side state |
| `setWidgetState({ modelContent })` | `await app.updateModelContext({ content })` | The host does not hand model context back to the View: also keep a copy in the view state if you need it after a reload |
| `setWidgetState({ imageIds })` | — | Not yet implemented (see File Operations) |

```typescript
// Before (OpenAI)
window.openai.setWidgetState({
modelContent: "Selected: M6 hex bolt",
privateContent: { tab: "details" },
});
const saved = window.openai.widgetState?.privateContent;

// After (MCP Apps)
if (app.getHostCapabilities()?.viewState) {
await app.setViewState({ version: 1, tab: "details" });
}
await app.updateModelContext({
content: [{ type: "text", text: "Selected: M6 hex bolt" }],
});
const saved = app.getHostContext()?.viewState; // after connect()
```

In React, {@link @modelcontextprotocol/ext-apps/react!useViewState `useViewState`} wraps the restore and the debounced save. See [Persisting view state](./patterns.md#persisting-view-state) for the full pattern and its fallback.

### File Operations (Not Yet in MCP Apps)

Expand Down
80 changes: 78 additions & 2 deletions docs/patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,73 @@ await app.sendMessage({

## Persisting view state

For recoverable view state (e.g., current page in a PDF viewer, camera position in a map), use [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) with a stable identifier provided by the server.
A View loses what it holds in memory whenever its iframe is destroyed: on a page reload, when the conversation is reopened, or when the host unmounts it. The host re-sends the tool input and result, but not what the user did afterwards.

For recoverable view state (e.g., current page in a PDF viewer, camera position in a map), ask the host to keep it with {@link app!App.setViewState `setViewState`}. The host stores it for this View instance (the View it renders for one tool call) and hands it back as `viewState` in {@link app!App.getHostContext `getHostContext()`} the next time it renders that View:

<!-- prettier-ignore -->
```ts source="./patterns.tsx#persistViewState"
await app.connect();

// Restore: the host hands back what this view last saved, or null
const saved = app.getHostContext()?.viewState;
if (saved?.version === 1 && typeof saved.currentPage === "number") {
showPage(saved.currentPage);
}

// Save as the user changes things, debounced. Each save replaces the last.
let saveTimer: ReturnType<typeof setTimeout> | undefined;
function saveState(state: { currentPage: number }) {
if (!app.getHostCapabilities()?.viewState) return; // see the fallback below
clearTimeout(saveTimer);
saveTimer = setTimeout(() => {
app.setViewState({ version: 1, ...state }).catch((err) => {
console.error("Failed to save view state:", err);
});
}, 500);
}

// e.g., saveState({ currentPage: 5 });
```

- Each save replaces the saved state as a whole, and `null` clears it.
- Save as changes happen, debounced: a View can be destroyed without warning.
- Version the state. An older build of your View may have written it.
- The host shows the state neither to the model nor to your server. To tell the model what the user is looking at, use {@link app!App.updateModelContext `updateModelContext`} as well.

**React**: {@link @modelcontextprotocol/ext-apps/react!useViewState `useViewState`} does the restore and the debounced save. Use one such hook per View, with all the state to save in one object, because each save replaces the last. On a host that cannot save view state it behaves like plain `useState`:

<!-- prettier-ignore -->
```tsx source="./patterns.tsx#persistViewStateReact"
type ViewerState = { version: 1; currentPage: number };
const INITIAL_STATE: ViewerState = { version: 1, currentPage: 1 };

function PdfViewer() {
const { app } = useApp({
appInfo: { name: "PDF Viewer", version: "1.0.0" },
capabilities: {},
});

// Like useState, but restored from the host and saved back (debounced)
const [saved, setState] = useViewState<ViewerState>(app, INITIAL_STATE);
// The saved state may come from an older version of this View
const state = saved.version === 1 ? saved : INITIAL_STATE;

return (
<button
onClick={() =>
setState({ ...state, currentPage: state.currentPage + 1 })
}
>
Page {state.currentPage}
</button>
);
}
```

### Fallback: `localStorage` with a server-provided key

Not every host can save view state: check `app.getHostCapabilities()?.viewState`. Where it is missing, fall back to [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) with a stable identifier provided by the server.

**Server-side**: Tool handler generates a unique `viewUUID` and returns it in `CallToolResult._meta.viewUUID`:

Expand Down Expand Up @@ -564,10 +630,20 @@ app.ontoolresult = (result) => {
// e.g., saveState({ currentPage: 5 });
```

Compared with `setViewState`, this fallback asks more of you and promises less:

| | `setViewState` | `viewUUID` + `localStorage` |
| -------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Storage key | Derived by the host | Your server makes a `viewUUID` and returns it in every tool result |
| Available | Right after `connect()` | Only once the tool result arrives |
| Where it lives | With the host, which may let it follow the user to another device | In one browser, under the sandbox origin that the host assigned, if that origin allows storage and stays the same |
| Cleanup | Deleted with the conversation | Never |
| Needs | A host that advertises `viewState` | Nothing from the host |

For state that represents user effort (e.g., saved bookmarks, annotations, custom configurations), consider persisting it server-side using [app-only tools](#tools-that-are-private-to-apps) instead. Pass the `viewUUID` to the app-only tool to scope the saved data to that view instance.

> [!NOTE]
> For full examples using `localStorage`, see: [`examples/pdf-server/`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/pdf-server) (persists current page) and [`examples/map-server/`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/map-server) (persists camera position).
> For full examples that use `setViewState` with the `localStorage` fallback, see: [`examples/pdf-server/`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/pdf-server) (persists current page) and [`examples/map-server/`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/map-server) (persists camera position). For `useViewState`, see [`examples/basic-server-react/`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-server-react).

## Pausing computation-heavy views when offscreen

Expand Down
69 changes: 67 additions & 2 deletions docs/patterns.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import type {
} from "@modelcontextprotocol/server";
import type { McpUiHostContext } from "../src/types.js";
import { useEffect, useState } from "react";
import { useApp } from "../src/react/index.js";
import { useApp, useViewState } from "../src/react/index.js";
import { registerAppTool } from "../src/server/index.js";
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/server";
import { z } from "zod";
Expand Down Expand Up @@ -371,7 +371,72 @@ function persistViewStateServer(url: string, title: string, pageCount: number) {
}

/**
* Example: Persisting view state (client-side)
* Example: Persisting view state with the host (vanilla JS)
*/
async function persistViewStateWithHost(
Comment thread
ochafik marked this conversation as resolved.
Resolved
app: App,
showPage: (page: number) => void,
) {
//#region persistViewState
await app.connect();

// Restore: the host hands back what this view last saved, or null
const saved = app.getHostContext()?.viewState;
if (saved?.version === 1 && typeof saved.currentPage === "number") {
showPage(saved.currentPage);
}

// Save as the user changes things, debounced. Each save replaces the last.
let saveTimer: ReturnType<typeof setTimeout> | undefined;
function saveState(state: { currentPage: number }) {
if (!app.getHostCapabilities()?.viewState) return; // see the fallback below
clearTimeout(saveTimer);
saveTimer = setTimeout(() => {
app.setViewState({ version: 1, ...state }).catch((err) => {
console.error("Failed to save view state:", err);
});
}, 500);
}

// e.g., saveState({ currentPage: 5 });
//#endregion persistViewState
void saveState;
}

/**
* Example: Persisting view state with the host (React)
*/
function PersistViewStateReact() {
Comment thread
ochafik marked this conversation as resolved.
Resolved
//#region persistViewStateReact
type ViewerState = { version: 1; currentPage: number };
const INITIAL_STATE: ViewerState = { version: 1, currentPage: 1 };

function PdfViewer() {
Comment thread
ochafik marked this conversation as resolved.
Resolved
const { app } = useApp({
appInfo: { name: "PDF Viewer", version: "1.0.0" },
capabilities: {},
});

// Like useState, but restored from the host and saved back (debounced)
const [saved, setState] = useViewState<ViewerState>(app, INITIAL_STATE);
// The saved state may come from an older version of this View
const state = saved.version === 1 ? saved : INITIAL_STATE;

return (
<button
onClick={() =>
setState({ ...state, currentPage: state.currentPage + 1 })
}
>
Page {state.currentPage}
</button>
);
}
//#endregion persistViewStateReact
}

/**
* Example: Persisting view state in localStorage (fallback, client-side)
*/
function persistViewState(app: App) {
//#region persistData
Expand Down
7 changes: 7 additions & 0 deletions examples/basic-host/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ This basic host can also be used to test MCP Apps during local development.
- [`index.html`](index.html) / [`src/index.tsx`](src/index.tsx) - React UI host with tool selection, parameter input, and iframe management
- [`sandbox.html`](sandbox.html) / [`src/sandbox.ts`](src/sandbox.ts) - Outer iframe proxy with security validation and bidirectional message relay
- [`src/implementation.ts`](src/implementation.ts) - Core logic: server connection, tool calling, and AppBridge setup
- [`src/storage.ts`](src/storage.ts) - What the host keeps in `localStorage`: the tool calls, and the state their Views saved

## Getting Started

Expand All @@ -24,6 +25,12 @@ By default, the host application will try to connect to an MCP server at `http:/
SERVERS='["http://localhost:1234/mcp", "http://localhost:5678/mcp"]' npm run start
```

## Persistence

Tool calls that have a View survive a reload of the host page: the host stores each call (server, tool, input and result) in its own `localStorage` and renders its View again from the stored input and result, without calling the tool again. Closing a call (×) removes it, and so does a reload while its server or tool is unavailable. To see a tool's new result after changing its code, call it again.

The host also supports [view state](../../specification/draft/apps.mdx#view-state-persistence) (`ui/set-view-state`): it advertises `hostCapabilities.viewState`, stores what each View saves under a key that it derives from the server and the tool call, hands it back as `hostContext.viewState` the next time it renders that View, and deletes it when the call is closed. A new call of the same tool starts with `null`.

## Architecture

This example uses a double-iframe sandbox pattern for secure UI isolation:
Expand Down
Loading
Loading