Skip to content

@mfui/client

@mfui/client is the browser-side SDK for defining MFUI components, sending a serializable manifest to the server, reading MFUI semantic streams, and working with projected messages.

Most applications use this package in the chat UI or request layer they already own.

defineMFUIComponent()

Creates a component definition that can be used locally and serialized into an MFUI component manifest.

Import

ts
import { defineMFUIComponent } from '@mfui/client';

Signature

ts
function defineMFUIComponent<TSpec>(
  input: DefineMFUIComponentInput<TSpec>,
): MFUIComponentDefinition<TSpec>

Parameters

NameTypeRequiredDefaultDescription
inputDefineMFUIComponentInput<TSpec>Yesn/aComponent definition input.

Returns

TypeDescription
MFUIComponentDefinition<TSpec>A local component definition with manifest, project(), validate(), and toManifest().

Example

ts
import { z } from 'zod';
import { defineMFUIComponent } from '@mfui/client';

const taskListDefinition = defineMFUIComponent({
  name: 'app.task_list',
  schema: z.object({
    title: z.string(),
    items: z.array(
      z.object({
        label: z.string(),
        done: z.boolean().default(false),
      }),
    ),
  }),
  model: {
    description: 'Show a short checklist of tasks.',
    whenToUse: 'Use this when the answer contains actionable tasks.',
  },
  projection: {
    text: `### {{ title }}

{% for item in items %}
- {{ item.label }}{% if item.done %} (done){% endif %}
{% endfor %}`,
  },
});

Notes

When schema is a Zod schema, MFUI converts it to JSON Schema for the serialized manifest. If you pass a raw JSON Schema, local validate() returns a failure explaining that JSON Schema validation is handled by @mfui/server.

project() can throw if the projection template uses unsupported MFUI template tags or filters.

DefineMFUIComponentInput<TSpec>

Input object for defineMFUIComponent().

PropertyTypeRequiredDefaultDescription
namestringYesn/aStable component name used in model output, stream events, and renderer lookup.
schemaComponentSchema<TSpec>Yesn/aA Zod schema or JSON Schema describing valid component specs.
jsonSchemaJsonSchemaNon/aExplicit JSON Schema to put in the manifest. When provided, it overrides the schema generated from Zod.
projectionProjectionTemplatesYesn/aTemplates that turn the component spec into portable text. Currently supports text.
modelComponentModelHintsNon/aDescription, usage guidance, and examples included in server prompts.
metadataJsonObjectNon/aSerializable application metadata attached to the component manifest.

MFUIComponentDefinition<TSpec>

Component definition returned by defineMFUIComponent().

Property or MethodTypeDescription
namestringComponent name copied from the definition input.
manifestComponentManifestSerializable component manifest.
project(spec)(spec: TSpec) => ProjectionRenders the projection templates for a spec.
validate(spec)(spec: unknown) => ValidationResultValidates specs locally when schema is a Zod schema.
toManifest()() => ComponentManifestReturns the serializable manifest.

ComponentSchema<TSpec>

Schema input accepted by defineMFUIComponent().

Shape

ts
type ComponentSchema<TSpec> = ZodTypeAny | JsonSchema

Notes

Pass a Zod schema when you want local client-side validation through definition.validate(). Pass a JSON Schema when the schema is already available in serializable form.

ComponentModelHints

PropertyTypeRequiredDefaultDescription
descriptionstringYesn/aModel-facing description of what the component represents.
whenToUsestringNon/aModel-facing guidance for when the component is appropriate.
examplesArray<{ user: string; spec: unknown }>Non/aExample user requests and valid specs for prompting.

ComponentManifest

Serializable manifest for one component.

PropertyTypeRequiredDefaultDescription
namestringYesn/aStable component name.
schemaJsonSchemaYesn/aJSON Schema for the component spec.
projectionProjectionTemplatesYesn/aTemplates used to project the spec into text.
modelComponentModelHintsNon/aModel-facing hints used by server prompts.
metadataJsonObjectNon/aApplication metadata.

ProjectionTemplates

Template object used to render projections.

