Skip to main content
All posts

Build an MCP App with React: Hooks, Tool Data, and Host Styles (November 2026)

Abe Wheeler
MCP AppsMCP App ReactMCP App FrameworkMCP App TestingChatGPT AppsChatGPT App FrameworkChatGPT App TestingClaude ConnectorsClaude Connector FrameworkReactTypeScript
A React MCP App connects a bundled view to tool data and host context through the MCP Apps bridge.

A React MCP App connects a bundled view to tool data and host context through the MCP Apps bridge.

React is a good fit for an MCP App because the view is an interactive web interface. The confusing part is everything around the component. The app does not get its first data through props or an API route. An AI host such as ChatGPT or Claude creates the iframe, connects a bridge, and sends tool input, tool results, host context, and lifecycle events.

This guide builds that mental model first, then shows the React code for a reliable app on the current stack: @modelcontextprotocol/ext-apps 2.x and the split MCP TypeScript SDK v2. I checked every API below against the published ext-apps 2.0.4 and sunpeak 0.20.99 packages on November 17, 2026.

TL;DR: Install @modelcontextprotocol/ext-apps with @modelcontextprotocol/server (not the old @modelcontextprotocol/sdk). In React, call useApp and register every bridge handler inside onAppCreated. Validate structuredContent with the same Zod schema the server uses as outputSchema, call useHostStyles(app, app?.getHostContext()), and send server work through app.callServerTool to tools marked visibility: ['app']. Bundle the view into one HTML file and test it inside a host runtime.

What Changed Since August

The first version of this post targeted ext-apps 1.x and the monolithic MCP SDK v1. If you followed it, these are the changes that matter for a React view:

AreaBefore (ext-apps 1.x)Now (ext-apps 2.0.4)
Server SDK@modelcontextprotocol/sdk v1, McpServer from sdk/server/mcp.js@modelcontextprotocol/server ^2.0.0, McpServer from the package root
Tool inputSchemaRaw Zod shape, { city: z.string() }Zod object or other Standard Schema, z.object({ city: z.string() }) (raw shapes still type-check)
Zodv3 or v4Peer zod ^4.2.0
Late handler registrationSilent missed notificationconsole.warn, or a thrown Error with strict: true
Zod under strict CSPNo SDK default, so Zod’s JIT parser could throw on new Function()App sets z.config({ jitless: true }) unless allowUnsafeEval: true
Unknown tool in callServerToolVaried by hostRejects with JSON-RPC -32602

ext-apps 2.1.0 is also on npm, but as of today the latest tag still points at 2.0.4. 2.1.0 adds a WebMCP bridge: tools you register with App.registerTool() are mirrored into document.modelContext when the page provides one. It is on by default and you can turn it off with webMcpBridge: false, which useApp also forwards. Nothing else in this guide changes between the two versions.

React Owns the View, Not the Whole MCP App

An MCP App has three boundaries:

PartRuns whereOwns
MCP serverYour server processTools, resources, schemas, auth, database access
AI hostChatGPT, Claude, or another MCP Apps clientTool selection, iframe policy, bridge, host capabilities
React viewSandboxed iframeRendering, local interaction, app-to-host requests

React only owns the third row. It should not hold service credentials, trust model-generated arguments, or write directly to a protected database.

The normal first-render path looks like this:

Model chooses a tool
  -> MCP server runs the tool
  -> Tool returns content and structuredContent
  -> Host loads the linked ui:// resource
  -> React view connects to the host (ui/initialize)
  -> Host sends ui/notifications/tool-input and tool-result
  -> React renders structuredContent

The view and server are separate builds even when they live in one repository. The server returns the React build as an HTML resource, but the invocation data arrives through the bridge.

Install the React SDK Layer

ext-apps 2.0.4 peers on @modelcontextprotocol/server, client, and core at ^2.0.0, zod ^4.2.0, and React 17, 18, or 19. It needs Node 20 or newer.

npm install react react-dom zod @modelcontextprotocol/ext-apps @modelcontextprotocol/server
npm install -D typescript vite @vitejs/plugin-react vite-plugin-singlefile @types/react @types/react-dom

Add @modelcontextprotocol/node or @modelcontextprotocol/express for the HTTP transport, the same way the official basic-server-react example does.

Some setup guides still show npm install @modelcontextprotocol/ext-apps @modelcontextprotocol/sdk. That pairs ext-apps 2.x with the v1 SDK, and you will get peer dependency warnings and type mismatches on McpServer. Use the v2 packages. The TypeScript SDK v2 migration post covers moving an existing server.

@modelcontextprotocol/ext-apps/react is a subpath export of @modelcontextprotocol/ext-apps, so you do not install it separately. It exports:

  • useApp to create and connect the view-side App
  • useHostStyles, useHostStyleVariables, and useHostFonts
  • useDocumentTheme for reactive theme state
  • useAutoResize for the case where you built the App yourself with autoResize: false

The React entry also re-exports everything from the core App module, so your handlers use the same typed bridge methods as a plain JavaScript view. There is a react-with-deps subpath that bundles the SDK’s own dependencies for setups that cannot resolve them, but a normal Vite build does not need it.

Share One Schema Between Server and View

Put the tool’s output schema in a file both builds can import. The server uses it as outputSchema, and the view uses it to validate what arrives over the bridge.

// shared/inventory.ts
import { z } from 'zod';

export const InventorySchema = z.object({
  warehouseId: z.string(),
  items: z.array(
    z.object({
      sku: z.string(),
      name: z.string(),
      available: z.number().int(),
    })
  ),
});

export type Inventory = z.infer<typeof InventorySchema>;

Zod 4 schemas are Standard Schema objects with JSON Schema output, which is what ext-apps 2.x accepts for inputSchema and outputSchema. The outputSchema and structuredContent post goes deeper on what hosts do with the advertised schema.

The server must point the UI tool at the same resource URI it registers:

// server.ts
import fs from 'node:fs/promises';
import { McpServer } from '@modelcontextprotocol/server';
import { z } from 'zod';
import {
  registerAppResource,
  registerAppTool,
  RESOURCE_MIME_TYPE,
} from '@modelcontextprotocol/ext-apps/server';
import { InventorySchema } from './shared/inventory.js';

export function createServer() {
  const server = new McpServer({ name: 'inventory-app', version: '1.0.0' });
  const resourceUri = 'ui://inventory/summary-v1.html';

  registerAppTool(
    server,
    'show-inventory',
    {
      title: 'Show inventory',
      description: 'Show current inventory for one warehouse',
      inputSchema: z.object({ warehouseId: z.string() }),
      outputSchema: InventorySchema,
      _meta: { ui: { resourceUri } },
    },
    async ({ warehouseId }) => {
      const items = await loadInventory(warehouseId);
      return {
        content: [{ type: 'text', text: `Found ${items.length} inventory items.` }],
        structuredContent: { warehouseId, items },
      };
    }
  );

  // Called by the view's refresh button, hidden from the model.
  registerAppTool(
    server,
    'refresh-inventory',
    {
      description: 'Reload inventory for the open view',
      inputSchema: z.object({ warehouseId: z.string() }),
      outputSchema: InventorySchema,
      _meta: { ui: { resourceUri, visibility: ['app'] } },
    },
    async ({ warehouseId }) => {
      const items = await loadInventory(warehouseId);
      return {
        content: [{ type: 'text', text: `Refreshed ${items.length} items.` }],
        structuredContent: { warehouseId, items },
      };
    }
  );

  registerAppResource(
    server,
    'Inventory summary',
    resourceUri,
    { mimeType: RESOURCE_MIME_TYPE },
    async () => ({
      contents: [
        {
          uri: resourceUri,
          mimeType: RESOURCE_MIME_TYPE,
          text: await fs.readFile(new URL('./dist/inventory.html', import.meta.url), 'utf8'),
        },
      ],
    })
  );

  return server;
}

The values that must agree are:

  1. _meta.ui.resourceUri on the tool descriptor
  2. The URI passed to registerAppResource
  3. The uri returned by the resource handler
  4. The text/html;profile=mcp-app MIME type (RESOURCE_MIME_TYPE)

visibility: ['app'] keeps refresh-inventory out of the model’s tool list while still letting the view call it. The default is ['model', 'app']. The tool meta and visibility post covers the other combinations.

If the tool works but React never appears, check those four values before you debug the component.

Mount React and Bundle One HTML File

The HTML entry needs a root element and the React module:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="color-scheme" content="light dark" />
    <title>Inventory</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>

The TypeScript entry is normal React:

import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { InventoryApp } from './InventoryApp';
import './styles.css';

const root = document.getElementById('root');
if (!root) throw new Error('Missing #root element');

createRoot(root).render(
  <StrictMode>
    <InventoryApp />
  </StrictMode>
);

The host serves your view from a sandboxed origin, so relative paths like /assets/index-abc.js point at nothing. The simplest fix is to inline every script and stylesheet into one HTML file, which is what the official examples do with vite-plugin-singlefile:

// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { viteSingleFile } from 'vite-plugin-singlefile';

export default defineConfig({
  plugins: [react(), viteSingleFile()],
  build: {
    outDir: 'dist',
    emptyOutDir: false,
    rollupOptions: { input: 'inventory.html' },
  },
});

Fonts, images, and anything you load at runtime still need absolute URLs plus matching _meta.ui.csp domains on the resource. The CSP post lists which CSP field covers which request type.

Connect Before You Render Tool Data

useApp creates the App, calls your onAppCreated callback, opens a PostMessageTransport to window.parent, and runs the ui/initialize handshake. It returns { app, isConnected, error }, and app stays null until the handshake succeeds.

Register handlers inside onAppCreated. That callback runs after the App exists and before it connects, so the host cannot deliver the tool result before your handler is in place.

import { useEffect, useState, type ReactNode } from 'react';
import type { App, McpUiHostContext } from '@modelcontextprotocol/ext-apps';
import { useApp, useHostStyles } from '@modelcontextprotocol/ext-apps/react';
import { InventorySchema, type Inventory } from '../shared/inventory';

export function InventoryApp() {
  const [data, setData] = useState<Inventory>();
  const [hostContext, setHostContext] = useState<McpUiHostContext>();
  const [cancelled, setCancelled] = useState(false);
  const [runtimeError, setRuntimeError] = useState<string>();

  const { app, isConnected, error } = useApp({
    appInfo: { name: 'inventory-view', version: '1.0.0' },
    capabilities: {},
    onAppCreated: (created) => {
      created.ontoolresult = (result) => {
        setCancelled(false);
        if (result.isError) {
          setRuntimeError('The inventory tool failed.');
          return;
        }
        const parsed = InventorySchema.safeParse(result.structuredContent);
        if (!parsed.success) {
          setRuntimeError('The server returned invalid inventory data.');
          return;
        }
        setRuntimeError(undefined);
        setData(parsed.data);
      };

      created.ontoolcancelled = () => setCancelled(true);

      created.onhostcontextchanged = (patch) => {
        setHostContext((current) => ({ ...current, ...patch }));
      };

      created.onteardown = async () => {
        // Flush drafts or cancel timers here. The host waits for this to resolve.
        return {};
      };

      created.onerror = (nextError) => setRuntimeError(nextError.message);
    },
  });

  useEffect(() => {
    if (app) setHostContext(app.getHostContext());
  }, [app]);

  useHostStyles(app, app?.getHostContext());

  if (error) return <Status role="alert">Could not connect to the host.</Status>;
  if (!isConnected || !app) return <Status>Connecting...</Status>;
  if (cancelled) return <Status>The inventory request was cancelled.</Status>;
  if (runtimeError) return <Status role="alert">{runtimeError}</Status>;
  if (!data) return <Status>Loading inventory...</Status>;

  return (
    <main data-theme={hostContext?.theme}>
      <h1>Warehouse {data.warehouseId}</h1>
      <ul>
        {data.items.map((item) => (
          <li key={item.sku}>
            <span>{item.name}</span>
            <strong>{item.available}</strong>
          </li>
        ))}
      </ul>
    </main>
  );
}

function Status({ children, role = 'status' }: { children: ReactNode; role?: 'status' | 'alert' }) {
  return <p role={role}>{children}</p>;
}

This keeps the runtime states explicit. A blank screen hides whether the app is connecting, waiting for a result, cancelled, or broken.

safeParse is the important line. TypeScript types disappear at runtime, so result.structuredContent as Inventory does not protect the view from an old server build, a mocked host, or a partial failure. Because ext-apps 2.x puts Zod into jitless mode by default, this runs under the default MCP Apps CSP without unsafe-eval.

Handler Timing: The Bug ext-apps 2.x Now Reports

ext-apps 2.x tracks four one-shot events: toolinput, toolinputpartial, toolresult, and toolcancelled. If the first handler for any of them is registered after the handshake finishes, the SDK logs a warning because the host may already have sent that notification. With strict: true, it throws instead.

The most common way to hit this in React is registering inside a useEffect:

// Wrong: runs after connect, so the first tool result can be missed
const { app } = useApp({ appInfo, capabilities: {} });
useEffect(() => {
  if (app) app.ontoolresult = (r) => setData(r.structuredContent);
}, [app]);

