# API reference
URL: /generative-frame/docs/api-reference

Signatures and options for every generative-frame entry point.

> For AI agents: a documentation index is available at [llms.txt](/llms.txt). Use `.md` for canonical markdown pages; `.mdx` is kept as a backwards-compatible alias on supported URL paths.

## `generative-frame`

### `createWidget`

```
import { createWidget } from "generative-frame";

const widget: WidgetHandle = createWidget(options);
```

- `container`: `HTMLElement` — The element the frame is appended to.
- `tokens`: `ThemeTokens` (default `DEFAULT_LIGHT_TOKENS`) — Theme tokens sent into the frame. See [Theming](/generative-frame/docs/theming).
- `csp`: `CspOptions | string` (default `buildCsp()`) — The frame's Content Security Policy, as options or a complete policy string.
- `maxHeight?`: `number` — The iframe never grows past this height; taller content scrolls inside it.
- `minHeight`: `number` (default `0`) — The smallest height of the iframe.
- `code?`: `string` — Complete code to render immediately, as \`write(code)\` then \`end()\`.
- `product`: `string` (default `"generative-frame"`) — Scopes the frame origin, see \`SafeContentFrame\`.
- `frame?`: `SafeContentFrame` — A preconfigured Safe Content Frame, for example with \`useShadowDom\`. Cannot be combined with \`id\` or \`unsafeShimDomain\`.
- `unsafeShimDomain`: `string` (default `"scf.auiusercontent.com"`) — Load the Safe Content Frame shim from a domain you host. Isolation holds only if the domain is a public suffix on the Public Suffix List. See [Security model](/generative-frame/docs/security#hosting-the-shim-yourself).
- `opaqueOrigin`: `boolean` (default `false`) — Render in a \`sandbox="allow-scripts"\` frame with a \`null\` origin instead of Safe Content Frame: no shim, no storage. Cannot be combined with \`id\`, \`frame\`, or \`unsafeShimDomain\`. See [Security model](/generative-frame/docs/security#opaque-origin-frames).
- `id?`: `string` — A stable origin, so the widget's storage persists for this id. Choose it on the host. See [Persistent storage](/generative-frame/docs/quickstart#persistent-storage).
- `context?`: `HostContext` — Extra MCP Apps host context fields (locale, display mode, and so on) merged over the theme.
- `animate`: `boolean` (default `true`) — Fade in elements as they stream in. Always off under reduced motion.
- `css?`: `string` — Extra CSS appended after the frame's base styles.
- `readyTimeoutMs`: `number` (default `15000`) — How long the frame may take to connect before \`ready\` rejects and an error is reported.
- `initialState`: `unknown` (default `null`) — The state \`genframe.state\` returns when the frame connects. The frame then keeps the latest state the widget sets, also across a remount, and \`useWidget\` starts a frame it creates again (as when \`\<Activity>\` hides and shows it) from that latest state.
- `onPrompt?`: `(text: string) => unknown` — A widget called \`sendPrompt(text)\`.
- `onMessage?`: `(params: UiMessageParams) => unknown` — The raw MCP Apps \`ui/message\`. Takes precedence over \`onPrompt\`.
- `onOpenLink`: `(url: string) => unknown` (default `open in a new tab`) — An http(s) link the widget asked to open.
- `onCallTool?`: `(call: { name, arguments? }) => unknown` — A widget called \`genframe.callTool\` or MCP \`tools/call\`. The return value is the result.
- `onInitialized?`: `(params: McpAppInitializeParams) => void` — An MCP Apps widget sent \`ui/notifications/initialized\`. Receives the params of its \`ui/initialize\` request: \`appInfo\`, \`appCapabilities\`, and \`protocolVersion\`. A malformed field is omitted, and \`appCapabilities.availableDisplayModes\` keeps only \`inline\`, \`fullscreen\`, and \`pip\`. When \`replace()\` remounts the widget, it runs again with the new frame's params once that frame is shown.
- `onRequestDisplayMode?`: `({ mode }) => unknown` — A request for \`inline\`, \`fullscreen\`, or \`pip\`. The MCP Apps spec forbids switching a widget into a mode missing from the \`availableDisplayModes\` it declared.
- `onUpdateModelContext?`: `(params: unknown) => unknown` — MCP Apps \`ui/update-model-context\`.
- `onCopyText?`: `(text: string) => unknown` — A widget called \`genframe.copyText(text)\` or \`navigator.clipboard.writeText(text)\`. The request alone does not show the user asked for the copy, so confirm with them before writing the clipboard. Without it, copying fails in the widget.
- `onWidgetState?`: `(state: unknown) => void` — A widget called \`genframe.setState\` with a plain JSON value of up to about 1,000,000 characters as JSON, an object used in several places counting once for each. Calls from a frame that has since been replaced are ignored.
- `onResize?`: `(size: WidgetSize) => void` — The content size changed.
- `onError?`: `(error: WidgetError) => void` — An error, unhandled rejection, CSP violation, failed resource, or script error in the widget.
- `onLog?`: `(entry: ConsoleEntry) => void` — Console output from the widget.

### `WidgetHandle`

| Member                                                     | Description                                                                                                                                                    |
| ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ready: Promise<void>`                                     | Resolves once the frame runtime is connected; rejects if it never connects.                                                                                    |
| `code: string`                                             | All code written so far.                                                                                                                                       |
| `ended: boolean`                                           | Whether `end()` or `replace()` has been called.                                                                                                                |
| `iframe: HTMLIFrameElement \| undefined`                   | The current iframe.                                                                                                                                            |
| `write(chunk)`                                             | Appends streamed code. Throws after `end()`.                                                                                                                   |
| `end(): Promise<EndResult>`                                | Marks the code complete, runs held scripts, and resolves with `{ size, blank, errorCount }`.                                                                   |
| `replace(code): Promise<EndResult>`                        | Renders new complete code, morphing in place, or remounting when scripts already ran. A newer call removes a remount still in progress, whose promise rejects. |
| `setTheme(tokens)`                                         | Sends new theme tokens.                                                                                                                                        |
| `setContext(context)`                                      | Merges MCP Apps host context fields and notifies the widget.                                                                                                   |
| `notifyToolInput(args, { partial? })`                      | Forwards tool input to MCP Apps widgets.                                                                                                                       |
| `notifyToolResult(result)`                                 | Forwards a tool result to MCP Apps widgets.                                                                                                                    |
| `screenshot({ scale?, background? }): Promise<Screenshot>` | Captures the widget as `{ dataUrl, width, height }`.                                                                                                           |
| `inspect(): Promise<WidgetInspection>`                     | `{ kind, ended, size, blank, errors, console, code }`.                                                                                                         |
| `on(event, listener): () => void`                          | Subscribes to `ready`, `resize`, `error`, `log`, or `end`.                                                                                                     |
| `dispose()`                                                | Removes the frame, and a replacement frame still rendering.                                                                                                    |