PropertyTypeRequiredDefaultDescription
textstringYesn/aMFUI semantic template that renders component specs to text.

Projection

Rendered projection object.

PropertyTypeRequiredDefaultDescription
textstringYesn/aDeterministic text representation of a component spec.

JsonSchema

JSON Schema object shape.

Shape

ts
type JsonSchema = JsonObject

JsonObject

JSON-compatible object shape.

Shape

ts
type JsonObject = Record<string, unknown>

ValidationResult

Validation success or failure union.

Shape

ts
type ValidationResult = ValidationSuccess | ValidationFailure

ValidationSuccess

Successful validation result.

PropertyTypeRequiredDefaultDescription
oktrueYesn/aSuccess discriminator.

ValidationFailure

Failed validation result.

PropertyTypeRequiredDefaultDescription
okfalseYesn/aFailure discriminator.
errorsstring[]Yesn/aValidation error messages.

isMFUIComponentDefinition()

Checks whether an unknown value has the shape of an MFUI component definition.

Import

ts
import { isMFUIComponentDefinition } from '@mfui/client';

Signature

ts
function isMFUIComponentDefinition(
  value: unknown,
): value is MFUIComponentDefinition

Parameters

NameTypeRequiredDefaultDescription
valueunknownYesn/aValue to inspect.

Returns

TypeDescription
booleantrue when the value is an object with manifest, project, and toManifest properties.

createMFUIManifest()

Creates the manifest payload usually sent from the frontend to the backend.

Import

ts
import { createMFUIManifest } from '@mfui/client';

Signature

ts
function createMFUIManifest(
  input: CreateMFUIManifestInput,
): MFUIManifest

Parameters

NameTypeRequiredDefaultDescription
inputCreateMFUIManifestInputYesn/aManifest construction input.

Returns

TypeDescription
MFUIManifestSerializable manifest with a components array and optional layouts array.

Example

ts
import { createMFUIManifest } from '@mfui/client';
import {
  alertDefinition,
  timelineDefinition,
  formDefinition,
  barChartDefinition,
  lineChartDefinition,
  pieChartDefinition,
} from '@mfui/client/definitions';
import { columnsLayout } from '@mfui/client/layouts';

const mfui = createMFUIManifest({
  components: [
    alertDefinition,
    timelineDefinition,
    formDefinition,
    barChartDefinition,
    lineChartDefinition,
    pieChartDefinition,
  ],
  layouts: [columnsLayout],
});

await fetch('/api/chat', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ messages, mfui }),
});

Notes

This helper normalizes component and layout inputs but does not validate the full manifest. Use server-side validation before trusting model-generated component specs.

CreateMFUIManifestInput

Input object for createMFUIManifest().

PropertyTypeRequiredDefaultDescription
componentsreadonly ComponentManifestInput[]Yesn/aComponent definitions, raw component manifests, or objects with toManifest().
layoutsreadonly LayoutManifestInput[]Non/aBuiltin layout definitions, raw layout manifests, or objects with toManifest().

MFUIManifest

Serializable request manifest that lists the components available to a model request.

PropertyTypeRequiredDefaultDescription
componentsComponentManifest[]Yesn/aComponents available to the current request.
layoutsLayoutManifest[]Non/aBuiltin layouts available to the current request.

ComponentManifestInput

Component input accepted by helpers that can work with either raw manifests or objects that expose a manifest.

Shape

ts
type ComponentManifestInput = ComponentManifest | ComponentManifestProvider

ComponentManifestProvider

Object that can return a component manifest.

Property or MethodTypeDescription
toManifest()() => ComponentManifestReturns the serializable component manifest.

LayoutManifest

Serializable manifest for one builtin layout.

PropertyTypeRequiredDefaultDescription
namestringYesn/aStable layout name.
modelComponentModelHintsNon/aModel-facing layout guidance used by server prompts.
metadataJsonObjectNon/aApplication metadata.

LayoutManifestInput

Layout input accepted by helpers that can work with either raw manifests or objects that expose a manifest.

Shape

