diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4af5aeefb..c7a83d8a7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/.github/workflows/update-snapshots.yml b/.github/workflows/update-snapshots.yml index 182f01a90..775fb4a67 100644 --- a/.github/workflows/update-snapshots.yml +++ b/.github/workflows/update-snapshots.yml @@ -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' diff --git a/AGENTS.md b/AGENTS.md index 219b94718..d43bc60bb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/docs/migrate_from_openai_apps.md b/docs/migrate_from_openai_apps.md index 22d5d9f0c..537f9c1f1 100644 --- a/docs/migrate_from_openai_apps.md +++ b/docs/migrate_from_openai_apps.md @@ -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) diff --git a/docs/patterns.md b/docs/patterns.md index 884de2651..ec814a387 100644 --- a/docs/patterns.md +++ b/docs/patterns.md @@ -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: + + +```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 | 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`: + + +```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(app, INITIAL_STATE); + // The saved state may come from an older version of this View + const state = saved.version === 1 ? saved : INITIAL_STATE; + + return ( + + ); +} +``` + +### 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`: @@ -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 diff --git a/docs/patterns.tsx b/docs/patterns.tsx index bb9eaa492..684430645 100644 --- a/docs/patterns.tsx +++ b/docs/patterns.tsx @@ -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"; @@ -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( + 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 | 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() { + //#region 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(app, INITIAL_STATE); + // The saved state may come from an older version of this View + const state = saved.version === 1 ? saved : INITIAL_STATE; + + return ( + + ); + } + //#endregion persistViewStateReact +} + +/** + * Example: Persisting view state in localStorage (fallback, client-side) */ function persistViewState(app: App) { //#region persistData diff --git a/examples/basic-host/README.md b/examples/basic-host/README.md index c64cda75d..bc005ee25 100644 --- a/examples/basic-host/README.md +++ b/examples/basic-host/README.md @@ -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 @@ -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: diff --git a/examples/basic-host/src/implementation.ts b/examples/basic-host/src/implementation.ts index 5f680ffdc..5e407d2d1 100644 --- a/examples/basic-host/src/implementation.ts +++ b/examples/basic-host/src/implementation.ts @@ -9,6 +9,7 @@ import { } from "@modelcontextprotocol/client"; import { getTheme, onThemeChange } from "./theme"; import { HOST_STYLE_VARIABLES } from "./host-styles"; +import { VIEW_STATE_MAX_BYTES, loadStoredToolCalls, loadViewState, removeStoredToolCall, saveViewState, type ViewState } from "./storage"; const SANDBOX_PROXY_BASE_URL = "http://localhost:8081/sandbox.html"; @@ -24,6 +25,7 @@ export const log = { export interface ServerInfo { name: string; + url: string; client: Client; tools: Map; resources: Map; @@ -46,7 +48,7 @@ export async function connectToServer(serverUrl: URL): Promise { const resources = new Map(resourcesList.resources.map((r) => [r.uri, r])); log.info("Server resources:", Array.from(resources.keys())); - return { name, client, tools, resources, appHtmlCache: new Map() }; + return { name, url: serverUrl.href, client, tools, resources, appHtmlCache: new Map() }; } async function connectWithFallback(serverUrl: URL): Promise { @@ -79,6 +81,11 @@ interface UiResourceData { } export interface ToolCallInfo { + /** + * Generated by the host and kept across page reloads: it identifies the View + * instance, that is, the View rendered for this tool call. + */ + id: string; serverInfo: ServerInfo; tool: Tool; input: Record; @@ -99,13 +106,47 @@ export function callTool( ): ToolCallInfo { log.info("Calling tool", name, "with input", input); const resultPromise = serverInfo.client.callTool({ name, arguments: input }) as Promise; + return newToolCallInfo(crypto.randomUUID(), serverInfo, name, input, resultPromise); +} + + +/** + * Rebuilds the tool calls that were stored before the page was reloaded, so + * that their Views are rendered again from the stored input and result. The + * tools are not called again; only the UI resources are read again. + */ +export function restoreToolCalls(servers: ServerInfo[]): ToolCallInfo[] { + const toolCalls: ToolCallInfo[] = []; + for (const { id, serverUrl, serverName, toolName, input, result } of loadStoredToolCalls()) { + const serverInfo = servers.find((s) => s.url === serverUrl && s.name === serverName); + if (result && serverInfo?.tools.has(toolName)) { + log.info("Restoring tool call", toolName, id); + toolCalls.push(newToolCallInfo(id, serverInfo, toolName, input, Promise.resolve(result))); + } else { + // The page was reloaded before the call finished (its result is lost), + // or its server or tool is gone. A real host would keep the call and + // show it as unavailable; this one forgets it, with its saved state. + log.warn("Dropping stored tool call", toolName, id, result ? "- server or tool unavailable" : "- unfinished"); + removeStoredToolCall(serverUrl, id); + } + } + return toolCalls; +} + +function newToolCallInfo( + id: string, + serverInfo: ServerInfo, + name: string, + input: Record, + resultPromise: Promise, +): ToolCallInfo { const tool = serverInfo.tools.get(name); if (!tool) { throw new Error(`Unknown tool: ${name}`); } - const toolCallInfo: ToolCallInfo = { serverInfo, tool, input, resultPromise }; + const toolCallInfo: ToolCallInfo = { id, serverInfo, tool, input, resultPromise }; const uiResourceUri = getToolUiResourceUri(tool); if (uiResourceUri) { @@ -275,6 +316,8 @@ export interface AppBridgeCallbacks { export interface AppBridgeOptions { containerDimensions?: { maxHeight?: number; width?: number } | { height: number; width?: number }; displayMode?: "inline" | "fullscreen"; + /** Id of the tool call that the View is rendered for. Without it, the View cannot save state. */ + toolCallId?: string; } export function newAppBridge( @@ -284,12 +327,29 @@ export function newAppBridge( options?: AppBridgeOptions, ): AppBridge { const serverCapabilities = serverInfo.client.getServerCapabilities(); + + // Read the state that this View instance saved earlier (`null` if none). + // If it cannot be read, `viewState` stays undefined and we advertise neither + // the capability nor the state: the View must not overwrite state that it + // has not seen. + const toolCallId = options?.toolCallId; + let viewState: ViewState | undefined; + if (toolCallId) { + try { + viewState = loadViewState(serverInfo.url, toolCallId); + } catch (error) { + log.warn("Could not read saved view state, so not advertising viewState:", error); + } + } + const appBridge = new AppBridge(serverInfo.client, IMPLEMENTATION, { openLinks: {}, serverTools: serverCapabilities?.tools, serverResources: serverCapabilities?.resources, // Declare support for model context updates updateModelContext: { text: {} }, + // Declare support for saving view state (only if we could read it) + ...(viewState !== undefined && { viewState: { maxBytes: VIEW_STATE_MAX_BYTES } }), }, { // Pass initial host context with theme, display mode, and style variables hostContext: { @@ -301,6 +361,8 @@ export function newAppBridge( containerDimensions: options?.containerDimensions ?? { maxHeight: 6000 }, displayMode: options?.displayMode ?? "inline", availableDisplayModes: ["inline", "fullscreen"], + // Only sent here, in the `ui/initialize` result; never in host-context-changed + ...(viewState !== undefined && { viewState }), }, }); @@ -361,6 +423,18 @@ export function newAppBridge( return {}; }; + if (toolCallId && viewState !== undefined) { + appBridge.onsetviewstate = async ({ state }) => { + // The state is opaque to the host: it is stored and handed back to this + // View instance, and shown to neither the model nor the server. + log.info("View state from MCP App:", state); + // Throws (so the View gets an error, and what was saved before is kept) + // if the state is larger than maxBytes or localStorage refuses it. + saveViewState(serverInfo.url, toolCallId, state); + return {}; + }; + } + appBridge.onsizechange = async ({ width, height }) => { // The MCP App has requested a `width` and `height`, but if // `box-sizing: border-box` is applied to the outer iframe element, then we diff --git a/examples/basic-host/src/index.tsx b/examples/basic-host/src/index.tsx index 00c0d52b2..85320790d 100644 --- a/examples/basic-host/src/index.tsx +++ b/examples/basic-host/src/index.tsx @@ -2,7 +2,8 @@ import { getToolUiResourceUri, McpUiToolMetaSchema } from "@modelcontextprotocol import type { Tool } from "@modelcontextprotocol/client"; import { Component, type ErrorInfo, type ReactNode, StrictMode, Suspense, use, useEffect, useMemo, useRef, useState } from "react"; import { createRoot } from "react-dom/client"; -import { callTool, connectToServer, hasAppHtml, initializeApp, loadSandboxProxy, log, newAppBridge, type ServerInfo, type ToolCallInfo, type ModelContext, type AppMessage } from "./implementation"; +import { callTool, connectToServer, hasAppHtml, initializeApp, loadSandboxProxy, log, newAppBridge, restoreToolCalls, type ServerInfo, type ToolCallInfo, type ModelContext, type AppMessage } from "./implementation"; +import { addStoredToolCall, removeStoredToolCall, setStoredToolCallResult } from "./storage"; import { getTheme, toggleTheme, onThemeChange, type Theme } from "./theme"; import styles from "./index.module.css"; @@ -52,9 +53,6 @@ interface HostProps { serversPromise: Promise; } -type ToolCallEntry = ToolCallInfo & { id: number }; -let nextToolCallId = 0; - // Parse URL query params for debugging: ?server=name&tool=name&call=true&theme=hide function getQueryParams() { const params = new URLSearchParams(window.location.search); @@ -89,21 +87,51 @@ function ThemeToggle() { function Host({ serversPromise }: HostProps) { - const [toolCalls, setToolCalls] = useState([]); - const [destroyingIds, setDestroyingIds] = useState>(new Set()); + const [toolCalls, setToolCalls] = useState([]); + const [destroyingIds, setDestroyingIds] = useState>(new Set()); const queryParams = useMemo(() => getQueryParams(), []); - const requestClose = (id: number) => { + // After a page reload, render the stored tool calls again once the servers + // are connected. (The `cancelled` flag guards against React Strict Mode's + // double invocation.) + useEffect(() => { + let cancelled = false; + serversPromise.then((servers) => { + if (cancelled) return; + const restored = restoreToolCalls(servers); + setToolCalls((calls) => [...restored, ...calls]); + }, () => { /* Reported by ServerSelect's error boundary */ }); + return () => { cancelled = true; }; + }, [serversPromise]); + + const addToolCall = (info: ToolCallInfo) => { + setToolCalls((calls) => [...calls, info]); + + // Store a call that has a View, then its result, so that a page reload can + // render the View again without calling the tool. A failed call is not kept. + if (!hasAppHtml(info)) return; + const { id, serverInfo, tool, input } = info; + addStoredToolCall({ id, serverUrl: serverInfo.url, serverName: serverInfo.name, toolName: tool.name, input }); + info.resultPromise.then( + (result) => setStoredToolCallResult(id, result), + () => removeStoredToolCall(serverInfo.url, id), + ); + }; + + const requestClose = (id: string) => { setDestroyingIds((s) => new Set(s).add(id)); }; - const completeClose = (id: number) => { + const completeClose = ({ id, serverInfo }: ToolCallInfo) => { setDestroyingIds((s) => { const next = new Set(s); next.delete(id); return next; }); setToolCalls((calls) => calls.filter((c) => c.id !== id)); + // Closing a call is this host's "delete the conversation": the state that + // its View saved goes with it. + removeStoredToolCall(serverInfo.url, id); }; return ( @@ -115,12 +143,12 @@ function Host({ serversPromise }: HostProps) { toolCallInfo={info} isDestroying={destroyingIds.has(info.id)} onRequestClose={() => requestClose(info.id)} - onCloseComplete={() => completeClose(info.id)} + onCloseComplete={() => completeClose(info)} /> ))} setToolCalls([...toolCalls, { ...info, id: nextToolCallId++ }])} + addToolCall={addToolCall} initialServer={queryParams.server} initialTool={queryParams.tool} autoCall={queryParams.call} @@ -197,7 +225,8 @@ function CallToolPanel({ serversPromise, addToolCall, initialServer, initialTool const url = new URL(window.location.href); url.searchParams.set("server", server.name); url.searchParams.set("tool", tool); - url.searchParams.set("call", "true"); // Auto-call on refresh + // The call is stored and restored on refresh, so don't auto-call again + url.searchParams.delete("call"); history.replaceState(null, "", url.toString()); }; @@ -214,6 +243,8 @@ function CallToolPanel({ serversPromise, addToolCall, initialServer, initialTool initialTool={initialTool} autoCall={autoCall && !hasAutoCalledRef.called} onAutoCall={(server, tool) => { + // React Strict Mode runs the calling effect twice + if (hasAutoCalledRef.called) return; hasAutoCalledRef.called = true; handleSubmit(server, tool); }} @@ -449,6 +480,7 @@ function AppIFramePanel({ toolCallInfo, isDestroying, onTeardownComplete }: AppI // Provide container dimensions - maxHeight for flexible sizing containerDimensions: { maxHeight: 6000 }, displayMode: "inline", + toolCallId: toolCallInfo.id, }); appBridgeRef.current = appBridge; initializeApp(iframe, appBridge, toolCallInfo); diff --git a/examples/basic-host/src/storage.ts b/examples/basic-host/src/storage.ts new file mode 100644 index 000000000..d77518aef --- /dev/null +++ b/examples/basic-host/src/storage.ts @@ -0,0 +1,130 @@ +/** + * What the host keeps in its own `localStorage` so that tool calls, and the + * state their Views saved with `ui/set-view-state`, survive a page reload. + * + * A real host would keep both with the conversation, on its backend. + */ +import { + ProtocolError, + ProtocolErrorCode, + type CallToolResult, +} from "@modelcontextprotocol/client"; + +const TOOL_CALLS_KEY = "basic-host:tool-calls"; +const VIEW_STATE_KEY_PREFIX = "basic-host:view-state:"; + +/** Advertised as `hostCapabilities.viewState.maxBytes`. */ +export const VIEW_STATE_MAX_BYTES = 65536; + +/** Enough to render a tool call's View again without calling the tool. */ +export interface StoredToolCall { + /** Host-generated; identifies the View instance across reloads. */ + id: string; + serverUrl: string; + /** Checked on restore: another server may be at that URL by then. */ + serverName: string; + toolName: string; + input: Record; + /** Absent until the tool call has finished. */ + result?: CallToolResult; +} + +export type ViewState = Record | null; + +/** Returns `[]` if nothing is stored, or if storage is unavailable or corrupt. */ +export function loadStoredToolCalls(): StoredToolCall[] { + try { + const calls = JSON.parse(localStorage.getItem(TOOL_CALLS_KEY) ?? "[]"); + if (!Array.isArray(calls)) return []; + return calls.filter((call) => typeof call?.id === "string"); + } catch (error) { + console.warn("[HOST] Could not read stored tool calls:", error); + return []; + } +} + +// Best effort: if this fails the host works as before, without persistence. +function updateStoredToolCalls( + update: (calls: StoredToolCall[]) => StoredToolCall[], +): void { + try { + const calls = update(loadStoredToolCalls()); + localStorage.setItem(TOOL_CALLS_KEY, JSON.stringify(calls)); + } catch (error) { + console.warn("[HOST] Could not store tool calls:", error); + } +} + +export function addStoredToolCall(call: StoredToolCall): void { + updateStoredToolCalls((calls) => [...calls, call]); +} + +/** Does nothing if the call was removed in the meantime. */ +export function setStoredToolCallResult( + id: string, + result: CallToolResult, +): void { + updateStoredToolCalls((calls) => + calls.map((call) => (call.id === id ? { ...call, result } : call)), + ); +} + +/** Removes a tool call and, with it, the state that its View saved. */ +export function removeStoredToolCall(serverUrl: string, id: string): void { + updateStoredToolCalls((calls) => calls.filter((call) => call.id !== id)); + try { + localStorage.removeItem(viewStateKey(serverUrl, id)); + } catch (error) { + console.warn("[HOST] Could not delete saved view state:", error); + } +} + +/** + * The host derives the key under which a View's state is saved; the View can + * neither name nor influence it. The spec asks for at least the user, the + * user's connection to the server and the View instance. This host has no + * user accounts, and identifies a server connection by its configured URL. + */ +function viewStateKey(serverUrl: string, toolCallId: string): string { + return `${VIEW_STATE_KEY_PREFIX}${toolCallId}:${serverUrl}`; +} + +/** + * Returns the saved state, or `null` if nothing is saved. + * @throws if storage cannot be read. The host must then not advertise + * `hostCapabilities.viewState` for this render. + */ +export function loadViewState(serverUrl: string, toolCallId: string): ViewState { + const json = localStorage.getItem(viewStateKey(serverUrl, toolCallId)); + return json === null ? null : JSON.parse(json); +} + +/** + * Replaces the saved state as a whole; `null` clears it. + * @throws if the state is too large (`-32602`: never as given) or cannot be + * stored (a plain error, which reaches the View as `-32603`: not now). What + * was saved before then stays as it was. + */ +export function saveViewState( + serverUrl: string, + toolCallId: string, + state: ViewState, +): void { + // A save that arrives after its call was closed must not bring state back. + if (!loadStoredToolCalls().some((call) => call.id === toolCallId)) { + throw new Error("Tool call is no longer stored"); + } + const key = viewStateKey(serverUrl, toolCallId); + if (state === null) { + localStorage.removeItem(key); + return; + } + const json = JSON.stringify(state); + if (new TextEncoder().encode(json).length > VIEW_STATE_MAX_BYTES) { + throw new ProtocolError( + ProtocolErrorCode.InvalidParams, + "View state too large", + ); + } + localStorage.setItem(key, json); +} diff --git a/examples/basic-server-react/README.md b/examples/basic-server-react/README.md index d2f2e0d7a..02e9ad85e 100644 --- a/examples/basic-server-react/README.md +++ b/examples/basic-server-react/README.md @@ -51,6 +51,7 @@ To test local modifications, use this configuration (replace `~/code/ext-apps` w - Tool registration with a linked UI resource - React UI using the [`useApp()`](https://apps.extensions.modelcontextprotocol.io/api/functions/_modelcontextprotocol_ext-apps_react.useApp.html) hook - App communication APIs: [`callServerTool`](https://apps.extensions.modelcontextprotocol.io/api/classes/app.App.html#callservertool), [`sendMessage`](https://apps.extensions.modelcontextprotocol.io/api/classes/app.App.html#sendmessage), [`sendLog`](https://apps.extensions.modelcontextprotocol.io/api/classes/app.App.html#sendlog), [`openLink`](https://apps.extensions.modelcontextprotocol.io/api/classes/app.App.html#openlink) +- View state persistence with the [`useViewState()`](https://apps.extensions.modelcontextprotocol.io/api/functions/_modelcontextprotocol_ext-apps_react.useViewState.html) hook: the text typed into the fields comes back after a reload, on hosts that support it ## Key Files diff --git a/examples/basic-server-react/src/mcp-app.tsx b/examples/basic-server-react/src/mcp-app.tsx index 2b5fbef9a..c11b02f9f 100644 --- a/examples/basic-server-react/src/mcp-app.tsx +++ b/examples/basic-server-react/src/mcp-app.tsx @@ -2,13 +2,25 @@ * @file App that demonstrates a few features using MCP Apps SDK + React. */ import type { App, McpUiHostContext } from "@modelcontextprotocol/ext-apps"; -import { useApp } from "@modelcontextprotocol/ext-apps/react"; +import { useApp, useViewState } from "@modelcontextprotocol/ext-apps/react"; import type { CallToolResult } from "@modelcontextprotocol/client"; import { StrictMode, useCallback, useEffect, useState } from "react"; import { createRoot } from "react-dom/client"; import styles from "./mcp-app.module.css"; +// What the user typed into the fields below and has not sent yet. The host +// saves it (if it supports that), so that it comes back after a reload. +type Draft = { version: 1; messageText: string; logText: string; linkUrl: string }; + +const INITIAL_DRAFT: Draft = { + version: 1, + messageText: "This is message text.", + logText: "This is log text.", + linkUrl: "https://modelcontextprotocol.io/", +}; + + function extractTime(callToolResult: CallToolResult): string { const { text } = callToolResult.content?.find((c) => c.type === "text")!; return text; @@ -70,9 +82,12 @@ interface GetTimeAppInnerProps { } function GetTimeAppInner({ app, toolResult, hostContext }: GetTimeAppInnerProps) { const [serverTime, setServerTime] = useState("Loading..."); - const [messageText, setMessageText] = useState("This is message text."); - const [logText, setLogText] = useState("This is log text."); - const [linkUrl, setLinkUrl] = useState("https://modelcontextprotocol.io/"); + // Like `useState`, but starts from the state that the host saved for this + // View, and saves each change (debounced) with `app.setViewState()`. + const [saved, setDraft] = useViewState(app, INITIAL_DRAFT); + // The saved state may come from an older version of this View. + const draft = saved.version === 1 ? saved : INITIAL_DRAFT; + const { messageText, logText, linkUrl } = draft; useEffect(() => { if (toolResult) { @@ -137,17 +152,17 @@ function GetTimeAppInner({ app, toolResult, hostContext }: GetTimeAppInnerProps)
-