### Storage

| Function                                                                   | Description                                                                                           |
| -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `clearWidgetStorage(id, { product?, unsafeShimDomain?, readyTimeoutMs? })` | Clears the storage of widgets with this `id`; resolves with `{ cleared }`, the storage kinds cleared. |
| `widgetStorageSalt(id)`                                                    | The `SafeContentFrame` salt behind an `id`'s origin.                                                  |

### `previewWidget`

```
previewWidget(code: string, options?: PreviewOptions): Promise<PreviewResult>
```

Options and result are on [Repair loop and screenshots](/generative-frame/docs/repair#previewwidget).

### Theme

| Export                                                                      | Description                              |
| --------------------------------------------------------------------------- | ---------------------------------------- |
| `readThemeTokens(element?, sources?)`                                       | Reads the page theme into `ThemeTokens`. |
| `defaultThemeTokens(scheme)`, `DEFAULT_LIGHT_TOKENS`, `DEFAULT_DARK_TOKENS` | Built-in palettes.                       |

### CSP

| Export                | Description                                                                                                   |
| --------------------- | ------------------------------------------------------------------------------------------------------------- |
| `buildCsp(options?)`  | The policy string for `CspOptions`. See [Security model](/generative-frame/docs/security#the-default-policy). |
| `DEFAULT_CDN_ORIGINS` | The default CDN allowlist.                                                                                    |

## `generative-frame/react`

### `<Widget>`

`WidgetProps` are every `createWidget` option except `container` and `code`, plus:

- `code`: `string` — Widget code, complete or still growing.
- `streaming`: `boolean` (default `false`) — True while \`code\` is still growing; scripts run once it turns false.
- `className?`: `string` — Class for the wrapper \`div\`.
- `style?`: `CSSProperties` — Style for the wrapper \`div\`.

### Hooks and helpers

| Export                                                       | Description                                                                                                                                                     |
| ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `useWidget(options): { ref, widget }`                        | Mounts a frame into the element passed to `ref`. Options are read once per mount; handlers call their latest version; a new `tokens` object becomes `setTheme`. |
| `useThemeTokens(element?, sources?, { observeBodyStyle? }?)` | Theme tokens that update with the page; one shared observer per element and sources.                                                                            |

## `generative-frame/tools`

| Export                                                                         | Description                                                                                                                                                                                                                                                                    |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `createWidgetTools({ registry?, guidance?, preview?, modules?, extraTools? })` | `{ read_me, show_widget, edit_widget, preview_widget }`, plus `extraTools`. See [Tools and prompts](/generative-frame/docs/tools).                                                                                                                                             |
| `toAISDKTools(tools, { jsonSchema })`                                          | The tools in the Vercel AI SDK shape.                                                                                                                                                                                                                                          |
| `getToolDeclarations(tools)`                                                   | `{ description, inputSchema }` per tool, without `execute`.                                                                                                                                                                                                                    |
| `buildWidgetInstructions(tools, { preload? }): Promise<string>`                | A system prompt section for the tools. When `read_me` offers a `spec` module, its guidance is preloaded by default. An explicit `preload` replaces that default: `{}` and `{ platform: "mobile" }` leave `spec` on demand, and `{ modules: ["spec", "chart"] }` preloads both. |
| `createWidgetRegistry(initial?)`                                               | The latest code per title.                                                                                                                                                                                                                                                     |
| `applyWidgetEdits(code, edits)`                                                | `{ ok: true, code }` or `{ ok: false, error, index }`.                                                                                                                                                                                                                         |

The `ToolDefinition`, `AnyTool`, `GuidanceModule`, and `JsonSchema` types are exported too. A `GuidanceModule` is `{ name, summary, guidance(): string }`.

## `generative-frame/prompts`

```
buildWidgetGuidance(options?: GuidanceOptions): string
```

These options change model guidance, not the frame's enforced policy. Configure matching origins in `createWidget({ csp })`; `buildWidgetGuidance` does not grant resource or network access.

- `modules`: `WidgetModule[]` (default `[]`) — \`diagram\`, \`chart\`, \`data_viz\`, \`interactive\`, \`mockup\`, \`elicitation\`, \`art\`.
- `platform`: `"desktop" | "mobile"` (default `"desktop"`) — The user's client.
- `tokens?`: `ThemeTokens` — The tokens the host sends; their names become the token reference.
- `cdnOrigins`: `string[]` (default `DEFAULT_CDN_ORIGINS`) — Where the model may load libraries from.
- `fontStyleOrigins`: `string[]` (default `[]`) — Extra font stylesheet origins to describe to the model; also configure fontStyleOrigins in createWidget csp.
- `fontOrigins`: `string[]` (default `[]`) — Extra font file origins to describe to the model; also configure fontOrigins in createWidget csp.
- `connectOrigins`: `string[]` (default `[]`) — Where widget code may send requests.
- `allowEval`: `boolean` (default `false`) — Whether \`eval\` is available.
- `width`: `number` (default `680 on desktop, 360 on mobile`) — Frame width in CSS pixels.
- `hostApi`: `{ prompt?: boolean; callTool?: boolean; modelContext?: boolean; clipboard?: boolean }` (default `{ prompt: true, callTool: false, modelContext: false, clipboard: false }`) — Which host functions the guidance documents. \`createWidgetToolkit\` turns on \`modelContext\`, and \`clipboard\` when you pass \`widget.onCopyText\`.

`WIDGET_MODULES` lists the module names.

## `generative-frame/repair`

| Export                                           | Description                                                                                                    |
| ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- |
| `repairLoop(options): Promise<RepairLoopResult>` | Generate, render, and feed back until accepted or out of rounds. Resolves with `{ ok, code, report, rounds }`. |
| `buildRepairFeedback(report, options?)`          | Model-readable feedback for a `RenderReport`.                                                                  |

Options are on [Repair loop and screenshots](/generative-frame/docs/repair#repairloop).

## `generative-frame/assistant-ui`

```
createWidgetToolkit(options?: WidgetToolkitOptions): { toolkit, tools, registry }
useWidgetInstructions(tools, { preload? }): void
useAssistantUiThemeTokens(element?): ThemeTokens
```

`WidgetToolkitOptions` takes the `createWidgetTools` options, plus:

- `execution`: `"frontend" | "backend"` (default `"frontend"`) — \`frontend\` runs the tools in the browser; \`backend\` only renders.
- `widget?`: `Omit<UseWidgetOptions, "tokens" | "initialState">` — Options for every widget frame (csp, product, maxHeight, handlers).
- `spec?`: `WidgetToolkitExtension` — Spec mode, from \`createSpecToolkit(catalog, options)\` in \`generative-frame/spec/assistant-ui\`. Adds \`render_spec\` and the \`spec\` module of \`read_me\`.
- `extraTools?`: `Record<string, AnyTool>` — More tools for the model, such as data lookups. They execute like the widget tools and render nothing in the thread.
- `themeElement`: `Element | null` (default `document root`) — Where the theme is read from.
- `display`: `"standalone" | "inline"` (default `"standalone"`) — How the widget tools are presented relative to the reasoning trace.
- `renderReport`: `{ timeoutMs?, settleMs? } | false` (default `{ timeoutMs: 10000, settleMs: 300 }`) — Frontend execution: \`show_widget\` and \`edit_widget\` results wait for the frame and carry a \`render\` report. \`false\` returns at once.
- `preview`: `(code, { width?, appearance? }) => Promise<PreviewResult>` (default `previewWidget`) — Renders code for \`preview_widget\`.
- `previewScreenshot`: `boolean` (default `false`) — Keep the PNG in \`preview_widget\` results.
- `widgetId`: `(({ toolCallId, threadId }) => string) | false` (default `<remoteId>:<toolCallId>, or aui:<toolCallId> without a remote id`) — The storage id of a widget's frame, from the thread's remote id and the \`show_widget\` call that created it. \`false\` gives every frame a fresh origin.

The `RenderReportOptions`, `WidgetRenderReport`, `WidgetToolkitExtension`, `ToolkitExecution`, and `ToolkitDisplay` types are exported too.

## `generative-frame/spec`

| Export                                                            | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `defineCatalog({ components, actions? })`                         | A `Catalog` with `component`, `action`, `propsSchema`, `paramsSchema`, `validateProps`, `validateParams`, and `prompt`.                                                                                                                                                                                                                                                                                                                                                                                                |
| `catalog.prompt({ mode?, customRules?, omitExample?, hostApi? })` | Model guidance; `mode` is `"jsonl"` (default) or `"inline"`, and `hostApi: { prompt?, modelContext?, clipboard? }` documents the built-in `sendMessage`, `updateModelContext`, and `copyText` actions.                                                                                                                                                                                                                                                                                                                 |
| `createSpecStream({ mode?, initial? })`                           | `{ push(chunk), result(), spec }`; `mode` is `"jsonl"` (default) or `"inline"`.                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `parseSpecStream(source, options?)`                               | The same for a complete string.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `applyPatch(doc, operations)`                                     | Applies RFC 6902 operations.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `validateSpec(spec, catalog, { partial? })`                       | `{ ok, issues }`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `resolveSpec(spec, { state?, locale? })`                          | The element tree the renderer draws for one state, each `ResolvedElement` with `id`, `type`, `props`, `bindings`, `on`, `children`, `slots`, and, inside a `repeat`, its `itemPath`, with the item's `key` on a direct child of the `repeat`; `null` when the root does not resolve. `locale` sets the BCP 47 locale for `number`, `currency`, and `percent`; omitted, invalid, or unsupported tags use `en-US`.                                                                                                       |
| `formatSpecIssues(issues)`                                        | Issues as model-readable text.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `createStateStore(initial?, { writes? }?)`                        | `{ getState, get, set, writes, seed, subscribe }`. `set(path, value, mode?)` inserts at array indices by default and replaces an existing item with `"replace"`. `writes()` lists the writes `seed` re-applies as `[path, value]`, `[path, value, "replace"]`, or, for a write through an array, `[path, value, mode, arrayParents]`, oldest first, a replacing write dropping earlier ones at and below its path that no insert at an index on that path has since moved; `writes` applies saved ones over `initial`. |
| `emptySpec()`                                                     | An empty spec.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |

## `generative-frame/spec/react`

| Export                                                   | Description                                              |
| -------------------------------------------------------- | -------------------------------------------------------- |
| `useSpecStream({ source?, complete?, mode?, initial? })` | `{ spec, text, errors, push, end, reset }`.              |
| `<SpecPlaceholder>`                                      | The default placeholder for elements that cannot render. |

### `<SpecRenderer>`

- `spec`: `Spec` — The spec to render.
- `components`: `SpecComponents` — Implementations by component type.
- `catalog?`: `Catalog` — Validates props before rendering; invalid elements render a placeholder.
- `state?`: `SpecStateStore` — An external store. Otherwise one is created and seeded from \`spec.state\`.
- `locale`: `string` (default `en-US`) — The BCP 47 locale for \`$calc\` functions \`number\`, \`currency\`, and \`percent\`. Invalid or unsupported tags fall back to \`en-US\`.
- `handlers?`: `Record<string, ActionHandler>` — Action handlers by name.
- `confirmAction?`: `(request: { action, params, elementId? }) => boolean | Promise<boolean>` — Called before an action whose catalog definition has \`confirm: true\` runs. Return \`true\` to run it or \`false\` to stop the action list. Without it, a \`confirm: true\` action fails, and a \`watch\` that dispatches one is rejected.
- `onAction?`: `(name, params, context) => unknown` — Called for catalog actions without a handler.
- `onError?`: `(error, { elementId? }) => void` — A component threw or an action failed.
- `streaming`: `boolean` (default `false`) — Missing elements take no space, an element with invalid props keeps its last valid render, and one pending placeholder follows the spec.
- `placeholder`: `ComponentType<SpecPlaceholderProps>` (default `SpecPlaceholder`) — Rendered for elements that cannot render.

## `generative-frame/spec/vue`

The Vue renderer, with `vue` as an optional peer. `SpecRenderer` takes the same props as the React one, with `placeholder` a Vue component.

| Export                                                   | Description                                                                                                                                                     |
| -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SpecRenderer`                                           | Renders a spec with Vue components.                                                                                                                             |
| `useSpecStream({ source?, complete?, mode?, initial? })` | `{ spec, text, errors, push, end, reset }`; the options accept plain values, refs, or getters, and `spec`, `text`, and `errors` are refs.                       |
| `useSpecElement()`                                       | The rendering element's `{ id, element, bindings, state, streaming }`, for a component that needs them. Throws outside a component that `SpecRenderer` renders. |
| `SpecPlaceholder`                                        | The default placeholder for elements that cannot render.                                                                                                        |

## `generative-frame/spec/tools`

| Export                                                              | Description                                                                                                                                                                                                                  |
| ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `createSpecTools(catalog, { specs?, customRules? })`                | `{ render_spec }`. `specs` is a `Map<string, { spec, version }>` shared with the host, and `customRules` follow the built-in rules in the tool's description. See [`render_spec`](/generative-frame/docs/tools#render_spec). |
| `specGuidanceModule(catalog, promptOptions?)`                       | The `spec` module for `createWidgetTools({ modules })`. `promptOptions` are `catalog.prompt` options except `mode`.                                                                                                          |
| `SPEC_TOOL_RESULTS_RULE`                                            | The rule that tells the model where the assistant-ui spec toolkit mounts earlier tool results. Add it to a backend `render_spec`'s `customRules` and spec guidance alongside the toolkit's `toolResults: true`.              |
| `toAISDKTools(tools, { jsonSchema })`, `getToolDeclarations(tools)` | The same adapters as in `generative-frame/tools`.                                                                                                                                                                            |

## `generative-frame/spec/assistant-ui`

```
createSpecToolkit(catalog: Catalog, options: SpecToolkitOptions): WidgetToolkitExtension
```

Pass the result of `createSpecToolkit` to `createWidgetToolkit({ spec })`.

- `components`: `SpecComponents` — Implementations for the catalog's components.
- `locale`: `string` (default `en-US`) — The BCP 47 locale for \`$calc\` functions \`number\`, \`currency\`, and \`percent\`. Invalid or unsupported tags fall back to \`en-US\`.
- `handlers?`: `Record<string, ActionHandler>` — Action handlers by name.
- `onAction?`: `(name, params, context) => unknown` — Called for catalog actions without a handler.
- `confirmAction?`: `(request: { action, params, elementId? }) => boolean | Promise<boolean>` — Called before an action whose catalog definition has \`confirm: true\` runs. Return \`true\` to run it or \`false\` to stop the action list. Without it, a \`confirm: true\` action fails, and a \`watch\` that dispatches one is rejected.
- `placeholder?`: `ComponentType<SpecPlaceholderProps>` — Placeholder for elements that cannot render.
- `specPrompt?`: `Omit<SpecPromptOptions, "mode">` — Options for the \`spec\` module guidance (\`customRules\`, \`omitExample\`); \`customRules\` also go into \`render_spec\`'s description.
- `toolResults?`: `boolean` — Mounts earlier tool results under \`/tools\` in backend execution too, as frontend execution always does. Pair it with \`SPEC_TOOL_RESULTS_RULE\` in the server's \`render_spec\` and spec guidance, which tells the model the results are there.

## `generative-frame/spec/assistant-ui/vue`

```
createSpecToolkit(catalog: Catalog, options: SpecToolkitOptions): VueSpecToolkit
```

The same options with Vue implementations: `components` from `generative-frame/spec/vue`'s `SpecComponents`, and `placeholder` as a Vue `Component`. `entries({ execution, display })` returns a `Toolkit` for `Tools({ toolkit })` from `@assistant-ui/core/react`, and `modules` holds the `spec` module guidance.