ts
type LayoutManifestInput = LayoutManifest | LayoutManifestProvider

LayoutManifestProvider

Object that can return a layout manifest.

Property or MethodTypeDescription
toManifest()() => LayoutManifestReturns the serializable layout manifest.

readMFUIMessage()

Reads an MFUI semantic stream and resolves to the final projected message.

Import

ts
import { readMFUIMessage } from '@mfui/client';

Signature

ts
function readMFUIMessage(
  source: MFUIStreamSource,
): Promise<ProjectedMessage | undefined>

Parameters

NameTypeRequiredDefaultDescription
sourceMFUIStreamSourceYesn/aA Response, a ReadableStream<Uint8Array>, or null.

Returns

TypeDescription
Promise<ProjectedMessage | undefined>The last completed projected message, or undefined when the stream is empty or missing.

Example

ts
import { readMFUIMessage } from '@mfui/client';

const response = await fetch('/api/chat', {
  method: 'POST',
  headers: { Accept: 'text/event-stream' },
});

const message = await readMFUIMessage(response);
console.log(message?.portableText);

Throws

Throws when a Response is not OK, when the stream contains an MFUI error event, or when the semantic stream data cannot be parsed.

streamMFUIMessage()

Reads an MFUI semantic stream as progressive projected message snapshots.

Import

ts
import { streamMFUIMessage } from '@mfui/client';

Signature

ts
function streamMFUIMessage(
  source: MFUIStreamSource,
): AsyncIterable<ProjectedMessage>

Parameters

NameTypeRequiredDefaultDescription
sourceMFUIStreamSourceYesn/aA Response, a ReadableStream<Uint8Array>, or null.

Returns

TypeDescription
AsyncIterable<ProjectedMessage>Yields projected message snapshots as semantic stream events arrive.

Example

ts
import { streamMFUIMessage } from '@mfui/client';

for await (const message of streamMFUIMessage(response)) {
  renderAssistantMessage(message);
}

Throws

Throws for the same error cases as readMFUIMessage().

MFUIStreamSource

Stream source accepted by readMFUIMessage() and streamMFUIMessage().

Shape

ts
type MFUIStreamSource = Response | ReadableStream<Uint8Array> | null

Notes

When a Response is provided, the client checks response.ok before reading the body.

ProjectedMessage<TSpec>

Projected message with portableText.

PropertyTypeRequiredDefaultDescription
idstringYesn/aMessage id.
partsArray<ProjectedMessagePart<TSpec>>Yesn/aProjected text, component, and layout parts.
portableTextstringYesn/aDeterministic text for copy, storage, search, and future model context.
metadataJsonObjectNon/aApplication metadata copied from the raw message.

ProjectedMessagePart<TSpec>

Union of projected text, component, and layout parts.

Shape

ts
type ProjectedMessagePart<TSpec = unknown> =
  | TextPart
  | ProjectedComponentPart<TSpec>
  | ProjectedLayoutPart<TSpec>

ProjectedComponentPart<TSpec>

Component part with a required text projection.

Shape

ts
type ProjectedComponentPart<TSpec = unknown> =
  Omit<ComponentPart<TSpec>, 'projection'> & {
    projection: Projection
  }

ProjectedLayoutPart<TSpec>

Layout part with projected cells and a required text projection.

Shape

ts
type ProjectedLayoutPart<TSpec = unknown> = {
  id: string
  type: 'layout'
  layout: 'mfui.columns'
  columns: Array<TextPart | ProjectedComponentPart<TSpec>>
  projection: Projection
  metadata?: JsonObject
}

TextPart

Plain text message part.

PropertyTypeRequiredDefaultDescription
idstringYesn/aStable part id.
type'text'Yesn/aPart discriminator.
contentstringYesn/aText content.
metadataJsonObjectNon/aApplication metadata.

ComponentPart<TSpec>

Message part that references a component and spec.

PropertyTypeRequiredDefaultDescription
idstringYesn/aStable part id.
type'component'Yesn/aPart discriminator.
componentstringYesn/aComponent name.
specTSpecYesn/aComponent spec data.
projectionProjectionNon/aExisting projection. When missing, helpers can render it from the manifest.
metadataJsonObjectNon/aApplication metadata.