Move the registration into onAppCreated. If a child component needs its own listener, register a first handler in onAppCreated and then use app.addEventListener('toolresult', handler) and removeEventListener in the child’s effect. Only the first handler for each event is checked, so a later add and remove on dependency change does not warn.

I turn on strict: true in development builds. It also throws when you call callServerTool, sendMessage, or another host-bound method before the handshake, which turns two quiet race conditions into test failures. The SDK notes that throwing will become the default in a future release.

Treat Partial Input as Preview Data

Some hosts stream tool arguments before the server call finishes. Register ontoolinputpartial next to your other handlers:

created.ontoolinputpartial = ({ arguments: partial }) => {
  const query = partial?.query;
  setSearchPreview(typeof query === 'string' ? query : '');
};

created.ontoolinput = ({ arguments: input }) => {
  const query = input?.query;
  setSearchPreview(typeof query === 'string' ? query : '');
};

Use partial input for labels, skeletons, and previews. Do not start a write, charge a card, choose an auth scope, or make any other lasting decision from it. Partial JSON can parse cleanly while a string or nested value is still incomplete.

Apply Host Styles With Fallbacks

useHostStyles(app, initialContext) applies the host’s CSS variables, theme, and fonts to the document, then reapplies them on every host-context change. It accepts null, so you can call it unconditionally before the app connects. Your CSS then reads the standard variables:

:root {
  color-scheme: light dark;
  font-family: var(--font-sans, system-ui, sans-serif);
  background: transparent;
}

