Consolidate host styling patterns into unified documentation
Merge the separate "Support native host styling using CSS variables" and "Reacting to light/dark theme changes" sections into a single "Matching host styling (CSS variables, theme, and fonts)" pattern. This provides clearer guidance by covering all three concerns together. - Rename `docs/patterns.ts` to `docs/patterns.tsx` for JSX support - Add `hostStylingVanillaJs` and `hostStylingReact` consolidated examples - Enhance `applyHostFonts_fromHostContext` to apply initial fonts after `connect()`, not just on context change - Add CSS usage examples to `applyHostStyleVariables()` JSDoc - Update font example to use `var(--font-sans, system-ui, sans-serif)` Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
77306d1aaf
commit
566ac58ab7
6 changed files with 108 additions and 26 deletions
|
|
@ -82,7 +82,7 @@ Guest UI (App) <--PostMessageTransport--> Host (AppBridge) <--MCP Client--> MCP
|
||||||
|
|
||||||
JSDoc `@example` tags use `{@includeCode ./file.examples.ts#regionName}` to pull in type-checked code from companion `.examples.ts`/`.examples.tsx` files. Regions are marked with `//#region name` and `//#endregion name`, wrapped in functions (whose parameters provide types for external values). Region names follow `exportedName_variant` or `ClassName_methodName_variant` pattern (e.g., `useApp_basicUsage`, `App_hostCapabilities_checkAfterConnection`).
|
JSDoc `@example` tags use `{@includeCode ./file.examples.ts#regionName}` to pull in type-checked code from companion `.examples.ts`/`.examples.tsx` files. Regions are marked with `//#region name` and `//#endregion name`, wrapped in functions (whose parameters provide types for external values). Region names follow `exportedName_variant` or `ClassName_methodName_variant` pattern (e.g., `useApp_basicUsage`, `App_hostCapabilities_checkAfterConnection`).
|
||||||
|
|
||||||
Standalone docs in `docs/` (listed in `typedoc.config.mjs` `projectDocuments`) can also have type-checked companion `.ts` files using the same `@includeCode` pattern.
|
Standalone docs in `docs/` (listed in `typedoc.config.mjs` `projectDocuments`) can also have type-checked companion `.ts`/`.tsx` files using the same `@includeCode` pattern.
|
||||||
|
|
||||||
## Full Examples
|
## Full Examples
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -18,49 +18,41 @@ Set {@link types!McpUiToolMeta.visibility Tool.\_meta.ui.visibility} to `["app"]
|
||||||
- See [PDF example](https://github.com/modelcontextprotocol/ext-apps/blob/main/examples/pdf-viewer) to read binaries by chunks to avoid call tool size limitations on platforms like claude.ai
|
- See [PDF example](https://github.com/modelcontextprotocol/ext-apps/blob/main/examples/pdf-viewer) to read binaries by chunks to avoid call tool size limitations on platforms like claude.ai
|
||||||
- Pass auth token in `_meta` (will be loaded again in the future) + refresh token + store in local storage (see Persist data section below)
|
- Pass auth token in `_meta` (will be loaded again in the future) + refresh token + store in local storage (see Persist data section below)
|
||||||
|
|
||||||
{@includeCode ./patterns.ts#authenticatedCalls}
|
{@includeCode ./patterns.tsx#authenticatedCalls}
|
||||||
|
|
||||||
## [TODO] Giving errors back to model
|
## [TODO] Giving errors back to model
|
||||||
|
|
||||||
- Before app runs: validate inputs in tool call
|
- Before app runs: validate inputs in tool call
|
||||||
- After it runs: use `updateModelContext`
|
- After it runs: use `updateModelContext`
|
||||||
|
|
||||||
{@includeCode ./patterns.ts#errorsToModel}
|
{@includeCode ./patterns.tsx#errorsToModel}
|
||||||
|
|
||||||
## Support native host styling using CSS variables
|
## Matching host styling (CSS variables, theme, and fonts)
|
||||||
|
|
||||||
Hosts provide CSS variables (e.g., `--color-background-primary`) that match their theme. Apply these to the document, then use them in your styles via `var()`.
|
Use the SDK's style helpers to apply host styling, then reference them in your CSS:
|
||||||
|
|
||||||
|
- **CSS variables** — Use `var(--color-background-primary)`, etc. in your CSS
|
||||||
|
- **Theme** — Use `[data-theme="dark"]` selectors or `light-dark()` function for theme-aware styles
|
||||||
|
- **Fonts** — Use `var(--font-sans)` or `var(--font-mono)` with fallbacks (e.g., `font-family: var(--font-sans, system-ui, sans-serif)`)
|
||||||
|
|
||||||
**Vanilla JS:**
|
**Vanilla JS:**
|
||||||
|
|
||||||
{@includeCode ../src/styles.examples.ts#applyHostStyleVariables_fromHostContext}
|
{@includeCode ./patterns.tsx#hostStylingVanillaJs}
|
||||||
|
|
||||||
**React:**
|
**React:**
|
||||||
|
|
||||||
{@includeCode ../src/react/useHostStyles.examples.tsx#useHostStyles_basicUsage}
|
{@includeCode ./patterns.tsx#hostStylingReact}
|
||||||
|
|
||||||
## Reacting to light/dark theme changes
|
|
||||||
|
|
||||||
The host provides a `theme` value (`"light"` or `"dark"`) in the context. Apply it to `<html data-theme="...">` so you can use CSS selectors like `[data-theme="dark"]` for styling.
|
|
||||||
|
|
||||||
**Vanilla JS:**
|
|
||||||
|
|
||||||
{@includeCode ../src/styles.examples.ts#applyDocumentTheme_fromHostContext}
|
|
||||||
|
|
||||||
**React:** `useHostStyles()` (shown above) applies theme automatically. To read the theme reactively for conditional rendering:
|
|
||||||
|
|
||||||
{@includeCode ../src/react/useDocumentTheme.examples.tsx#useDocumentTheme_conditionalRender}
|
|
||||||
|
|
||||||
## [TODO] Support fullscreen / exit fullscreen
|
## [TODO] Support fullscreen / exit fullscreen
|
||||||
|
|
||||||
{@includeCode ./patterns.ts#fullscreen}
|
{@includeCode ./patterns.tsx#fullscreen}
|
||||||
|
|
||||||
## [TODO] Persist data (incl. widget state)
|
## [TODO] Persist data (incl. widget state)
|
||||||
|
|
||||||
- Note: OAI's `window.openai.setWidgetState({modelContent, privateContent, imageIds})` has only a partial equivalent in the MCP Apps spec (for now!): `App.updateModelContext({content, structuredContent})`
|
- Note: OAI's `window.openai.setWidgetState({modelContent, privateContent, imageIds})` has only a partial equivalent in the MCP Apps spec (for now!): `App.updateModelContext({content, structuredContent})`
|
||||||
- For data persistence / to reload when conversation is reloaded, you must use localStorage / IndexedDb with `hostInfo.toolInfo.id` as key returned `CallToolResult._meta.widgetUUID = randomUUID()`
|
- For data persistence / to reload when conversation is reloaded, you must use localStorage / IndexedDb with `hostInfo.toolInfo.id` as key returned `CallToolResult._meta.widgetUUID = randomUUID()`
|
||||||
|
|
||||||
{@includeCode ./patterns.ts#persistData}
|
{@includeCode ./patterns.tsx#persistData}
|
||||||
|
|
||||||
## [TODO] Lower perceived latency / manage loading time
|
## [TODO] Lower perceived latency / manage loading time
|
||||||
|
|
||||||
|
|
@ -68,13 +60,13 @@ Leverage partial inputs to show widgets as possible.
|
||||||
|
|
||||||
Beware of partial JSON being partial (but healed), so some of your objects may not be complete (e.g. in a list you may need to skip the last item if your code validates input schemas strictly).
|
Beware of partial JSON being partial (but healed), so some of your objects may not be complete (e.g. in a list you may need to skip the last item if your code validates input schemas strictly).
|
||||||
|
|
||||||
{@includeCode ./patterns.ts#lowerPerceivedLatency}
|
{@includeCode ./patterns.tsx#lowerPerceivedLatency}
|
||||||
|
|
||||||
## [TODO] Supporting both iframe & MCP Apps in same binary
|
## [TODO] Supporting both iframe & MCP Apps in same binary
|
||||||
|
|
||||||
See recipe: https://github.com/modelcontextprotocol/ext-apps/issues/34
|
See recipe: https://github.com/modelcontextprotocol/ext-apps/issues/34
|
||||||
|
|
||||||
{@includeCode ./patterns.ts#iframeAndMcpApps}
|
{@includeCode ./patterns.tsx#iframeAndMcpApps}
|
||||||
|
|
||||||
## [TODO] Migrating from OpenAI to MCP Apps
|
## [TODO] Migrating from OpenAI to MCP Apps
|
||||||
|
|
||||||
|
|
@ -82,4 +74,4 @@ See [OpenAI -> MCP Apps](https://docs.google.com/document/d/13ROImOR9B8xc32yhqsF
|
||||||
|
|
||||||
Also: [Managing State](https://platform.openai.com/docs/actions/managing-state) (OpenAI)
|
Also: [Managing State](https://platform.openai.com/docs/actions/managing-state) (OpenAI)
|
||||||
|
|
||||||
{@includeCode ./patterns.ts#migrateFromOpenai}
|
{@includeCode ./patterns.tsx#migrateFromOpenai}
|
||||||
|
|
|
||||||
162
docs/patterns.tsx
Normal file
162
docs/patterns.tsx
Normal file
|
|
@ -0,0 +1,162 @@
|
||||||
|
/**
|
||||||
|
* Type-checked code examples for the patterns documentation.
|
||||||
|
*
|
||||||
|
* These examples are included in {@link ./patterns.md} via `@includeCode` tags.
|
||||||
|
* Each function's region markers define the code snippet that appears in the docs.
|
||||||
|
*
|
||||||
|
* @module
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { App } from "../src/app.js";
|
||||||
|
import {
|
||||||
|
applyDocumentTheme,
|
||||||
|
applyHostFonts,
|
||||||
|
applyHostStyleVariables,
|
||||||
|
} from "../src/styles.js";
|
||||||
|
import type { McpUiHostContext } from "../src/types.js";
|
||||||
|
import { useApp, useHostStyles } from "../src/react/index.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example: Authenticated calls from App
|
||||||
|
*/
|
||||||
|
function authenticatedCalls(app: App) {
|
||||||
|
//#region authenticatedCalls
|
||||||
|
// TODO: Use tool calls / read resources
|
||||||
|
// See PDF example to read binaries by chunks
|
||||||
|
// Pass auth token in _meta + refresh token + store in local storage
|
||||||
|
//#endregion authenticatedCalls
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example: Giving errors back to model
|
||||||
|
*/
|
||||||
|
function errorsToModel(app: App) {
|
||||||
|
//#region errorsToModel
|
||||||
|
// Before app runs: validate inputs in tool call
|
||||||
|
// After it runs: updateModelContext
|
||||||
|
// TODO: Complete implementation
|
||||||
|
//#endregion errorsToModel
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example: Unified host styling (theme, CSS variables, fonts)
|
||||||
|
*/
|
||||||
|
function hostStylingVanillaJs(app: App) {
|
||||||
|
//#region hostStylingVanillaJs
|
||||||
|
function applyHostContext(ctx: McpUiHostContext) {
|
||||||
|
if (ctx.theme) {
|
||||||
|
applyDocumentTheme(ctx.theme);
|
||||||
|
}
|
||||||
|
if (ctx.styles?.variables) {
|
||||||
|
applyHostStyleVariables(ctx.styles.variables);
|
||||||
|
}
|
||||||
|
if (ctx.styles?.css?.fonts) {
|
||||||
|
applyHostFonts(ctx.styles.css.fonts);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply when host context changes
|
||||||
|
app.onhostcontextchanged = applyHostContext;
|
||||||
|
|
||||||
|
// Apply initial styles after connecting
|
||||||
|
app.connect().then(() => {
|
||||||
|
const ctx = app.getHostContext();
|
||||||
|
if (ctx) {
|
||||||
|
applyHostContext(ctx);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
//#endregion hostStylingVanillaJs
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example: Host styling with React (CSS variables, theme, fonts)
|
||||||
|
*/
|
||||||
|
function hostStylingReact() {
|
||||||
|
//#region hostStylingReact
|
||||||
|
function MyApp() {
|
||||||
|
const { app } = useApp({
|
||||||
|
appInfo: { name: "MyApp", version: "1.0.0" },
|
||||||
|
capabilities: {},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Apply all host styles (variables, theme, fonts)
|
||||||
|
useHostStyles(app, app?.getHostContext());
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
background: "var(--color-background-primary)",
|
||||||
|
fontFamily: "var(--font-sans)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<p>Styled with host CSS variables and fonts</p>
|
||||||
|
<p className="theme-aware">Uses [data-theme] selectors</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
//#endregion hostStylingReact
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example: Support fullscreen / exit fullscreen
|
||||||
|
*/
|
||||||
|
function fullscreen() {
|
||||||
|
//#region fullscreen
|
||||||
|
// TODO: Implement fullscreen support
|
||||||
|
//#endregion fullscreen
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example: Persist data (incl. widget state)
|
||||||
|
*/
|
||||||
|
function persistData(app: App) {
|
||||||
|
//#region persistData
|
||||||
|
// Note: OAI's window.openai.setWidgetState({modelContent, privateContent, imageIds})
|
||||||
|
// has only a partial equivalent in MCP Apps: App.updateModelContext({content, structuredContent})
|
||||||
|
// For data persistence / to reload when conversation is reloaded,
|
||||||
|
// use localStorage / IndexedDb with hostInfo.toolInfo.id as key
|
||||||
|
// returned CallToolResult._meta.widgetUUID = randomUUID()
|
||||||
|
// TODO: Complete implementation
|
||||||
|
//#endregion persistData
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example: Lower perceived latency / manage loading time
|
||||||
|
*/
|
||||||
|
function lowerPerceivedLatency(app: App) {
|
||||||
|
//#region lowerPerceivedLatency
|
||||||
|
// TODO: Leverage partial inputs to show widgets as possible.
|
||||||
|
// Beware of partial JSON being partial (but healed),
|
||||||
|
// so some objects may not be complete.
|
||||||
|
//#endregion lowerPerceivedLatency
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example: Supporting both iframe & MCP Apps in same binary
|
||||||
|
*/
|
||||||
|
function iframeAndMcpApps() {
|
||||||
|
//#region iframeAndMcpApps
|
||||||
|
// TODO: See recipe: https://github.com/modelcontextprotocol/ext-apps/issues/34
|
||||||
|
//#endregion iframeAndMcpApps
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example: Migrating from OpenAI to MCP Apps
|
||||||
|
*/
|
||||||
|
function migrateFromOpenai() {
|
||||||
|
//#region migrateFromOpenai
|
||||||
|
// TODO: See OpenAI -> MCP Apps migration guide
|
||||||
|
// https://docs.google.com/document/d/13ROImOR9B8xc32yhqsFyC9Hh3_H63JFORDIyjyIPcU4/edit
|
||||||
|
//#endregion migrateFromOpenai
|
||||||
|
}
|
||||||
|
|
||||||
|
// Suppress unused variable warnings
|
||||||
|
void authenticatedCalls;
|
||||||
|
void errorsToModel;
|
||||||
|
void hostStylingVanillaJs;
|
||||||
|
void hostStylingReact;
|
||||||
|
void fullscreen;
|
||||||
|
void persistData;
|
||||||
|
void lowerPerceivedLatency;
|
||||||
|
void iframeAndMcpApps;
|
||||||
|
void migrateFromOpenai;
|
||||||
|
|
@ -91,11 +91,20 @@ function applyHostStyleVariables_toElement(app: App) {
|
||||||
*/
|
*/
|
||||||
function applyHostFonts_fromHostContext(app: App) {
|
function applyHostFonts_fromHostContext(app: App) {
|
||||||
//#region applyHostFonts_fromHostContext
|
//#region applyHostFonts_fromHostContext
|
||||||
|
// Apply when host context changes
|
||||||
app.onhostcontextchanged = (params) => {
|
app.onhostcontextchanged = (params) => {
|
||||||
if (params.styles?.css?.fonts) {
|
if (params.styles?.css?.fonts) {
|
||||||
applyHostFonts(params.styles.css.fonts);
|
applyHostFonts(params.styles.css.fonts);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Apply initial fonts after connecting
|
||||||
|
app.connect().then(() => {
|
||||||
|
const ctx = app.getHostContext();
|
||||||
|
if (ctx?.styles?.css?.fonts) {
|
||||||
|
applyHostFonts(ctx.styles.css.fonts);
|
||||||
|
}
|
||||||
|
});
|
||||||
//#endregion applyHostFonts_fromHostContext
|
//#endregion applyHostFonts_fromHostContext
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -77,6 +77,19 @@ export function applyDocumentTheme(theme: McpUiTheme): void {
|
||||||
* @example Apply to a specific element
|
* @example Apply to a specific element
|
||||||
* {@includeCode ./styles.examples.ts#applyHostStyleVariables_toElement}
|
* {@includeCode ./styles.examples.ts#applyHostStyleVariables_toElement}
|
||||||
*
|
*
|
||||||
|
* @example Use host style variables in CSS
|
||||||
|
* ```css
|
||||||
|
* body {
|
||||||
|
* background-color: var(--color-background-primary);
|
||||||
|
* color: var(--color-text-primary);
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* .card {
|
||||||
|
* background-color: var(--color-background-secondary);
|
||||||
|
* border: 1px solid var(--color-border-primary);
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
* @see {@link McpUiStyles} for the available CSS variables
|
* @see {@link McpUiStyles} for the available CSS variables
|
||||||
* @see {@link McpUiHostContext} for the full host context structure
|
* @see {@link McpUiHostContext} for the full host context structure
|
||||||
*/
|
*/
|
||||||
|
|
@ -116,7 +129,7 @@ export function applyHostStyleVariables(
|
||||||
* @example Use host fonts in CSS
|
* @example Use host fonts in CSS
|
||||||
* ```css
|
* ```css
|
||||||
* body {
|
* body {
|
||||||
* font-family: "Anthropic Sans", sans-serif;
|
* font-family: var(--font-sans, system-ui, sans-serif);
|
||||||
* }
|
* }
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,6 @@
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"resolveJsonModule": true
|
"resolveJsonModule": true
|
||||||
},
|
},
|
||||||
"include": ["src/**/*.ts", "src/**/*.tsx", "docs/**/*.ts"],
|
"include": ["src/**/*.ts", "src/**/*.tsx", "docs/**/*.ts", "docs/**/*.tsx"],
|
||||||
"exclude": ["node_modules", "dist", "examples/**/*.ts"]
|
"exclude": ["node_modules", "dist", "examples/**/*.ts"]
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue