Skip to main content
All posts

Interactive MCP Apps: Building Two-Way UIs with useAppState (November 2026)

Abe Wheeler
MCP AppsMCP App FrameworkChatGPT AppsChatGPT App FrameworkClaude AppsClaude ConnectorsMCP App Testing
Build UIs that can be interacted with by humans or agents with sunpeak.

Build UIs that can be interacted with by humans or agents with sunpeak.

TL;DR: useAppState works like React useState, but it syncs chosen UI state to the host through updateModelContext. A compatible host can pass the latest update to the model on a later turn, usually after the next user message. Use it for compact decisions and selections, not as a database or permission check. Import it from sunpeak alongside useToolData.

Every tutorial for MCP Apps starts with the same shape: tool returns data, component renders it as a card. That covers a lot of apps. But it leaves out the interactive half of the picture.

When a user reviews a proposed action, the model should know what they chose. When a user checks three items off a list, the model should have those three IDs on the next relevant turn. useAppState is how that works in MCP Apps: it turns selected UI state into model context without making every interaction a new chat message.

Why Not Just useState

React useState is local to the component instance. The host does not know about it. The value is lost when that instance unmounts unless you restore it elsewhere. For UI-only state like open/closed panels or hover effects, that is fine.

useAppState does something different: it syncs state to the host through updateModelContext. A compatible host can make that update available to the model on a later turn. The MCP Apps App API says the request does not start an immediate model response, and each update replaces the previous context from that app.

The MCP Apps request is ui/update-model-context. Send the complete, current model-visible snapshot, because the host keeps the latest update rather than merging a series of partial updates. If the UI should ask the model to respond now, use sendMessage after updating context.

ChatGPT also exposes window.openai.widgetState and window.openai.setWidgetState for ChatGPT-specific widget persistence. Those are useful for UI-only state inside one ChatGPT message, but they are not the portable API to build around. For new cross-host MCP Apps, start with the MCP Apps bridge and use ChatGPT extensions only when the feature is truly ChatGPT-specific.

useAppState wraps the portable model-visible path into one React hook so you write resource code instead of host bridge code.

The hook signature is almost identical to useState:

import { useAppState } from 'sunpeak';

const [state, setState] = useAppState({ confirmed: false });

The difference is that setState also sends the new state to the host. It does not guarantee recovery after a remount, a new conversation, or a switch to another device. Save data that must survive those events on your server.

Use useState for hover states, open/closed panels, active tabs, animation triggers, and scroll position.

Use useAppState for decisions, selected rows, staged form values, approval choices, filters, checklist progress, and anything else the model should see.

The Current MCP Apps State Contract

An interactive MCP App has two data directions:

  1. The model and server send data into the UI. Your resource reads that data with useToolData, usually from the tool result’s structuredContent.
  2. The user changes state in the UI. Your resource writes the state the model should know about with useAppState, which calls updateModelContext for you.

Keep those two directions separate. structuredContent is the initial tool result. It should be concise, typed, and useful to both the model and the UI. useAppState describes what changed after render. It should describe the user’s current interaction state, not duplicate the whole tool result. The MCP Apps overview separates server tool results from later app-to-host context updates.

For an approval card, the tool result might say:

{
  "proposalId": "cleanup-42",
  "title": "Delete production snapshots",
  "description": "This will permanently delete 14 snapshots.",
  "confirmLabel": "Approve deletion",
  "cancelLabel": "Keep them"
}

The app state after a click should be much smaller:

{
  "proposalId": "cleanup-42",
  "decision": "confirmed"
}

The opaque proposal ID ties the choice to one specific review. The server must still check the current user, proposal, and action before any write. Model context needs neither the whole UI tree nor OAuth tokens, analytics fields, or raw database rows.

A host may support only some content types for updateModelContext. Check its advertised capability or handle a rejected update, then give the user a visible way to continue. Never treat an unacknowledged context update as a completed action.

Use this rule when deciding what to sync: if the model needs it to answer the next user message, put it in useAppState. If only the UI needs it, keep it in component state, ChatGPT widget state, or your backend.

A Practical Example: Approval Flow

One interactive pattern in Claude Connectors and ChatGPT Apps is a review flow. The model shows a proposal. The user confirms or rejects it. The app reports that choice to the host, so the model can use it on a later turn.

This example shows a proposal and two buttons. It reports a choice; it does not perform the proposed deletion.

import { useToolData, useAppState, SafeArea } from 'sunpeak';
import type { ResourceConfig } from 'sunpeak';

export const resource: ResourceConfig = {
  title: 'Approval',
  description: 'Request user confirmation before taking an action',
};

interface ApprovalData {
  proposalId: string;
  title: string;
  description: string;
  confirmLabel?: string;
  cancelLabel?: string;
}

interface ApprovalState {
  proposalId: string | null;
  decision: 'confirmed' | 'cancelled' | null;
}

export function ApprovalResource() {
  const { output } = useToolData<unknown, ApprovalData>();
  const [state, setState] = useAppState<ApprovalState>({
    proposalId: null,
    decision: null,
  });

  if (!output) return null;

  const handleConfirm = () => {
    setState({ proposalId: output.proposalId, decision: 'confirmed' });
  };

  const handleCancel = () => {
    setState({ proposalId: output.proposalId, decision: 'cancelled' });
  };

  return (
    <SafeArea className="p-5 font-sans max-w-sm mx-auto space-y-4">
      <div>
        <h1 className="text-lg font-bold">{output.title}</h1>
        <p className="text-sm text-gray-600 mt-1">{output.description}</p>
      </div>

      {state.decision === null ? (
        <div className="flex gap-3">
          <button
            onClick={handleCancel}
            className="flex-1 py-2 px-4 rounded-lg border border-gray-300 text-sm font-medium"
          >
            {output.cancelLabel ?? 'Cancel'}
          </button>
          <button
            onClick={handleConfirm}
            className="flex-1 py-2 px-4 rounded-lg bg-blue-600 text-white text-sm font-medium"
          >
            {output.confirmLabel ?? 'Confirm'}
          </button>
        </div>
      ) : (
        <div className="text-center py-2">
          <p className="font-medium text-green-700">
            {state.decision === 'confirmed' ? 'Choice recorded for the next turn' : 'Cancelled'}
          </p>
        </div>
      )}
    </SafeArea>
  );
}

The tool that triggers this resource passes the proposal ID, title, and description as structuredContent. After a click, the host can include { proposalId: 'cleanup-42', decision: 'confirmed' } in a later model turn. That value describes the user’s choice. It is not authorization to delete data by itself.

The tool looks like this:

// src/tools/request-approval.ts
import { z } from 'zod';
import type { AppToolConfig, ToolHandlerExtra } from 'sunpeak/mcp';

export const tool: AppToolConfig = {
  resource: 'approval',
  title: 'Request Approval',
  description: 'Show a proposed action for review without performing it',
  annotations: { readOnlyHint: true, openWorldHint: false },
};

export const schema = {
  proposalId: z.string().describe('Opaque ID for the proposal being reviewed'),
  title: z.string().describe('Action title'),
  description: z.string().describe('What will happen if the user confirms'),
  confirmLabel: z.string().optional().describe('Confirm button text'),
  cancelLabel: z.string().optional().describe('Cancel button text'),
};

type Args = z.infer<z.ZodObject<typeof schema>>;

export default async function (args: Args, _extra: ToolHandlerExtra) {
  return {
    structuredContent: {
      proposalId: args.proposalId,
      title: args.title,
      description: args.description,
      confirmLabel: args.confirmLabel ?? 'Confirm',
      cancelLabel: args.cancelLabel ?? 'Cancel',
    },
  };
}

The review tool only displays information, so readOnlyHint: true describes its own behavior. Mark the separate deletion tool as destructive if it can delete data. MCP tool annotations are hints about what a tool itself does, not a substitute for server-side authorization or an action-specific confirmation. See the MCP App tool metadata guide for the broader metadata pattern.

For a real deletion, include a stable proposal ID, show the exact target and effect, and have the server validate the user and current proposal before it executes a separate write tool. Return the resulting server record or status so the UI and model can distinguish “choice recorded” from “deletion completed.”

setState: Replacement and Functional Updates

setState from useAppState accepts two forms, just like React’s useState.

You can pass a full replacement object:

setState({ proposalId: output.proposalId, decision: 'confirmed' });

Or you can pass a callback that receives the previous state:

setState(prev => ({ ...prev, proposalId: output.proposalId, decision: 'confirmed' }));

The callback form is useful when you have many fields and only want to update a few, because it avoids accidentally dropping fields. Either way, the new state replaces the old state entirely. There is no shallow merge like React class component setState.

For complex state with many fields, the callback pattern keeps things readable:

const [state, setState] = useAppState({ step: 1, answers: {}, complete: false });

// Advance to step 2 without losing answers
setState(prev => ({ ...prev, step: 2 }));

A Checklist Example

Here is a checklist where the user checks items off a list and the model knows which are done:

import { useToolData, useAppState, SafeArea } from 'sunpeak';
import type { ResourceConfig } from 'sunpeak';

export const resource: ResourceConfig = {
  title: 'Checklist',
  description: 'Interactive task checklist with model-visible completion state',
};

interface ChecklistData {
  title: string;
  items: Array<{ id: string; label: string }>;
}

interface ChecklistState {
  checked: string[];
}

export function ChecklistResource() {
  const { output } = useToolData<unknown, ChecklistData>(undefined, undefined);
  const [state, setState] = useAppState<ChecklistState>({ checked: [] });

  if (!output) return null;

  const toggle = (id: string) => {
    setState(prev => {
      const checked = prev.checked.includes(id)
        ? prev.checked.filter((c) => c !== id)
        : [...prev.checked, id];
      return { checked };
    });
  };

  return (
    <SafeArea className="p-5 font-sans max-w-sm mx-auto">
      <h1 className="text-lg font-bold mb-3">{output.title}</h1>
      <ul className="space-y-2">
        {output.items.map((item) => {
          const done = state.checked.includes(item.id);
          return (
            <li key={item.id}>
              <label className="flex items-center gap-3 cursor-pointer">
                <input
                  type="checkbox"
                  checked={done}
                  onChange={() => toggle(item.id)}
                  className="w-4 h-4 rounded"
                />
                <span className={done ? 'line-through text-gray-400' : ''}>{item.label}</span>
              </label>
            </li>
          );
        })}
      </ul>
      <p className="text-xs text-gray-400 mt-4">
        {state.checked.length} of {output.items.length} complete
      </p>
    </SafeArea>
  );
}

Every time the user checks or unchecks an item, useAppState sends the updated checked array to the host. On a later turn, a compatible host can give the model those IDs so it can answer based on the current checklist.

Adding Test Data

Add a simulation file at tests/simulations/request-approval.json:

{
  "tool": "request-approval",
  "userMessage": "Delete the old production snapshots",
  "toolInput": {
    "proposalId": "cleanup-42",
    "title": "Delete production snapshots",
    "description": "This will permanently delete 14 snapshots from January 2025. This cannot be undone.",
    "confirmLabel": "Approve deletion",
    "cancelLabel": "Keep them"
  },
  "toolResult": {
    "structuredContent": {
      "proposalId": "cleanup-42",
      "title": "Delete production snapshots",
      "description": "This will permanently delete 14 snapshots from January 2025. This cannot be undone.",
      "confirmLabel": "Approve deletion",
      "cancelLabel": "Keep them"
    }
  }
}

Run pnpm dev and open http://localhost:3000. The approval card renders. Click “Approve deletion” and watch the view change to “Choice recorded for the next turn.” The sunpeak Inspector shows the app state in its sidebar so you can inspect the host-side update. No snapshots are deleted by this example.

Testing Interactive State

For unit tests, use Vitest and @testing-library/react to test state transitions. Mock useAppState alongside useToolData:

import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { ApprovalResource } from './approval';

let currentState = { proposalId: null, decision: null };
const mockSetState = vi.fn((newState) => {
  currentState = newState;
});

vi.mock('sunpeak', () => ({
  useToolData: () => ({
    output: {
      proposalId: 'cleanup-42',
      title: 'Delete production snapshots',
      description: 'This will permanently delete 14 snapshots.',
      confirmLabel: 'Approve deletion',
      cancelLabel: 'Keep them',
    },
    input: null,
    inputPartial: null,
    isError: false,
    isLoading: false,
    isCancelled: false,
    cancelReason: null,
  }),
  useAppState: () => [currentState, mockSetState],
  useHostContext: () => null,
  useDisplayMode: () => 'inline',
  SafeArea: ({ children, ...props }: any) => <div {...props}>{children}</div>,
}));

describe('ApprovalResource', () => {
  it('calls setState with confirmed decision on confirm click', () => {
    render(<ApprovalResource />);
    fireEvent.click(screen.getByText('Approve deletion'));
    expect(mockSetState).toHaveBeenCalledWith(
      expect.objectContaining({ proposalId: 'cleanup-42', decision: 'confirmed' })
    );
  });

  it('calls setState with cancelled decision on cancel click', () => {
    currentState = { proposalId: null, decision: null };
    render(<ApprovalResource />);
    fireEvent.click(screen.getByText('Keep them'));
    expect(mockSetState).toHaveBeenCalledWith(
      expect.objectContaining({ proposalId: 'cleanup-42', decision: 'cancelled' })
    );
  });
});

That test checks the component contract: a user click calls the state setter with the expected proposal and decision. It does not prove that the host bridge received the state. Check the bridge with a host integration test or observe the update in the Inspector.

For end-to-end tests, click the button inside the inspector iframe and assert that the confirmed state renders:

import { test, expect } from 'sunpeak/test';

test('approval resource shows confirmed state after clicking confirm', async ({ inspector }) => {
  const result = await inspector.renderTool('request-approval');
  expect(result.source).toBe('fixture');
  const app = result.app();
  await app.getByRole('button', { name: 'Approve deletion' }).click();
  await expect(app.getByText('Choice recorded for the next turn')).toBeVisible();
});

Omitting the second argument to renderTool loads the matching simulation. Passing {} calls the server handler instead. The current InspectorResult helper exposes app(), content, structuredContent, and source, but no modelContext() method. To assert the outbound payload automatically, test a component using the lower-level bridge with a mocked updateModelContext request, or add a host integration check that captures that request. The UI assertion above checks only what the user sees.

The same test can run against the Claude host by setting host: 'claude' in your Playwright project config. The sunpeak testing framework runs both host runtimes locally without accounts, API keys, or credits on your CI runners. See the cross-host testing guide for full matrix testing patterns.

For a production app, cover these states:

  1. Initial render from structuredContent.
  2. User interaction updates visible UI.
  3. A host integration check observes the latest model-context update.
  4. A new tool invocation starts from the intended initial state or from server data, not from stale UI state.

Where State Lives After the Decision

Once the user acts, useAppState holds the state for that resource instance and syncs the model-visible part to the host. Treat that as conversation state, not durable storage.

This is the right behavior for most interactive apps. An approval flow should start fresh each time the model asks for approval. A checklist that persists across conversations needs durable storage, usually your database or an MCP tool call that writes the user’s progress. On the next invocation, pass that saved state back as tool input or structuredContent.

