Skip to content

@mfui/server

@mfui/server is the server-side SDK for building MFUI prompts, parsing model output, validating component specs, and returning MFUI semantic SSE responses.

Most adapter packages use these primitives internally. Application servers use them directly when they want to build a custom model integration.

createMFUIPrompt()

Creates model instructions for the components and layouts available to the current request. The prompt tells the model how to emit normal text and when to insert <mfui> blocks.

Import

ts
import { createMFUIPrompt } from '@mfui/server';

Signature

ts
function createMFUIPrompt(mfui: MFUIManifest): string

Parameters

NameTypeRequiredDefaultDescription
mfuiMFUIManifestYesn/aComponents and layouts available for this model request. null and undefined are treated as disabled MFUI.

Returns

TypeDescription
stringPrompt text containing component descriptions, layout descriptions, JSON Schemas, examples, and MFUI block instructions. Returns an empty string when MFUI is disabled or has no components or layouts.

Example

ts
import { createMFUIPrompt } from '@mfui/server';

const system = [
  'You are a helpful assistant.',
  createMFUIPrompt(mfui),
].filter(Boolean).join('\n\n');

Throws

Throws MFUIServerError when a provided manifest has an invalid shape.

buildComponentCatalogText()

Builds only the component catalog portion of the MFUI prompt.

Import

ts
import { buildComponentCatalogText } from '@mfui/server';

Signature

ts
function buildComponentCatalogText(mfui: MFUIManifest): string

Parameters

NameTypeRequiredDefaultDescription
mfuiMFUIManifestYesn/aComponents to list for the model. null and undefined are treated as disabled MFUI.

Returns

TypeDescription
stringHuman-readable component catalog text. Returns an empty string when there are no components.

buildLayoutCatalogText()

Builds only the layout catalog portion of the MFUI prompt.

Import

ts
import { buildLayoutCatalogText } from '@mfui/server';

Signature

ts
function buildLayoutCatalogText(mfui: MFUIManifest): string

Parameters

NameTypeRequiredDefaultDescription
mfuiMFUIManifestYesn/aBuiltin layouts to list for the model. null and undefined are treated as disabled MFUI.

Returns

TypeDescription
stringHuman-readable layout catalog text. Returns an empty string when there are no layouts.

MFUIManifest

Serializable manifest sent from the client to the server.

PropertyTypeRequiredDefaultDescription
componentsComponentManifest[]Yesn/aComponents available to the current model request.
layoutsArray<{ name: string; model?: { description: string; whenToUse?: string; examples?: Array<{ user: string; spec: unknown }> }; metadata?: JsonObject }>Non/aBuiltin layouts available to the current model request.

ComponentManifest

Serializable manifest for one component.

PropertyTypeRequiredDefaultDescription
namestringYesn/aStable component name used in model output, stream events, and renderers.
schemaJsonSchemaYesn/aJSON Schema for the component spec.
projection{ text: string }Yesn/aTemplate used to project a valid component spec into portable text.
model{ description: string; whenToUse?: string; examples?: Array<{ user: string; spec: unknown }> }Non/aModel-facing component guidance used by createMFUIPrompt().
metadataJsonObjectNon/aSerializable application metadata.

JsonSchema

JSON Schema object used to validate component specs on the server.

Shape

ts
type JsonSchema = JsonObject

JsonObject

JSON-compatible object shape.

Shape

ts
type JsonObject = Record<string, unknown>

createMFUIStreamWriter()

Creates an MFUI semantic SSE writer. Use this when you are building a custom provider adapter or writing server-side tests around MFUI streams.

Import

ts
import { createMFUIStreamWriter } from '@mfui/server';

Signature

ts
function createMFUIStreamWriter(
  mfui: MFUIManifest,
  options?: MFUIStreamWriterOptions,
): MFUIStreamWriter

Parameters

NameTypeRequiredDefaultDescription
mfuiMFUIManifestYesn/aManifest used to validate component snapshots and render projections.
optionsMFUIStreamWriterOptionsNo{}Writer options.

Returns

TypeDescription
MFUIStreamWriterStateful writer that emits MFUI semantic SSE events and exposes a Response.

Example

ts
import {
  createMFUIBlockParser,
  createMFUIStreamWriter,
} from '@mfui/server';