body {
  margin: 0;
  color: var(--color-text-primary, #171717);
  background: transparent;
}

main {
  padding: 16px;
}

li {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  padding: 12px 0;
  border-bottom: 1px solid var(--color-border-primary, #d4d4d4);
}

Every host-context field is optional, so keep CSS fallbacks, and do not guess the host from a color or font value. If you only want one piece, useHostStyleVariables and useHostFonts are exported separately.

Use useDocumentTheme only when the rendered content itself depends on the theme, such as picking a light or dark chart image. Most color changes belong in CSS because that avoids extra React branches. The host styles post lists the full variable set.

Call Server Tools Through the Host

An interactive view often needs fresh data after a click. Send that work back through the host instead of putting backend credentials in the iframe:

async function refreshInventory(app: App, warehouseId: string) {
  if (!app.getHostCapabilities()?.serverTools) {
    setRuntimeError('This host cannot refresh inventory from the app.');
    return;
  }

  setRuntimeError(undefined);

  try {
    const result = await app.callServerTool({
      name: 'refresh-inventory',
      arguments: { warehouseId },
    });

    if (result.isError) {
      setRuntimeError('The inventory refresh failed.');
      return;
    }

    const parsed = InventorySchema.safeParse(result.structuredContent);
    if (!parsed.success) {
      setRuntimeError('The refresh returned invalid inventory data.');
      return;
    }

    setData(parsed.data);
  } catch {
    setRuntimeError('The host could not reach the inventory tool.');
  }
}

Call it from the rendered branch, where app and data both exist: onClick={() => refreshInventory(app, data.warehouseId)}. Passing them in avoids reading a possibly undefined data inside the handler.

There are two error paths:

  • A tool execution error resolves with isError: true.
  • A transport failure, timeout, host rejection, or unknown tool name rejects the promise. In ext-apps 2.x an unknown tool rejects with JSON-RPC -32602.

Handle both. The server must still validate arguments, check the user’s session and permissions, and enforce business rules, because a tool marked visibility: ['app'] is hidden from the model but is still a normal MCP tool. The MCP App actions post covers sendMessage and updateModelContext, which follow the same pattern.

Avoid React Connection Loops

useApp has two behaviors worth knowing:

  1. It reads its options only on the first mount. Changing the object later does not reconnect.
  2. It does not close the App on unmount, so the React Strict Mode double mount does not tear down a live bridge.

Those choices prevent duplicate initialization. They also mean runtime values such as theme or tool data belong in React state, not in changing useApp options. Call app.close() yourself if you really need to disconnect.

useApp forwards two App options. For anything else, construct the App yourself in an effect, connect it with PostMessageTransport, and call useAutoResize(app) if you turned off automatic resizing.

OptionDefaultThrough useApp?What it does
autoResizetrueYesWatches body and documentElement with ResizeObserver and sends ui/notifications/size-changed
strictfalseYesThrows instead of warning on late one-shot handlers and pre-handshake host calls
allowUnsafeEvalfalseNoWhen false, the App constructor sets Zod to jitless mode so parsing works without unsafe-eval
webMcpBridgetrueYes, 2.1.0 onlyMirrors App.registerTool() tools into document.modelContext when available

Common React MCP App Failures

SymptomLikely causeFix
Tool runs, iframe never appearsresourceUri mismatch or wrong MIME typeCompare the four linked values above
Iframe appears blankScript or CSS referenced by a relative pathBundle with vite-plugin-singlefile or use absolute URLs with CSP domains
Stuck on “Loading”ontoolresult registered in useEffect after connectRegister in onAppCreated; check the console for the 2.x late-handler warning
EvalError or CSP violation on first messageext-apps 1.x, or allowUnsafeEval: true under a strict CSPUpgrade and keep the 2.x default
Two connections in developmentYour own effect creates a second AppUse useApp, or guard a manual App with a ref
Refresh button throws -32602Tool name typo or tool not registered on this serverMatch the name exactly; list tools in a protocol test
Wrong colors in dark modeHard-coded colors, no host variablesUse --color-* variables with fallbacks

Do Not Test the View as a Normal Web Page

Opening inventory.html in a tab proves React can mount. It does not prove the app works, because a normal tab has no MCP Apps parent bridge, so useApp never connects.

Use three test layers.

Component Tests

Extract presentation components and pass plain props:

render(
  <InventoryList
    items={[
      { sku: 'A-1', name: 'Cable', available: 4 },
      { sku: 'B-2', name: 'Adapter', available: 0 },
    ]}
  />
);

expect(screen.getByText('Cable')).toBeVisible();
expect(screen.getByText('4')).toBeVisible();

Also unit test the schema: feed InventorySchema.safeParse a missing items array, a string available, and an extra field, and assert the result. That is the boundary your view trusts. The unit testing post shows how to mock the bridge for components that call app actions.

Protocol Tests

Connect an MCP client to the server and assert:

  • tools/list includes _meta.ui.resourceUri on show-inventory
  • refresh-inventory has _meta.ui.visibility set to ['app']
  • resources/read returns the matching URI and text/html;profile=mcp-app
  • tools/call returns structuredContent that passes InventorySchema
  • app-only data stays out of model-visible content
  • the resource declares only the CSP domains and permissions the view needs

These catch a broken link between the server and the React build before a browser opens.

Browser Tests in a Host Runtime

Render the resource through an MCP App inspector or host test harness and cover:

  • Connecting and initial loading
  • Partial and complete tool input
  • Success, empty, malformed, error, and cancellation results
  • Repeated results without a remount
  • Light and dark themes
  • Inline, fullscreen, and other supported display modes
  • Narrow mobile widths and safe areas
  • A host without serverTools
  • Every callServerTool, link, message, download, or display mode action

Use deterministic fixtures for these states. A live model can pick a different tool or argument shape on each run, which makes it a poor source for UI regression tests. The cross-host testing post covers where ChatGPT and Claude differ.

When a React MCP App Framework Helps

The official React entry solves the connection and host style layer. You still have to pick conventions for:

  • Server and resource file layout
  • Schema sharing and runtime validation
  • The single-file React bundle
  • Tool and resource registration
  • Local host simulation
  • Deterministic tool result fixtures
  • Browser, visual, and live-host tests
  • Production server and deployment

That direct setup is reasonable when you already have an MCP server and want full control.

sunpeak’s MCP App framework packages those conventions on top of ext-apps 2.x. Each resource is a React component in src/resources/, each tool is a file in src/tools/ that exports tool, schema, outputSchema, and a handler, and sunpeak build produces the bundles. The hooks remove most of the handler wiring from the example above:

import { useToolData, useCallServerTool, SafeArea } from 'sunpeak';
import type { Inventory } from '../../shared/inventory';

export function InventoryResource() {
  const { output, isLoading, isError, isCancelled } = useToolData<{ warehouseId: string }, Inventory>();
  const callServerTool = useCallServerTool();

  if (isCancelled) return <p>The inventory request was cancelled.</p>;
  if (isError) return <p role="alert">The inventory tool failed.</p>;
  if (isLoading || !output) return <p>Loading inventory...</p>;

  return (
    <SafeArea className="p-4">
      <InventoryList items={output.items} />
      <button
        onClick={() =>
          callServerTool({ name: 'refresh-inventory', arguments: { warehouseId: output.warehouseId } })
        }
      >
        Refresh
      </button>
    </SafeArea>
  );
}

useToolData returns input, inputPartial, output, isError, isLoading, isCancelled, and cancelReason, and sunpeak registers the handlers behind it before calling connect(), so the timing issue above does not apply. It also retries the handshake up to four times with a fresh transport if the host is slow to answer. useCallServerTool resolves to undefined with a console warning if the app is not connected yet, and still rejects on transport errors, so keep the try/catch. You should still validate output with your schema if old servers might send a different shape.

The MCP App Inspector renders the same resource in local ChatGPT and Claude runtimes, so you can switch tool data, theme, display mode, viewport, and host without redeploying. You can also point it at an existing server in any language:

npx sunpeak inspect --server https://your-mcp-server.example.com/mcp

Use the direct SDK when you want to own the bridge adapter and build pipeline. Use a framework when you want React state, the resource build, the inspector, and the test setup to follow one documented path. Either way, the output stays portable: normal MCP tools, ui:// resources, the MCP App MIME type, and the standard ui/* bridge.

Get Started

Documentation →
npx sunpeak new

Further Reading

Frequently Asked Questions

Can I build an MCP App with React?

Yes. React runs inside the MCP App view, which an AI host such as ChatGPT or Claude renders in a sandboxed iframe. The official @modelcontextprotocol/ext-apps/react subpath provides useApp for the bridge connection plus useHostStyles, useHostStyleVariables, useHostFonts, useDocumentTheme, and useAutoResize. Your MCP server still owns tools, resources, schemas, authentication, and backend work.

Which packages does a React MCP App need in November 2026?

The npm latest tag for @modelcontextprotocol/ext-apps is 2.0.4, and it peers on the split MCP TypeScript SDK v2 packages (@modelcontextprotocol/server, client, and core at ^2.0.0), zod ^4.2.0, and React 17, 18, or 19. Install react, react-dom, zod, @modelcontextprotocol/ext-apps, and @modelcontextprotocol/server, plus vite, @vitejs/plugin-react, and vite-plugin-singlefile for the view bundle. Do not install the old @modelcontextprotocol/sdk v1 package with ext-apps 2.x.

Where should I register tool result handlers in a React MCP App?

Inside the onAppCreated callback you pass to useApp. It runs after the App instance exists and before the ui/initialize handshake, so the host cannot send tool input or a tool result before your handler is ready. ext-apps 2.x warns when the first handler for toolinput, toolinputpartial, toolresult, or toolcancelled is registered after the handshake, and throws instead when strict is true.

How should a React MCP App validate tool results?

Share one Zod schema between the server and the view. The server passes it as outputSchema to registerAppTool, and the view calls schema.safeParse(result.structuredContent) before writing to React state. TypeScript types disappear at runtime, so a cast does not protect the view from a stale or malformed result. ext-apps 2.x sets Zod to jitless mode by default, so this works under the default MCP Apps CSP without unsafe-eval.

What does useApp do in the MCP Apps React SDK?

useApp creates an App instance, calls onAppCreated, opens a PostMessageTransport to window.parent, and performs the initialization handshake. It returns app (null until connected), isConnected, and error. It reads its options only on the first mount and does not close the App on unmount, which avoids duplicate connections during the React Strict Mode double mount. It forwards only autoResize and strict to the App; create the App manually for other options.

How should a React MCP App match ChatGPT or Claude styling?

Call useHostStyles(app, app?.getHostContext()). It applies the host CSS variables, theme, and fonts, then updates them when the host sends ui/notifications/host-context-changed. Style components with variables such as --color-background-primary and --color-text-primary, and always include CSS fallbacks because every host-context field is optional.

Can a React MCP App call another server tool?

Yes, when the host advertises the serverTools capability. Call app.callServerTool with a tool name and arguments, check result.isError for tool-level failures, and catch rejected promises for transport, timeout, unknown-tool, or host failures. Mark helper tools with _meta.ui.visibility set to ["app"] so the model does not call them, and keep writes and permission checks in the server tool.

How do I test a React MCP App?

Use three layers. Component tests render presentation components with plain props. Protocol tests connect an MCP client and check tools/list, resources/read, the MCP App MIME type, and schema-valid structuredContent. Browser tests render the resource in an MCP App host runtime such as the sunpeak inspector and cover connecting, partial input, results, errors, cancellation, themes, display modes, narrow widths, and missing host capabilities.