CopilotKit

Fixed Schema A2UI

Pre-defined A2UI schema with dynamic data. The fastest approach — no LLM schema generation needed.


"use client";/** * A2UI Fixed Schema — Mastra port. * * Fixed-schema flavor: the component tree lives on the frontend catalog, * and the agent streams *data* into the data model. This Mastra port * reuses the shared `weatherAgent` (aliased as `a2ui-fixed-schema`) so * the same `generate_a2ui` tool drives rendering. Because the schema is * frontend-owned, the agent's job is limited to filling in the bound * fields (origin, destination, airline, price, etc.). * * Reference: *   https://docs.copilotkit.ai/integrations/langgraph/generative-ui/a2ui/fixed-schema */import React from "react";import { CopilotKit } from "@copilotkit/react-core";import {  CopilotChat,  useConfigureSuggestions,} from "@copilotkit/react-core/v2";import { fixedCatalog } from "./a2ui/catalog";export default function A2UIFixedSchemaDemo() {  return (    <CopilotKit      runtimeUrl="/api/copilotkit"      agent="a2ui-fixed-schema"      a2ui={{ catalog: fixedCatalog }}    >      <div className="flex justify-center items-center h-screen w-full">        <div className="h-full w-full max-w-4xl">          <Chat />        </div>      </div>    </CopilotKit>  );}function Chat() {  useConfigureSuggestions({    suggestions: [      {        title: "Find SFO → JFK",        message: "Find me a flight from SFO to JFK on United for $289.",      },    ],    available: "always",  });  return (    <CopilotChat agentId="a2ui-fixed-schema" className="h-full rounded-2xl" />  );}

In the fixed-schema approach, you design the UI schema once (by hand, or using the A2UI Composer) and keep it on the agent side. The agent tool only provides the data; the surface appears instantly when the tool returns because nothing has to be generated at runtime.

How the schema is delivered to the runtime is the only thing that varies between integrations:

  • Schema-loading (langgraph-python, langgraph-typescript, langgraph-fastapi, llamaindex, crewai-crews, pydantic-ai, ms-agent-python, google-adk) — the schema is saved as a .json file next to the agent and loaded once at startup.
  • Schema-inline (spring-ai, ms-agent-dotnet) — the schema is declared inline as a typed literal in source. The host language doesn't ship a load_schema JSON loader, so the structure is compiled in directly.
  • LLM-driven (mastra, strands) — the agent runs a secondary LLM call to produce the operations container per-request. The catalog is still fixed; the schema is generated on demand.

Ask about a flight and the agent renders a fully structured card from a pre-defined schema:

How it works#

  1. The schema is made available to the agent — either loaded from a JSON file at startup, declared inline, or generated per-request, depending on the integration.
  2. The agent's display_flight tool receives data from the primary LLM (origin / destination / airline / price).
  3. The tool returns a2ui.render(...) with createSurface + updateComponents + updateDataModel operations.
  4. The A2UI middleware intercepts the tool result and the frontend renders the surface using the matching 5-component client catalog (Title, Airport, Arrow, AirlineBadge, PriceTag, plus the built-ins).

Compositional schemas#

The example below ships a flight card assembled compositionally from small sub-components rather than one monolithic FlightCard:

Card
 └─ Column
     ├─ Title        ("Flight Details")
     ├─ Row          (Airport → Arrow → Airport)
     ├─ Row          (AirlineBadge · PriceTag)
     └─ Button       (Book)

That tree lives backend-side — as a JSON file, an inline literal, or a per-request LLM output, depending on the integration. Components without data bindings (like Title or Arrow) carry their value inline; components bound to the LLM's data (like Airport) reference fields via JSON Pointer paths such as { "path": "/origin" }. The A2UI binder resolves those paths before the React renderer runs, so renderer props are typed as their resolved values (plain z.string(), not a path-or-literal union).

The 5-component custom catalog#

The frontend catalog declares just the domain-specific primitives (Title, Airport, Arrow, AirlineBadge, PriceTag) and merges in CopilotKit's basic catalog (Card, Column, Row, Text, Button, …) via includeBasicCatalog: true.

Declare the component definitions#

Each component declares its props as a Zod schema. Props are the resolved values, never the path expressions:

definitions.ts
import { z } from "zod";import type { CatalogDefinitions } from "@copilotkit/a2ui-renderer";/** * Dynamic string: literal OR a data-model path binding. The GenericBinder * resolves path bindings to the actual value at render time. */const DynString = z.union([z.string(), z.object({ path: z.string() })]);export const flightDefinitions = {  Title: {    description: "A prominent heading for the flight card.",    props: z.object({      text: DynString,    }),  },  Airport: {    description: "A 3-letter airport code, displayed large.",    props: z.object({      code: DynString,    }),  },  Arrow: {    description: "A right-pointing arrow used between airports.",    props: z.object({}),  },  AirlineBadge: {    description: "A pill-styled airline name tag.",    props: z.object({      name: DynString,    }),  },  PriceTag: {    description: "A stylized price display (e.g. '$289').",    props: z.object({      amount: DynString,    }),  },  /**   * Button override: swaps in an ActionButton renderer that tracks   * its own `done` state so clicking "Book flight" visually updates to   * a "Booked ✓" confirmation. The basic catalog's Button is stateless,   * so without this override the click fires the action but the button   * looks unchanged. Mirrors the pattern in beautiful-chat   * (src/app/demos/beautiful-chat/declarative-generative-ui/renderers.tsx).   */  Button: {    description:      "An interactive button with an action event. Use 'child' with a Text component ID for the label. After click, the button shows a confirmation state.",    props: z.object({      child: z        .string()        .describe(          "The ID of the child component (e.g. a Text component for the label).",        ),      variant: z.enum(["primary", "secondary", "ghost"]).optional(),      // Union with { event } so GenericBinder resolves this as ACTION → callable () => void.      action: z        .union([          z.object({            event: z.object({              name: z.string(),              context: z.record(z.any()).optional(),            }),          }),          z.null(),        ])        .optional(),    }),  },} satisfies CatalogDefinitions;

Implement the React renderers#

TypeScript enforces that the renderer map's keys and prop shapes match the definitions exactly, so refactors stay safe:

renderers.tsx
export const flightRenderers: CatalogRenderers<FlightDefinitions> = {  Title: ({ props: rawProps }) => {    const props = rawProps as Record<string, any>;    return (      <div        style={{          fontSize: "1.15rem",          fontWeight: 600,          color: "#010507",        }}      >        {props.text}      </div>    );  },  Airport: ({ props: rawProps }) => {    const props = rawProps as Record<string, any>;    return (      <span        style={{          fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",          fontSize: "1.5rem",          fontWeight: 600,          letterSpacing: "0.05em",          color: "#010507",        }}      >        {props.code}      </span>    );  },  Arrow: () => <span style={{ color: "#AFAFB7", fontSize: "1.5rem" }}>→</span>,  AirlineBadge: ({ props: rawProps }) => {    const props = rawProps as Record<string, any>;    return (      <span        style={{          display: "inline-block",          padding: "2px 10px",          background: "rgba(190, 194, 255, 0.15)",          color: "#010507",          border: "1px solid #BEC2FF",          borderRadius: 999,          fontSize: "0.75rem",          fontWeight: 600,          letterSpacing: "0.08em",          textTransform: "uppercase",        }}      >        {props.name}      </span>    );  },  PriceTag: ({ props: rawProps }) => {    const props = rawProps as Record<string, any>;    return (      <span        style={{          fontWeight: 600,          fontSize: "1.1rem",          color: "#189370",          fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",        }}      >        {props.amount}      </span>    );  },  /**   * Button override: the basic catalog's Button is stateless. This   * stateful version lets clicking "Book flight" transition to   * "Booked ✓" without a round-trip to the agent.   */  Button: ({ props, children }) => {    return (      <ActionButton        label="Book flight"        doneLabel="Booked"        action={(props as Record<string, any>).action}      >        {(props as Record<string, any>).child          ? children((props as Record<string, any>).child)          : null}      </ActionButton>    );  },};

Wire the catalog#

createCatalog(..., { includeBasicCatalog: true }) merges the custom renderers with CopilotKit's built-ins so the schema can reference Card, Column, Row, Button alongside the domain primitives:

catalog.ts
import { createCatalog } from "@copilotkit/a2ui-renderer";import { flightDefinitions } from "./definitions";import { flightRenderers } from "./renderers";export const CATALOG_ID = "copilotkit://flight-fixed-catalog";export const fixedCatalog = createCatalog(flightDefinitions, flightRenderers, {  catalogId: CATALOG_ID,  includeBasicCatalog: true,});

Generate the schema dynamically#

Mastra and Strands take a different route: the agent tool runs a secondary LLM call with a forced tool choice that produces the operations container per-request. The frontend catalog is still fixed (same Title/Airport/Arrow/AirlineBadge/PriceTag primitives), but the schema is built on the fly. Schema construction and render emission happen in the same tool call:

index.ts
import { createTool } from "@mastra/core/tools";import { z } from "zod";import { openai } from "@ai-sdk/openai";import { generateText, tool as aiTool } from "ai";import {  getWeatherImpl,  queryDataImpl,  manageSalesTodosImpl,  getSalesTodosImpl,  scheduleMeetingImpl,  searchFlightsImpl,  generateA2uiImpl,  buildA2uiOperationsFromToolCall,} from "@copilotkit/showcase-shared-tools";// Re-export the dedicated tool sets defined in their own modules so the// barrel keeps a single import surface for callers under `@/mastra/tools`.export { setNotesTool } from "./shared-state-read-write";export {  researchAgentTool,  writingAgentTool,  critiqueAgentTool,} from "./subagents";export const weatherTool = createTool({  id: "get_weather",  description: "Get current weather for a location",  inputSchema: z.object({    location: z.string().describe("City name"),  }),  execute: async ({ location }) => JSON.stringify(getWeatherImpl(location)),});// Mock stock-price tool used by the headless-complete demo to exercise the// manual `useRenderTool` path alongside `get_weather`. Returns a fixed// payload so the StockCard renders deterministically without a real market// data API.export const stockPriceTool = createTool({  id: "get-stock-price",  description: "Get a mock current price for a stock ticker",  inputSchema: z.object({    ticker: z.string().describe("Stock ticker symbol, e.g. AAPL"),  }),  execute: async ({ ticker: rawTicker }) => {    const ticker = (rawTicker ?? "").toUpperCase();    return JSON.stringify({      ticker,      price_usd: 189.42,      change_pct: 1.27,    });  },});export const queryDataTool = createTool({  id: "query-data",  description: "Query financial database for chart data",  inputSchema: z.object({    query: z.string().describe("Natural language query"),  }),  execute: async ({ query }) => JSON.stringify(queryDataImpl(query)),});export const manageSalesTodosTool = createTool({  id: "manage-sales-todos",  description: "Create or update the sales todo list",  inputSchema: z.object({    todos: z      .array(        z.object({          id: z.string().optional(),          title: z.string(),          stage: z.string().optional(),          value: z.number().optional(),          dueDate: z.string().optional(),          assignee: z.string().optional(),          completed: z.boolean().optional(),        }),      )      .describe("Array of sales todo items"),  }),  execute: async ({ todos }) => JSON.stringify(manageSalesTodosImpl(todos)),});export const getSalesTodosTool = createTool({  id: "get-sales-todos",  description: "Get the current sales todo list",  inputSchema: z.object({    currentTodos: z      .array(        z.object({          id: z.string().optional(),          title: z.string().optional(),          stage: z.string().optional(),          value: z.number().optional(),          dueDate: z.string().optional(),          assignee: z.string().optional(),          completed: z.boolean().optional(),        }),      )      .optional()      .nullable()      .describe("Current todos if any"),  }),  execute: async ({ currentTodos }) =>    JSON.stringify(getSalesTodosImpl(currentTodos)),});export const scheduleMeetingTool = createTool({  id: "schedule-meeting",  description: "Schedule a meeting (requires user approval via HITL)",  inputSchema: z.object({    reason: z.string().describe("Reason for the meeting"),    durationMinutes: z.number().optional().describe("Duration in minutes"),  }),  execute: async ({ reason, durationMinutes }) =>    JSON.stringify(scheduleMeetingImpl(reason, durationMinutes)),});export const searchFlightsTool = createTool({  id: "search-flights",  description: "Search for available flights",  inputSchema: z.object({    flights: z      .array(        z.object({          airline: z.string(),          airlineLogo: z.string().optional(),          flightNumber: z.string(),          origin: z.string(),          destination: z.string(),          date: z.string(),          departureTime: z.string(),          arrivalTime: z.string(),          duration: z.string(),          status: z.string(),          statusColor: z.string().optional(),          price: z.string(),          currency: z.string().optional(),        }),      )      .describe("Array of flight results"),  }),  execute: async ({ flights }) => JSON.stringify(searchFlightsImpl(flights)),});// The `generate-a2ui` tool runs a secondary LLM call with a forced// `render_a2ui` tool, then converts that tool call's args into the// A2UI `a2ui_operations` container that the middleware forwards to// the frontend renderer. Mastra returns the operations as a JSON// string from the tool body; the catalog// (`copilotkit://generative-catalog`) resolves component names to// React renderers on the client.export const generateA2uiTool = createTool({  id: "generate-a2ui",  description: "Generate dynamic A2UI surface components",  inputSchema: z.object({    messages: z.array(z.record(z.unknown())).describe("Chat messages"),    contextEntries: z      .array(z.record(z.unknown()))      .optional()      .describe("Context entries"),  }),  execute: async ({ messages, contextEntries }) => {    const prep = generateA2uiImpl({      messages,      contextEntries,    });    const result = await generateText({      model: openai("gpt-4.1"),      system: prep.systemPrompt,      messages: prep.messages.map((m) => ({        role: (m.role as "user" | "assistant") ?? "user",        content: (m.content as string) ?? "",      })),      tools: {        render_a2ui: aiTool({          description: "Render a dynamic A2UI v0.9 surface.",          parameters: z.object({            surfaceId: z.string().describe("Unique surface identifier."),            catalogId: z.string().describe("The catalog ID."),            components: z              .array(z.record(z.unknown()))              .describe("A2UI v0.9 component array."),            data: z              .record(z.unknown())              .optional()              .describe("Optional initial data model."),          }),        }),      },      toolChoice: { type: "tool", toolName: "render_a2ui" },    });    const toolCall = result.toolCalls?.[0];    if (!toolCall) {      return JSON.stringify({ error: "LLM did not call render_a2ui" });    }    return JSON.stringify(      buildA2uiOperationsFromToolCall(toolCall.args as Record<string, unknown>),    );  },});

Why compositional beats monolithic#

A single big FlightCard component would be faster to write but would lock the design in place. Assembling the card from Card / Column / Row / Title / Airport / Arrow / AirlineBadge / PriceTag gives you:

  • Reusable primitives — the same Airport renderer works in search results, booking confirmations, and future seat maps.
  • Schema-level design iteration — re-arranging rows or swapping a badge requires only a JSON edit; the renderer code is untouched.
  • A2UI Composer compatibility — hand-written and Composer-built schemas share the same primitive vocabulary.

Registering the runtime#

On the TypeScript side, A2UI's middleware auto-detects the operations in any tool result, so even with a fixed schema, the minimum setup is a2ui: {}. The a2ui-fixed-schema cell happens to also keep injectA2UITool: true so the same agent can be pointed at dynamic-schema workflows later without re-configuring.

app/api/copilotkit/route.ts
const runtime = new CopilotRuntime({
  agents: { "a2ui-fixed-schema": agent },
  a2ui: { injectA2UITool: true, agents: ["a2ui-fixed-schema"] },
});

Action handlers (reference)#

The canonical reference pairs fixed schemas with action_handlers={...} to declare optimistic UI swaps (e.g. replacing the flight schema with BOOKED_SCHEMA when the user clicks "Book"). The Python SDK's a2ui.render does not yet accept action_handlers, so the cell omits them; the booked_schema.json sibling is retained so the swap can be wired up the moment the SDK exposes the handler kwarg.

When available, a button declares its action like this:

{
  "Button": {
    "label": "Book",
    "action": {
      "name": "book_flight",
      "context": [
        { "key": "flightNumber", "value": { "path": "/flightNumber" } },
        { "key": "price", "value": { "path": "/price" } }
      ]
    }
  }
}

And the Python tool matches it with a handler keyed by the action name (plus a "*" catch-all). Until the SDK lands, see the reference fixed-schema guide for the full pattern.

When should I use fixed schemas?#

  • The surface is well-known: flight cards, product tiles, order summaries, dashboards.
  • You want deterministic, designer-controlled UI. No LLM schema drift.
  • You want the fastest possible first paint; no secondary LLM call.

If the UI must adapt per prompt, reach for dynamic schemas instead.