State Rendering

Render your agent's state with your own React Native components in real time.

What is this?

State rendering lets you build UI that reflects your agent's state in real time. As your agent works and writes to its state, your app renders those changes: progress, drafts, or intermediate results.

When should I use this?

Use state rendering when you want to:

  • Show real-time progress (for example, "Researching... 2/5 complete")
  • Display drafts that update as the agent works
  • Build dashboards that reflect agent state
  • Render structured output outside the chat

How it works in code

Put shared state in the system prompt and tools

The demo exposes frontend preferences to Claude and gives the agent a tool for writing notes back into CopilotKit state. Keep the state contract small, typed, and mirrored by the UI components that read the same values.

shared-state-read-write-prompt.ts
export interface Preferences {
  name?: string;
  tone?: "formal" | "casual" | "playful";
  language?: string;
  interests?: string[];
}

export const SHARED_STATE_READ_WRITE_BASE_SYSTEM =
  "You are a helpful, concise assistant. " +
  "The user's preferences are supplied via shared state and will be " +
  "added to the system prompt at the start of every turn. Always " +
  "respect them. " +
  "When the user asks you to remember something, or when you observe " +
  "something worth surfacing in the UI, call `set_notes` with the " +
  "FULL updated list of short note strings (existing notes + new). " +
  "Each note should be under 120 characters.";

export const SET_NOTES_TOOL_SCHEMA = {
  name: "set_notes" as const,
  description:
    "Replace the notes array in shared state with the full updated list. " +
    "Use whenever the user asks you to 'remember' something, or when you " +
    "have an observation worth surfacing in the UI's notes panel. " +
    "Always pass the FULL notes list (existing + new), not a diff. " +
    "Keep each note short (< 120 chars).",
  input_schema: {
    type: "object" as const,
    properties: {
      notes: {
        type: "array",
        items: { type: "string" },
        description:
          "The complete updated notes array. Replaces the current notes.",
      },
    },
    required: ["notes"],
  },
};

function isStringArray(value: unknown): value is string[] {
  return Array.isArray(value) && value.every((v) => typeof v === "string");
}

/**
 * Coerce an arbitrary `unknown` (e.g. `input.state.preferences`) into a
 * sanitized `Preferences` object. We accept partial shapes — any field
 * may be missing — and silently drop fields that don't match the
 * expected types so a misbehaving frontend can't poison the prompt.
 */
export function coercePreferences(value: unknown): Preferences {
  if (!value || typeof value !== "object") return {};
  const v = value as Record<string, unknown>;
  const out: Preferences = {};
  if (typeof v.name === "string") out.name = v.name;
  if (v.tone === "formal" || v.tone === "casual" || v.tone === "playful") {
    out.tone = v.tone;
  }
  if (typeof v.language === "string") out.language = v.language;
  if (isStringArray(v.interests)) out.interests = v.interests;
  return out;
}

export function buildPreferencesPreamble(prefs: Preferences): string | null {
  const lines: string[] = [];
  if (prefs.name) lines.push(`- Name: ${prefs.name}`);
  if (prefs.tone) lines.push(`- Preferred tone: ${prefs.tone}`);
  if (prefs.language) lines.push(`- Preferred language: ${prefs.language}`);
  if (prefs.interests && prefs.interests.length > 0) {
    lines.push(`- Interests: ${prefs.interests.join(", ")}`);
  }
  if (lines.length === 0) return null;
  return [
    "The user has shared these preferences with you:",
    ...lines,
    "Tailor every response to these preferences. Address the user by name " +
      "when appropriate.",
  ].join("\n");
}

export function buildSharedStateReadWriteSystemPrompt(
  prefs: Preferences,
): string {
  const preamble = buildPreferencesPreamble(prefs);
  if (!preamble) return SHARED_STATE_READ_WRITE_BASE_SYSTEM;
  return `${SHARED_STATE_READ_WRITE_BASE_SYSTEM}\n\n${preamble}`;
}

Pass the schema to the shared agent loop

The route reads the current preferences and notes, then registers SET_NOTES_TOOL_SCHEMA with runAgenticLoop.