messageToPortableText()

Converts projected message parts into deterministic text.

Import

ts
import { messageToPortableText } from '@mfui/client';

Signature

ts
function messageToPortableText(
  partsOrMessage: ProjectedMessagePart[] | ProjectedMessage,
): string

Parameters

NameTypeRequiredDefaultDescription
partsOrMessageProjectedMessagePart[] | ProjectedMessageYesn/aProjected parts or a full projected message.

Returns

TypeDescription
stringText parts, component projection.text values, and layout projection.text values joined with blank lines. Empty chunks are omitted.

projectMessage()

Projects every component part, including component cells inside layout parts, in a raw message and returns a projected message.

Import

ts
import { projectMessage } from '@mfui/client';

Signature

ts
function projectMessage<TSpec = unknown>(
  message: MessageIR<TSpec>,
  options: ProjectMessageOptions,
): ProjectedMessage<TSpec>

Parameters

NameTypeRequiredDefaultDescription
messageMessageIR<TSpec>Yesn/aMessage containing text, component, and layout parts.
optionsProjectMessageOptionsYesn/aProjection options.

Returns

TypeDescription
ProjectedMessage<TSpec>Message with component projections and portableText.

Throws

Throws when a component part references a component that is not included in options.components.

ProjectMessageOptions

Options for projectMessage().

PropertyTypeRequiredDefaultDescription
componentsComponentManifestInput[]Yesn/aManifests used to project component parts.

MessageIR<TSpec>

Raw message with text, component, and layout parts.

PropertyTypeRequiredDefaultDescription
idstringYesn/aMessage id.
partsArray<MessagePart<TSpec>>Yesn/aText, component, and layout message parts.
metadataJsonObjectNon/aApplication metadata.

MessagePart<TSpec>

Union of text, component, and layout message parts.

Shape

ts
type MessagePart<TSpec = unknown> =
  | TextPart
  | ComponentPart<TSpec>
  | LayoutPart<TSpec>

LayoutPart<TSpec>

Raw builtin layout message part.

Shape

ts
type LayoutPart<TSpec = unknown> = {
  id: string
  type: 'layout'
  layout: 'mfui.columns'
  columns: Array<TextPart | ComponentPart<TSpec>>
  projection?: Projection
  metadata?: JsonObject
}

createTextPart()

Creates a text part for a message.

Import

ts
import { createTextPart } from '@mfui/client';

Signature

ts
function createTextPart(
  content: string,
  options?: { id?: string },
): TextPart

Parameters

NameTypeRequiredDefaultDescription
contentstringYesn/aText content for the part.
options{ id?: string }No{}Optional part options.
options.idstringNogenerated txt_* idStable part id.

Returns

TypeDescription
TextPartMessage part with type: 'text'.

createComponentPart()

Creates a component part for a message.

Import

ts
import { createComponentPart } from '@mfui/client';

Signature

ts
function createComponentPart<TSpec>(
  component: string,
  spec: TSpec,
  options?: { id?: string },
): ComponentPart<TSpec>

Parameters

NameTypeRequiredDefaultDescription
componentstringYesn/aComponent name.
specTSpecYesn/aComponent spec data.
options{ id?: string }No{}Optional part options.
options.idstringNogenerated cmp_* idStable part id.

Returns

TypeDescription
ComponentPart<TSpec>Message part with type: 'component'.

renderProjection()

Renders every projection template for a spec.

Import

ts
import { renderProjection } from '@mfui/client';

Signature

ts
function renderProjection(
  templates: ProjectionTemplates,
  data: unknown,
  options?: TemplateRenderOptions,
): Projection

Parameters

NameTypeRequiredDefaultDescription
templatesProjectionTemplatesYesn/aProjection template object. Currently contains text.
dataunknownYesn/aData object used as the template context.
optionsTemplateRenderOptionsNo{}Template rendering options.
options.validateSubsetbooleanNotrueWhether to reject unsupported MFUI template tags and filters before rendering.

