# 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\`.
- `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.
- `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.
- `onRequestDisplayMode?`: `({ mode }) => unknown` — A request for \`inline\`, \`fullscreen\`, or \`pip\`.
- `onUpdateModelContext?`: `(params: unknown) => unknown` — MCP Apps \`ui/update-model-context\`.
- `onWidgetState?`: `(state: unknown) => void` — A widget called \`genframe.setState\`.
- `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.        |
| `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.                                                                           |

### Storage

| Function                                                | Description                                                                                           |
| ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `clearWidgetStorage(id, { product?, 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.                                                                                             |
| `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
```

- `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.
- `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 }` (default `{ prompt: true, callTool: false }`) — Which host functions the guidance documents.

`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 except `extraTools`, plus:

- `execution`: `"frontend" | "backend"` (default `"frontend"`) — \`frontend\` runs the tools in the browser; \`backend\` only renders.
- `widget?`: `Omit<UseWidgetOptions, "tokens">` — 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, ToolDefinition>` — 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? })` | Model guidance; `mode` is `"jsonl"` (default) or `"inline"`.                                                            |
| `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 }`.                                                                                                       |
| `formatSpecIssues(issues)`                              | Issues as model-readable text.                                                                                          |
| `createStateStore(initial?)`                            | `{ getState, get, set, seed, subscribe }`.                                                                              |
| `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\`.
- `handlers?`: `Record<string, ActionHandler>` — Action handlers by name.
- `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 children render as pending.
- `placeholder`: `ComponentType<SpecPlaceholderProps>` (default `SpecPlaceholder`) — Rendered for elements that cannot render.

## `generative-frame/spec/tools`

| Export                                                              | Description                                                                                                                                           |
| ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `createSpecTools(catalog, { specs? })`                              | `{ render_spec }`. `specs` is a `Map<string, { spec, version }>` shared with the host. 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`.                                   |
| `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.
- `handlers?`: `Record<string, ActionHandler>` — Action handlers by name.
- `onAction?`: `(name, params, context) => unknown` — Called for catalog actions without a handler.
- `placeholder?`: `ComponentType<SpecPlaceholderProps>` — Placeholder for elements that cannot render.
- `specPrompt?`: `Omit<SpecPromptOptions, "mode">` — Options for the \`spec\` module guidance (\`customRules\`, \`omitExample\`).