Skip to content
/docsfor

API reference

Signatures and options for every generative-frame entry point.

generative-frame

createWidget

import { createWidget } from "generative-frame";

const widget: WidgetHandle = createWidget(options);
CreateWidgetOptions
containerHTMLElement

The element the frame is appended to.

tokensThemeTokens= DEFAULT_LIGHT_TOKENS

Theme tokens sent into the frame. See Theming.

cspCspOptions | string= 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.

minHeightnumber= 0

The smallest height of the iframe.

code?string

Complete code to render immediately, as `write(code)` then `end()`.

productstring= "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`.

unsafeShimDomainstring= "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.

opaqueOriginboolean= 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.

id?string

A stable origin, so the widget's storage persists for this id. Choose it on the host. See Persistent storage.

context?HostContext

Extra MCP Apps host context fields (locale, display mode, and so on) merged over the theme.

animateboolean= true

Fade in elements as they stream in. Always off under reduced motion.

css?string

Extra CSS appended after the frame's base styles.

readyTimeoutMsnumber= 15000

How long the frame may take to connect before `ready` rejects and an error is reported.

initialStateunknown= 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= 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

MemberDescription
ready: Promise<void>Resolves once the frame runtime is connected; rejects if it never connects.
code: stringAll code written so far.
ended: booleanWhether end() or replace() has been called.
iframe: HTMLIFrameElement | undefinedThe 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): () => voidSubscribes to ready, resize, error, log, or end.
dispose()Removes the frame, and a replacement frame still rendering.

Storage

FunctionDescription
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.

Theme

ExportDescription
readThemeTokens(element?, sources?)Reads the page theme into ThemeTokens.
defaultThemeTokens(scheme), DEFAULT_LIGHT_TOKENS, DEFAULT_DARK_TOKENSBuilt-in palettes.

CSP

ExportDescription
buildCsp(options?)The policy string for CspOptions. See Security model.
DEFAULT_CDN_ORIGINSThe default CDN allowlist.

generative-frame/react

<Widget>

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

WidgetProps
codestring

Widget code, complete or still growing.

streamingboolean= 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

ExportDescription
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

ExportDescription
createWidgetTools({ registry?, guidance?, preview?, modules?, extraTools? }){ read_me, show_widget, edit_widget, preview_widget }, plus extraTools. See Tools and prompts.
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.

GuidanceOptions
modulesWidgetModule[]= []

`diagram`, `chart`, `data_viz`, `interactive`, `mockup`, `elicitation`, `art`.

platform"desktop" | "mobile"= "desktop"

The user's client.

tokens?ThemeTokens

The tokens the host sends; their names become the token reference.

cdnOriginsstring[]= DEFAULT_CDN_ORIGINS

Where the model may load libraries from.

fontStyleOriginsstring[]= []

Extra font stylesheet origins to describe to the model; also configure fontStyleOrigins in createWidget csp.

fontOriginsstring[]= []

Extra font file origins to describe to the model; also configure fontOrigins in createWidget csp.

connectOriginsstring[]= []

Where widget code may send requests.

allowEvalboolean= false

Whether `eval` is available.

widthnumber= 680 on desktop, 360 on mobile

Frame width in CSS pixels.

hostApi{ prompt?: boolean; callTool?: boolean; modelContext?: boolean; clipboard?: boolean }= { 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

ExportDescription
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/assistant-ui

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

WidgetToolkitOptions takes the createWidgetTools options, plus:

WidgetToolkitOptions
execution"frontend" | "backend"= "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.

themeElementElement | null= document root

Where the theme is read from.

display"standalone" | "inline"= "standalone"

How the widget tools are presented relative to the reasoning trace.

renderReport{ timeoutMs?, settleMs? } | false= { 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>= previewWidget

Renders code for `preview_widget`.

previewScreenshotboolean= false

Keep the PNG in `preview_widget` results.

widgetId(({ toolCallId, threadId }) => string) | false= <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

ExportDescription
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

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

<SpecRenderer>

SpecRendererProps
specSpec

The spec to render.

componentsSpecComponents

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`.

localestring= 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.

streamingboolean= false

Missing elements take no space, an element with invalid props keeps its last valid render, and one pending placeholder follows the spec.

placeholderComponentType<SpecPlaceholderProps>= 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.

ExportDescription
SpecRendererRenders 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.
SpecPlaceholderThe default placeholder for elements that cannot render.

generative-frame/spec/tools

ExportDescription
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.
specGuidanceModule(catalog, promptOptions?)The spec module for createWidgetTools({ modules }). promptOptions are catalog.prompt options except mode.
SPEC_TOOL_RESULTS_RULEThe 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 }).

SpecToolkitOptions
componentsSpecComponents

Implementations for the catalog's components.

localestring= 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.