Returns

TypeDescription
ProjectionRendered projection object. Currently contains text.

Throws

Throws when template validation fails or template rendering fails.

renderSemanticTemplate()

Renders one MFUI semantic template string.

Import

ts
import { renderSemanticTemplate } from '@mfui/client';

Signature

ts
function renderSemanticTemplate(
  template: string,
  data: unknown,
  options?: TemplateRenderOptions,
): string

Parameters

NameTypeRequiredDefaultDescription
templatestringYesn/aMFUI semantic template.
dataunknownYesn/aData object used as the template context.
optionsTemplateRenderOptionsNo{}Template rendering options.
options.validateSubsetbooleanNotrueWhether to reject unsupported MFUI template tags and filters before rendering.

Returns

TypeDescription
stringRendered text.

validateSemanticTemplate()

Validates that a template uses only the MFUI-supported Liquid subset.

Import

ts
import { validateSemanticTemplate } from '@mfui/client';

Signature

ts
function validateSemanticTemplate(template: string): void

Parameters

NameTypeRequiredDefaultDescription
templatestringYesn/aTemplate to validate.

Returns

TypeDescription
voidReturns nothing when the template is valid.

Supported Template Subset

FeatureSupported values
Tagsfor, endfor, if, endif, unless, endunless, else, elsif
Filtersdefault, join, truncate, escapeMarkdown, strip, size

Throws

Throws when the template contains unsupported tags or filters.

TemplateRenderOptions

Options for renderProjection() and renderSemanticTemplate().

PropertyTypeRequiredDefaultDescription
validateSubsetbooleanNotrueWhether to reject unsupported MFUI template tags and filters before rendering.

createComponentRegistry()

Creates a small registry for component manifests.

Import

ts
import { createComponentRegistry } from '@mfui/client';

Signature

ts
function createComponentRegistry(
  components?: ComponentManifestInput[],
): ComponentRegistry

Parameters

NameTypeRequiredDefaultDescription
componentsComponentManifestInput[]No[]Initial components to register.

Returns

TypeDescription
ComponentRegistryRegistry with register(), get(), has(), and manifests() methods.

Notes

Registering the same component name again replaces the previous manifest.

ComponentRegistry

In-memory registry returned by createComponentRegistry().

MethodTypeDescription
register(component)(component: ComponentManifestInput) => ComponentRegistryRegisters a component and returns the same registry for chaining.
get(name)(name: string) => ComponentManifest | undefinedGets a manifest by component name.
has(name)(name: string) => booleanChecks whether a component name is registered.
manifests()() => ComponentManifest[]Returns registered manifests.

getComponentManifest()

Returns the raw manifest from either a manifest object or provider object.

Import

ts
import { getComponentManifest } from '@mfui/client';

Signature

ts
function getComponentManifest(
  component: ComponentManifestInput,
): ComponentManifest

Parameters

NameTypeRequiredDefaultDescription
componentComponentManifestInputYesn/aA raw component manifest or an object with toManifest().

Returns

TypeDescription
ComponentManifestNormalized component manifest.

projectSpecWithManifest()

Projects one component spec using one manifest.

Import

ts
import { projectSpecWithManifest } from '@mfui/client';

Signature

ts
function projectSpecWithManifest(
  manifest: ComponentManifest,
  spec: unknown,
): Projection

Parameters

NameTypeRequiredDefaultDescription
manifestComponentManifestYesn/aManifest containing projection templates.
specunknownYesn/aComponent spec to project.

Returns

TypeDescription
ProjectionRendered projection.

createMessageAccumulator()

Creates an event accumulator for code that already has MFUI semantic stream events and wants to manage message state manually.

Import

ts
import { createMessageAccumulator } from '@mfui/client';

Signature

ts
function createMessageAccumulator(): MessageAccumulator

Parameters

This function does not take parameters.

Returns

TypeDescription
MessageAccumulatorStateful accumulator for current and completed projected messages.

Example

ts
import { createMessageAccumulator } from '@mfui/client';

const accumulator = createMessageAccumulator();