const writer = createMFUIStreamWriter(mfui);
const parser = createMFUIBlockParser(mfui, writer);

parser.write('Here is the plan:\n\n');
parser.write('<mfui>{"component":"app.task_list","spec":{"title":"Next","items":[]}}</mfui>');
parser.close();

return writer.response();

Throws

Throws MFUIServerError when a provided manifest has an invalid shape.

MFUIStreamWriterOptions

Options for createMFUIStreamWriter().

PropertyTypeRequiredDefaultDescription
idstringNoGenerated msg_* idMessage id used in emitted message.start and message.end events.

MFUIStreamWriter

Writer returned by createMFUIStreamWriter().

MethodTypeDescription
start()() => voidEmits message.start if the stream has not started yet. Called automatically by text(), component(), and end().
text(text, options)(text: string, options?: { partId?: string }) => voidEmits a text delta and appends it to the current projected message. Empty strings are ignored.
component(input)(input: MFUIComponentInput) => ProjectedComponentPartValidates a component spec, renders its projection, emits component.snapshot, and returns the projected component part.
error(input)(input: MFUIStreamErrorInput) => voidEmits an MFUI error event and closes the stream.
end(options)(options?: MFUIStreamWriterEndOptions) => voidEmits message.end with final portable text and closes the stream.
response(init)(init?: ResponseInit) => ResponseReturns a text/event-stream Response backed by the writer stream.
snapshot()() => ProjectedMessage | undefinedReturns the current projected message, or undefined before the stream starts.

MFUIComponentInput

Input for MFUIStreamWriter.component().

PropertyTypeRequiredDefaultDescription
idstringNoGenerated cmp_* idComponent part id.
componentstringYesn/aComponent name. Must match a manifest component.
specunknownYesn/aComponent spec to validate and project.
metadataJsonObjectNon/aApplication metadata attached to the component part and stream event.

MFUIStreamWriterEndOptions

Options for MFUIStreamWriter.end().

PropertyTypeRequiredDefaultDescription
usage{ inputTokens?: number; outputTokens?: number }Non/aOptional model usage included in the final message.end event.

MFUIStreamErrorInput

Input for MFUIStreamWriter.error().

PropertyTypeRequiredDefaultDescription
codestringYesn/aMachine-readable error code.
messagestringYesn/aHuman-readable error message.
recoverablebooleanNon/aWhether the error may be recoverable by the client.

ProjectedMessage

Projected assistant message shape used by MFUIStreamWriter.snapshot() and adapter onMessage callbacks.

PropertyTypeRequiredDefaultDescription
idstringYesn/aMessage id.
partsProjectedMessagePart[]Yesn/aProjected text, component, and layout parts.
portableTextstringYesn/aDeterministic text representation of the message.
metadataJsonObjectNon/aApplication metadata.

createMFUIBlockParser()

Creates a parser that converts provider text output containing <mfui> blocks into MFUI stream writer calls.

Import

ts
import { createMFUIBlockParser } from '@mfui/server';

Signature

ts
function createMFUIBlockParser(
  mfui: MFUIManifest,
  writer: MFUIStreamWriter,
  options?: MFUIBlockParserOptions,
): MFUIBlockParser

Parameters

NameTypeRequiredDefaultDescription
mfuiMFUIManifestYesn/aCurrent manifest. Reserved for parity with writer construction.
writerMFUIStreamWriterYesn/aWriter that receives parsed text, component, and layout calls.
optionsMFUIBlockParserOptionsNo{}Parser options.

Returns

TypeDescription
MFUIBlockParserIncremental parser for provider text chunks.

Throws

Throws MFUIServerError when a malformed or invalid MFUI block is encountered. The writer also emits an error event before the exception is thrown.

MFUIBlockParserOptions

Options for createMFUIBlockParser().

PropertyTypeRequiredDefaultDescription
maxBlockLengthnumberNo65536Maximum number of characters allowed inside one open <mfui> block.

MFUIBlockParser

Incremental parser returned by createMFUIBlockParser().

MethodTypeDescription
write(text)(text: string) => voidProcesses the next provider text chunk. Normal text is sent to writer.text(). Complete MFUI blocks are parsed and sent to writer.component().
flush()() => voidFlushes buffered normal text without ending the writer. Throws if an MFUI block is still open.
close(options)(options?: MFUIStreamWriterEndOptions) => voidFlushes buffered text and calls writer.end(options).