agent_server.ts
app.post(
  "/shared-state-read-write",
  async (req: Request, res: Response): Promise<void> => {
    const input = req.body as RunAgentInput;
    const incomingState =
      ((input as any).state as Record<string, unknown> | undefined) ?? {};
    const prefs = coercePreferences(incomingState.preferences);
    const notes = Array.isArray(incomingState.notes)
      ? (incomingState.notes as unknown[]).filter(
          (n): n is string => typeof n === "string",
        )
      : [];
    await runAgenticLoop(req, res, {
      systemPrompt: buildSharedStateReadWriteSystemPrompt(prefs),
      toolSchemas: [SET_NOTES_TOOL_SCHEMA] as Anthropic.Tool[],
      initialState: { preferences: prefs, notes },
    });
  },
);

Select the Claude Agent SDK path

Compatible requests use runWithClaudeAgentSdk. Requests with aimock transport, frontend/runtime tools, extended thinking, or structured user content use the direct Anthropic Messages API fallback.

claude-agent-sdk-adapter.ts
export function shouldUseClaudeAgentSdk({
  input,
  forwardedHeaders,
  runtimeToolCount,
  enableThinking,
}: {
  input: RunAgentInput;
  forwardedHeaders: Record<string, string>;
  runtimeToolCount: number;
  enableThinking?: boolean;
}): boolean {
  if ((process.env.ANTHROPIC_BASE_URL ?? "").includes("aimock")) {
    return false;
  }
  // The official adapter keeps a `headers` property for forward compatibility,
  // but the Claude Agent SDK cannot forward per-request HTTP headers today.
  if (hasHeader(forwardedHeaders, "x-aimock-context")) {
    return false;
  }
  if (enableThinking) {
    return false;
  }
  // The official Claude Agent SDK path can execute backend MCP tools, but it
  // does not yet bridge CopilotKit frontend/runtime tools back through AG-UI.
  if (runtimeToolCount > 0) {
    return false;
  }
  if (hasStructuredUserContent(input)) {
    return false;
  }
  return true;
}
agent_server.ts
  if (
    shouldUseClaudeAgentSdk({
      input,
      forwardedHeaders,
      runtimeToolCount: runtimeTools.length,
      enableThinking: config.enableThinking,
    })
  ) {
    await runWithClaudeAgentSdk({
      input,
      emit,
      runId,
      threadId,
      systemPrompt,
      toolSchemas: config.toolSchemas,
      initialState: state,
      model: config.model ?? CLAUDE_MODEL,
      forwardedHeaders,
      executeTool: (toolName, toolInput, currentState, toolEmit) =>
        executeBackendTool(
          toolName,
          toolInput,
          currentState,
          toolEmit,
          forwardedHeaders,
          contextString,
        ),
    });
    res.end();
    return;
  }

Expose set_notes through MCP

The adapter receives the in-process MCP server and its allowedTools list. The schema becomes an executable SDK tool named mcp__copilotkit__set_notes.

claude-agent-sdk-adapter.ts
function createClaudeAgentAdapter({
  toolSchemas,
  emit,
  getState,
  setState,
  executeTool,
  model,
  systemPrompt,
}: {
  toolSchemas: Anthropic.Tool[];
  emit: Emit;
  getState: () => Record<string, unknown>;
  setState: (state: Record<string, unknown>) => void;
  executeTool: ExecuteTool;
  model: string;
  systemPrompt: string;
}) {
  const backendToolServer = buildBackendToolServer({
    toolSchemas,
    emit,
    getState,
    setState,
    executeTool,
  });

  return new ClaudeAgentAdapter({
    agentId: "claude-sdk-typescript",
    model: normalizeClaudeAgentSdkModel(model),
    systemPrompt,
    tools: [],
    mcpServers: backendToolServer.mcpServers,
    allowedTools: backendToolServer.allowedTools,
    permissionMode: "dontAsk",
    maxTurns: 10,
  });
}
claude-agent-sdk-adapter.ts
const COPILOTKIT_MCP_SERVER_NAME = "copilotkit";
const COPILOTKIT_TOOL_PREFIX = `mcp__${COPILOTKIT_MCP_SERVER_NAME}__`;