for await (const event of events) {
  const state = accumulator.apply(event);
  renderMessages(state.messages, state.currentMessage);
}

Throws

Throws if a stream event arrives before message.start, or if an error event is applied.

MessageAccumulator

Stateful accumulator returned by createMessageAccumulator().

Property or MethodTypeDescription
messagesreadonly ProjectedMessage[]Completed messages.
apply(event)(event: SemanticStreamEvent) => MessageAccumulatorStateApplies one event and returns the latest state.
snapshot()() => MessageAccumulatorStateReturns current accumulator state without applying a new event.
getPortableText(messageId)(messageId: string) => string | undefinedFinds portable text for a current or completed message.
findMessage(messageId)(messageId: string) => ProjectedMessage | undefinedFinds a current or completed message.

MessageAccumulatorState

Snapshot returned by message accumulator methods.

PropertyTypeRequiredDefaultDescription
messagesProjectedMessage[]Yesn/aCompleted messages.
currentMessageProjectedMessageNon/aCurrent in-progress projected message.

readSemanticStream()

Low-level parser for MFUI SSE semantic events.

Import

ts
import { readSemanticStream } from '@mfui/client';

Signature

ts
function readSemanticStream(
  body: ReadableStream<Uint8Array> | null,
): AsyncIterable<SemanticStreamEvent>

Parameters

NameTypeRequiredDefaultDescription
bodyReadableStream<Uint8Array> | nullYesn/aSSE response body.

Returns

TypeDescription
AsyncIterable<SemanticStreamEvent>Parsed semantic stream events. Returns an empty iterable when body is null.

SemanticStreamEvent<TSpec>

Union of all MFUI semantic stream events.

Shape

ts
type SemanticStreamEvent<TSpec = unknown> =
  | MessageStartEvent
  | TextDeltaEvent
  | ComponentSnapshotEvent<TSpec>
  | LayoutSnapshotEvent<TSpec>
  | MessageEndEvent
  | ErrorEvent

MessageStartEvent

Semantic stream event that starts a message.

PropertyTypeRequiredDefaultDescription
type'message.start'Yesn/aEvent discriminator.
idstringYesn/aMessage id.
createdAtstringNon/aOptional creation timestamp.

TextDeltaEvent

Semantic stream event that appends text to a text part.

PropertyTypeRequiredDefaultDescription
type'text.delta'Yesn/aEvent discriminator.
partIdstringYesn/aText part id.
textstringYesn/aText chunk to append.

ComponentSnapshotEvent<TSpec>

Semantic stream event for one complete component snapshot.

PropertyTypeRequiredDefaultDescription
type'component.snapshot'Yesn/aEvent discriminator.
partIdstringYesn/aComponent part id.
componentstringYesn/aComponent name.
specTSpecYesn/aComponent spec data.
projectionProjectionYesn/aText projection for the component.
metadataJsonObjectNon/aApplication metadata.

LayoutSnapshotEvent<TSpec>

Semantic stream event for one complete builtin layout snapshot.

PropertyTypeRequiredDefaultDescription
type'layout.snapshot'Yesn/aEvent discriminator.
partIdstringYesn/aLayout part id.
layout'mfui.columns'Yesn/aLayout name.
columnsArray<TextPart | ProjectedComponentPart<TSpec>>Yesn/aProjected column cells.
projectionProjectionYesn/aText projection for the layout.
metadataJsonObjectNon/aApplication metadata.

MessageEndEvent

Semantic stream event that finishes a message.

PropertyTypeRequiredDefaultDescription
type'message.end'Yesn/aEvent discriminator.
idstringYesn/aMessage id.
portableTextstringYesn/aFinal deterministic text for the message.
usage{ inputTokens?: number; outputTokens?: number }Non/aOptional model usage information.

ErrorEvent

Semantic stream event for a stream failure.

PropertyTypeRequiredDefaultDescription
type'error'Yesn/aEvent discriminator.
codestringYesn/aMachine-readable error code.
messagestringYesn/aHuman-readable error message.
recoverablebooleanNon/aWhether the error may be recoverable.