MFUI_BLOCK_TAG

Name of the XML-style tag that wraps MFUI component payloads in model text.

Import

ts
import { MFUI_BLOCK_TAG } from '@mfui/server';

Value

ts
const MFUI_BLOCK_TAG = 'mfui'

parseMFUIBlockPayload()

Parses the JSON payload inside an <mfui> block.

Import

ts
import { parseMFUIBlockPayload } from '@mfui/server';

Signature

ts
function parseMFUIBlockPayload(payload: string): MFUIComponentInput

Parameters

NameTypeRequiredDefaultDescription
payloadstringYesn/aRaw JSON string between <mfui> and </mfui>.

Returns

TypeDescription
MFUIComponentInputComponent name and spec parsed from the block payload.

Throws

Throws MFUIServerError when the payload is not valid JSON, not an object, or does not contain component and spec.

validateMFUIManifest()

Validates the shape of an MFUI manifest.

Import

ts
import { validateMFUIManifest } from '@mfui/server';

Signature

ts
function validateMFUIManifest(mfui: MFUIManifest): ValidationResult

Parameters

NameTypeRequiredDefaultDescription
mfuiMFUIManifestYesn/aManifest to validate.

Returns

TypeDescription
ValidationResult{ ok: true } when valid, otherwise { ok: false, errors }.

assertValidMFUIManifest()

Validates a manifest and throws when it is invalid.

Import

ts
import { assertValidMFUIManifest } from '@mfui/server';

Signature

ts
function assertValidMFUIManifest(mfui: MFUIManifest): void

Parameters

NameTypeRequiredDefaultDescription
mfuiMFUIManifestYesn/aManifest to validate.

Returns

TypeDescription
voidReturns nothing when valid.

Throws

Throws MFUIServerError with code invalid_component_manifest when invalid.

validateSpecWithManifest()

Validates one component spec against one component manifest.

Import

ts
import { validateSpecWithManifest } from '@mfui/server';

Signature

ts
function validateSpecWithManifest(
  manifest: ComponentManifest,
  spec: unknown,
): ValidationResult

Parameters

NameTypeRequiredDefaultDescription
manifestComponentManifestYesn/aComponent manifest containing the JSON Schema.
specunknownYesn/aComponent spec to validate.

Returns

TypeDescription
ValidationResultValidation result from AJV.

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.

MFUIMessageHandler

Callback type used by adapter onMessage options.

Shape

ts
type MFUIMessageHandler = (message: ProjectedMessage) => void | Promise<void>

MFUIErrorHandler

Callback type used by adapter onError options.

Shape

ts
type MFUIErrorHandler = (error: unknown) => void | Promise<void>

MFUIResponseHooks

Shared callback object shape used by adapter response options.

PropertyTypeRequiredDefaultDescription
onMessageMFUIMessageHandlerNon/aCalled with the final projected message after the MFUI response is fully processed.
onErrorMFUIErrorHandlerNon/aCalled when provider stream processing or MFUI block parsing fails.

MFUIServerError

Error shape thrown by server validation, prompt, writer, and block parser helpers.

PropertyTypeRequiredDefaultDescription
messagestringYesn/aHuman-readable error message from Error.
codestringYesn/aMachine-readable MFUI error code.
statusnumberYes400 for MFUI validation errorsHTTP-oriented status code.

SemanticStreamEvent

Union of MFUI semantic SSE events emitted by MFUIStreamWriter.

Shape

ts
type SemanticStreamEvent =
  | { type: 'message.start'; id: string; createdAt?: string }
  | { type: 'text.delta'; partId: string; text: string }
  | { type: 'component.snapshot'; partId: string; component: string; spec: unknown; projection: { text: string }; metadata?: JsonObject }
  | { type: 'layout.snapshot'; partId: string; layout: 'mfui.columns'; columns: unknown[]; projection: { text: string }; metadata?: JsonObject }
  | { type: 'message.end'; id: string; portableText: string; usage?: { inputTokens?: number; outputTokens?: number } }
  | { type: 'error'; code: string; message: string; recoverable?: boolean }