On ChatGPT, widget state is scoped to one rendered widget instance. That host-specific snapshot is separate from the portable model-context update. Across MCP Apps-compatible hosts, keep authoritative business data on the server and restore it from a fresh tool result.

Avoid localStorage for core state. It can be unavailable, isolated by sandbox policy, hard to clear, and inconsistent across hosts. It is fine for small UI preferences if the app can work without them.

When Not to Use useAppState

useAppState is for state the model needs to see. If the state only affects visual presentation and the model does not need to know about it, useState is simpler.

Display mode changes go through the display-mode request API, not useAppState. To request fullscreen:

import { useRequestDisplayMode } from 'sunpeak';

const { requestDisplayMode, availableModes } = useRequestDisplayMode();

if (availableModes?.includes('fullscreen')) {
  requestDisplayMode({ mode: 'fullscreen' });
}

Read-only displays that adapt to host context use useHostContext and useDisplayMode, neither of which write state.

ChatGPT also has host-specific hooks for platform features: useUploadFile for adding files to the conversation, useRequestModal for host-controlled modals, and useRequestCheckout for payments. These are separate from useAppState because they trigger host actions rather than syncing state to the model. Guard them with capability detection or isChatGPT() since they only work on ChatGPT. See the ChatGPT Apps compatibility guide and the display mode reference for details on host-specific behavior.

useToolData reads the server result, while useAppState reports selected user state to the host. For a write, call a server tool and render its authoritative result. Those three steps make an interactive MCP App understandable in the UI and in the conversation.

Get Started

Documentation →
npx sunpeak new

Further Reading

Frequently Asked Questions

What is useAppState in sunpeak?

useAppState is a React hook from sunpeak for MCP App state that should be visible to the AI model. It works like React useState, but each update is synced to the host through updateModelContext so the model can read user decisions, selections, staged form values, or checklist progress on a later turn.

What is the difference between useState and useAppState in MCP Apps?

React useState is local UI state. The host and model do not see it. useAppState is model-visible app state. Use useState for visual state such as expanded panels, hover effects, active tabs, and local animation. Use useAppState for state the model should use when it answers next, such as approvals, filters, selected rows, staged edits, and form progress.

How does the AI model read useAppState?

When state changes, useAppState calls updateModelContext with structured state. A compatible host can include the latest update on a later model turn, usually after the next user message. The update does not force an immediate assistant response or save data permanently. Use sendMessage when the UI needs to start a conversation turn.

What does the useAppState API look like?

useAppState works like useState but takes an initial state object and returns a readonly [state, setState] tuple. Example: const [state, setState] = useAppState({ confirmed: false }). The setState function accepts either a full replacement object or a callback function like setState(prev => ({ ...prev, confirmed: true })). Import it from sunpeak alongside useToolData.

Does useAppState work the same on ChatGPT and Claude?

The hook uses the portable MCP Apps model-context request, so the component does not need a host-specific import. Hosts can differ in capabilities and when they pass an update to the model, so test the behavior in each target host. ChatGPT also has optional widget-state APIs for instance-scoped UI persistence.

How do I test interactive MCP App state with sunpeak?

Use Vitest with @testing-library/react to test the click and the state setter. Run an inspector E2E test with a simulation to check the rendered state and inspect the host context panel. The current InspectorResult test helper has no modelContext() method, so test the bridge request separately if you need an automated assertion for its payload.

What are common use cases for useAppState in MCP Apps?

Common use cases include approval flows, multi-step forms, preference selectors, selected table rows, checklist progress, active filters, draft edits, and user confirmations before write actions. The test is simple: if the model should adjust its next answer based on the state, use useAppState.

Can I use useAppState and useToolData together in the same component?

Yes. useToolData reads the tool input and structuredContent returned by the MCP tool. useAppState manages state the user changes after the resource renders. Together they cover the normal two-way MCP App loop: model calls a tool, the resource renders the result, the user interacts with the UI, and the model can read the updated app state on a later turn.