function buildBackendToolServer({
  toolSchemas,
  emit,
  getState,
  setState,
  executeTool,
}: {
  toolSchemas: Anthropic.Tool[];
  emit: Emit;
  getState: () => Record<string, unknown>;
  setState: (state: Record<string, unknown>) => void;
  executeTool: ExecuteTool;
}): {
  mcpServers?: Record<string, McpServerConfig>;
  allowedTools: string[];
} {
  if (toolSchemas.length === 0) {
    return { allowedTools: [] };
  }

  const tools = toolSchemas.map((schema) =>
    sdkTool(
      schema.name,
      schema.description ?? "",
      zodShapeFromJsonSchema(schema.input_schema),
      async (args) => {
        try {
          const result = await executeTool(
            schema.name,
            args as Record<string, unknown>,
            getState(),
            emit,
          );
          if (result.state) {
            setState(result.state);
          }
          return {
            content: [{ type: "text" as const, text: result.resultText }],
          };
        } catch (error) {
          const message =
            error instanceof Error ? error.message : String(error);
          return {
            content: [{ type: "text" as const, text: message }],
            isError: true,
          };
        }
      },
    ),
  );

  return {
    mcpServers: {
      [COPILOTKIT_MCP_SERVER_NAME]: createSdkMcpServer({
        name: COPILOTKIT_MCP_SERVER_NAME,
        version: "1.0.0",
        tools,
      }),
    },
    allowedTools: toolSchemas.map(
      (schema) => `${COPILOTKIT_TOOL_PREFIX}${schema.name}`,
    ),
  };
}

Replace the notes in shared state

The backend handler validates the tool arguments and returns the updated state. The adapter emits that state as a snapshot after the tool result.

agent_server.ts
  if (toolName === "set_notes") {
    const notes = Array.isArray(toolInput.notes)
      ? (toolInput.notes as unknown[]).filter(
          (note): note is string => typeof note === "string",
        )
      : [];
    return {
      resultText: JSON.stringify({ status: "ok", count: notes.length }),
      state: { ...state, notes },
    };
  }
  1. On the backend, write the value to a key in the agent state. To stream a tool argument into a state key token by token, see State Streaming.
  2. On the frontend, subscribe to the agent's state with useAgent. Each time the state changes, your component renders again with the latest value.
  3. Read the keys from agent.state and render them.
src/ResearchProgress.tsx
import { Text, View } from "react-native";
import { useAgent, UseAgentUpdate } from "@copilotkit/react-native/headless";

type ResearchState = {
  status?: string;
  draft?: string;
  completed?: number;
  total?: number;
};

export function ResearchProgress() {
  const { agent } = useAgent({
    agentId: "researcher",
    updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged],
  });
  const state = (agent.state ?? {}) as ResearchState;

  return (
    <View style={{ padding: 16, gap: 8 }} accessibilityLiveRegion="polite">
      <Text style={{ fontWeight: "600" }}>
        {state.status ?? (agent.isRunning ? "Working..." : "Idle")}
      </Text>
      <Text>
        {state.completed ?? 0} of {state.total ?? "?"} complete
      </Text>
      {state.draft ? <Text>{state.draft}</Text> : null}
    </View>
  );
}

updates picks which changes re-render the component. OnStateChanged fires on state changes, and OnRunStatusChanged fires when a run starts or ends, so agent.isRunning stays current. Leave updates out to re-render on messages too.

Render it next to your chat, under the same provider. The chat and ResearchProgress share one agent:

App.tsx
import { View } from "react-native";
import { CopilotKitProvider } from "@copilotkit/react-native/headless";
import { CopilotChat } from "@copilotkit/react-native/components";
import { ResearchProgress } from "./src/ResearchProgress";

const runtimeUrl = "http://localhost:8200/api/copilotkit";

export default function App() {
  return (
    <CopilotKitProvider runtimeUrl={runtimeUrl}>
      <View style={{ flex: 1 }}>
        <ResearchProgress />
        <CopilotChat agentName="researcher" />
      </View>
    </CopilotKitProvider>
  );
}

To check it, ask the researcher agent to write a report. The status line and the counter change while the agent runs, and the draft grows as the agent updates draft in its state.

Inside the chat

The rendered CopilotChat has no slot for extra content between messages. To show state inside the conversation, build your own chat and add a row for it to your FlatList data. See Headless UI.

Treat state as untrusted

Treat agent state as external data. Validate it before you use it for a privileged action, and don't put secrets in state that is streamed to the device.

How is this guide?