Let end users add and authenticate MCP servers from the browser with @assistant-ui/react-mcp.
@assistant-ui/react-mcp lets end users see a list of connectors, sign in via OAuth, paste a custom server URL, and have the resulting tools flow into the chat. It runs the MCP client in the browser. To wire a fixed set of servers into your API route instead, see server-side MCP.
A server reaches the user in one of two ways:
- Connector: a preset you declare with
defineConnector(...). The user clicks Connect and completes auth. - Custom server: the user supplies the URL, name, and auth in
<McpAddFormPrimitive>. Do not render the add UI to disable it.
Both share one connection lifecycle, one persisted state, and one tool registration path.
How it works
AuiConfig({ mcp: McpManagerResource({ connectors }) })
│
├─ connection lifecycle, server lookup, OAuth and bearer auth
├─ mounts a modelContext scope when no chat runtime provides one
└─ registers connected tools as frontend tools, so your chat sees themThe manager is one resource, mounted like any other scope. It supports OAuth (PKCE with dynamic client registration), bearer tokens, and no auth, over Streamable HTTP. Token refresh runs inside the MCP SDK on a 401; this package handles persistence and the redirect step.
Because the client runs in the browser, a tool call goes straight from the page to the MCP server. The server must allow your origin through CORS. Your API route sees a result only when it comes back with the conversation.
Setup
Install
npm install @assistant-ui/react-mcpMount the manager
Declare your connectors and provide the mcp scope:
"use client";
import { AuiConfig, AuiProvider, useAui } from "@assistant-ui/react";
import { McpManagerResource, defineConnector } from "@assistant-ui/react-mcp";
const connectors = [
defineConnector({
id: "linear",
name: "Linear",
url: "https://mcp.linear.app",
auth: { type: "oauth", scopes: ["read"] },
icon: "/icons/linear.svg",
}),
defineConnector({
id: "weather",
name: "Weather",
url: "https://mcp.example.com/weather",
auth: { type: "none" },
connectionTimeout: 10_000,
}),
];
export function Providers({ children }: { children: React.ReactNode }) {
const aui = useAui();
const config = AuiConfig({
mcp: McpManagerResource({
connectors,
connectionTimeout: 15_000,
}),
});
return (
<AuiProvider extends={aui} config={config}>
{children}
</AuiProvider>
);
}McpManagerResource takes these options:
connectors: the presets above. Eachidmust be unique and must not contain__. The id is used for server lookup, OAuth routing, and tool names such aslinear__search.storage: where custom servers and credentials persist. Defaults toMcpLocalStorage(); see Storage.oauthRedirectUri: defaults to${window.location.origin}/mcp/callback.autoConnect: defaults totrue. Servers that need no sign-in, or already have saved credentials, connect on mount.connectionTimeout: milliseconds. Bounds the readiness flow (connect()pluslistTools()) with a clear error. A connector or custom server can override it.
A connector or custom server also accepts icon, requireApproval (see Tool approvals), elicitation (see Form elicitation), and cache: { defaultTtlMs }, which sets the MCP client's default cache lifetime.
Pick your UI
Drop-in shadcn dialog (recommended for most apps). Install the mcp-config component, then render <McpConfigDialog /> anywhere inside the provider. It includes a trigger, server cards, status badges, error banners, and the add form:
npx shadcn@latest add @assistant-ui/mcp-configThe @assistant-ui namespace resolves the Radix or Base UI flavor from your project's style through the style-aware registry entry in components.json. Without that entry, add by direct URL instead:
npx shadcn@latest add https://r.assistant-ui.com/base/mcp-config.jsonMain Component
npm install @assistant-ui/react-mcp@^0.1.29 @assistant-ui/store@^0.3.25assistant-ui dependencies
npm install @assistant-ui/react-mcp@^0.1.29 @assistant-ui/store@^0.3.25 @base-ui/react class-variance-authorityshadcn/ui dependencies
npm install @base-ui/reactimport { McpConfigDialog } from "@/components/assistant-ui/elements/mcp-config.aui";
export default function Page() {
return (
<header className="flex items-center justify-between">
<h1>My app</h1>
<McpConfigDialog />
</header>
);
}Pass children to replace the trigger: <McpConfigDialog><Button variant="ghost">Servers</Button></McpConfigDialog>.
Compose your own from primitives. Four unstyled, data-*-driven namespaces are available: McpManagerPrimitive, McpServerPrimitive, McpAddFormPrimitive, and McpElicitationPrimitive. The iteration primitives take a render function and wrap each item in a server scope, so the nested McpServerPrimitive.* reads the right server:
"use client";
import {
McpManagerPrimitive,
McpServerPrimitive,
} from "@assistant-ui/react-mcp";
const ServerCard = () => (
<McpServerPrimitive.Root>
<McpServerPrimitive.Icon />
<McpServerPrimitive.Name />
<McpServerPrimitive.Status />
<McpServerPrimitive.ConnectButton>Connect</McpServerPrimitive.ConnectButton>
<McpServerPrimitive.DisconnectButton>Disconnect</McpServerPrimitive.DisconnectButton>
<McpServerPrimitive.OAuthLink>Authorize</McpServerPrimitive.OAuthLink>
<McpServerPrimitive.RemoveButton>Remove</McpServerPrimitive.RemoveButton>
<McpServerPrimitive.Error />
</McpServerPrimitive.Root>
);
export default function McpPage() {
return (
<McpManagerPrimitive.Root>
<h2>Connectors</h2>
<McpManagerPrimitive.Connectors>
{() => <ServerCard />}
</McpManagerPrimitive.Connectors>
<h2>Your servers</h2>
<McpManagerPrimitive.CustomServers>
{() => <ServerCard />}
</McpManagerPrimitive.CustomServers>
<McpManagerPrimitive.AddCustomTrigger>
Add custom server
</McpManagerPrimitive.AddCustomTrigger>
</McpManagerPrimitive.Root>
);
}ConnectButton, DisconnectButton, OAuthLink, and RemoveButton render only when the server's state matches, so you do not gate them. RemoveButton never renders on a connector, because the user cannot remove one. To disable custom servers, omit AddCustomTrigger and CustomServers. McpServerPrimitive.Tools and McpServerPrimitive.ToolName list the tools a server published.
Add the custom-server form
<McpAddFormPrimitive.Root onSubmitted={() => closeDialog()}>
<label>Name <McpAddFormPrimitive.NameField /></label>
<label>URL <McpAddFormPrimitive.UrlField /></label>
<label>Auth <McpAddFormPrimitive.AuthSelect /></label> {/* none | bearer | oauth */}
<McpAddFormPrimitive.AuthFields /> {/* token or scope input depending on selection */}
<McpAddFormPrimitive.Error />
<McpAddFormPrimitive.Submit>Add</McpAddFormPrimitive.Submit>
<McpAddFormPrimitive.Cancel>Cancel</McpAddFormPrimitive.Cancel>
</McpAddFormPrimitive.Root>The form owns its draft state and submits through aui.mcp.addCustomServer(...). Pass a render function to AuthFields to customize it, and render your inputs with McpAddFormPrimitive.BearerTokenField and McpAddFormPrimitive.ScopesField so they stay bound to the form.
A server with bearer or oauth auth must use HTTPS, or plain HTTP on a loopback host: localhost, *.localhost, an address in 127.0.0.0/8, or [::1]. The form rejects any other authenticated http:// URL with Authenticated servers must use HTTPS or loopback HTTP. Serve the server over HTTPS or reach it through a local tunnel.
Handle the OAuth callback
Add a route at /mcp/callback, or wherever oauthRedirectUri points:
"use client";
import { McpOAuthCallback } from "@assistant-ui/react-mcp";
import { useRouter } from "next/navigation";
import { Providers } from "../../providers";
export default function Callback() {
const router = useRouter();
return (
<Providers>
<McpOAuthCallback onComplete={() => router.replace("/mcp")} />
</Providers>
);
}The callback reads state plus either code or an OAuth error from the URL, finds the server id encoded in state, checks the full state value against the pending authorization request, and completes auth on that server. useMcpOAuthCallback is the hook form, which returns { status, serverId, error }.
The user reaches the provider's sign-in page through McpServerPrimitive.OAuthLink, which renders once the server has an authorizationUrl.
Use the tools in chat
McpManagerResource registers connected tools as frontend tools in the modelContext scope. Any chat runtime in the same store, such as useChatRuntime, uploads them with each request. Send the completed tool results back so the model can continue:
"use client";
import { lastAssistantMessageIsCompleteWithToolCalls } from "ai";
import { useChatRuntime } from "@assistant-ui/ai-sdk";
export function Chat() {
const runtime = useChatRuntime({
sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,
});
/* … */
}Your API route must forward the uploaded tools to the model, with aiToolkit.tools({ frontend: tools }) or frontendTools(tools); see Backend. useChatRuntime() targets /api/chat by default; for another endpoint, see Custom transport.
The tools register again whenever a server connects, disconnects, or its tool list changes. The manager listens for the server's tool-list change notifications and refreshes after a short debounce.
Without a chat runtime, the manager brings its own minimal modelContext, and tools are still callable directly:
// In an event handler, never in render.
const aui = useAui();
const out = await aui.mcp.server({ id: "linear" }).callTool("search", { q });Tool names
A tool is registered as serverId__toolName when that name has only letters, numbers, underscores, and dashes and fits in 64 characters. Otherwise it gets a stable alias that starts with __mcp_, contains a hash of the server id and tool name, and keeps a readable suffix of the tool name. Persisted server ids never change, and calls route back to the original server and tool.
Because the server id is part of the name, two servers that publish search do not conflict. Two different server and tool pairs that map to the same registered name do. For example, connector a_ with tool b, and connector a with tool _b, both map to a___b; a hash collision would too. Neither tool is registered, and the console warns once per name:
[assistant-ui] Different MCP tools map to the tool name "a___b"; none of them is registered.There is no prefix option here. Rename one of your connector ids. Custom server ids are generated, so a collision involving one clears when the user removes that server.
Use getMcpToolName(serverId, toolName) to get the registered name for a renderer, because the alias form is not something to build by hand. It works before the server connects. Server state and direct callTool() calls keep the original MCP tool name.
import { MessagePrimitive } from "@assistant-ui/react";
import { getMcpToolName } from "@assistant-ui/react-mcp";
<MessagePrimitive.Parts
components={{
tools: {
by_name: {
[getMcpToolName("github", "get_pull_request_review_comments")]:
ReviewCommentsToolUI,
},
},
}}
/>Tool approvals
Every call the model makes to a connected tool asks first. Direct aui.mcp.server({ id }).callTool(...) calls from your own code skip this prompt, so confirm with the user yourself where that matters. The default thread opens the pending tool group and shows Allow and Deny in ToolFallback. A deny returns an error result, The user declined this tool call., to the model.
Set requireApproval: false on a connector, or in addCustomServer(...), to let that server's tools run without asking. Do this only for servers you trust. A runtime without human-in-the-loop support fails the call instead of running it.
Under the hood, the tool calls human() with this payload, and the UI resumes it with { approved: boolean }:
{ type: "mcp-tool-approval", serverId, serverName, toolName, arguments }A custom renderer replaces the default UI, so it must render the controls itself when the interrupt has that type:
import type { ToolCallMessagePartComponent } from "@assistant-ui/react";
const isMcpApproval = (payload: unknown) =>
typeof payload === "object" &&
payload !== null &&
"type" in payload &&
payload.type === "mcp-tool-approval";
const ReviewCommentsToolUI: ToolCallMessagePartComponent = ({
interrupt,
resume,
}) => {
if (isMcpApproval(interrupt?.payload)) {
return (
<div>
<button onClick={() => resume({ approved: true })}>Allow</button>
<button onClick={() => resume({ approved: false })}>Deny</button>
</div>
);
}
return null; // your tool UI
};This human() interrupt is separate from the server-side toolApproval gate that server-side MCP uses. For how a renderer receives an interrupt or an approval, see Tool UI.
Form elicitation
A connected server can ask the user for structured input through form-mode elicitation. The server waits for the response, so you must render a form for it. For a ready-made one, use the elicitation form component. Set elicitation: false on a connector or custom server to stop it advertising the capability.
Compose the form from McpElicitationPrimitive inside a server-scoped subtree:
import { McpElicitationPrimitive } from "@assistant-ui/react-mcp";
<McpElicitationPrimitive.Items>
{() => (
<McpElicitationPrimitive.Root>
<McpElicitationPrimitive.Message />
<McpElicitationPrimitive.Error />
<McpElicitationPrimitive.Fields>
{({ name, schema, value, setValue }) =>
(schema as { type?: string } | undefined)?.type === "boolean" ? (
<label>
{name}
<input
type="checkbox"
checked={value === true}
onChange={(event) => setValue(event.target.checked)}
/>
</label>
) : (
<input
name={name}
value={typeof value === "string" ? value : ""}
onChange={(event) => setValue(event.target.value)}
/>
)
}
</McpElicitationPrimitive.Fields>
<McpElicitationPrimitive.Accept>Submit</McpElicitationPrimitive.Accept>
<McpElicitationPrimitive.Decline>Decline</McpElicitationPrimitive.Decline>
<McpElicitationPrimitive.Cancel>Cancel</McpElicitationPrimitive.Cancel>
</McpElicitationPrimitive.Root>
)}
</McpElicitationPrimitive.Items>The field rules:
- Numeric fields can stay text inputs. Parseable strings are coerced.
- Boolean fields must use a checkbox. A string draft for a boolean is flagged invalid, not coerced.
- Clearing a field returns it to unanswered, so an empty text input is omitted from the response instead of sent as
"", unless the schema admits""through anenummember or a""default. - Render
enumproperties as a select. When""is not a member, the blank option is the unanswered state.
A client-side validation error keeps the elicitation pending, and McpElicitationPrimitive.Error shows the message.
Storage
All persisted state (custom server records, OAuth tokens, callback state, PKCE verifiers, client registrations) goes through one MCPStorage resource:
McpLocalStorage(): the default. Keys use theaui-mcp:prefix inwindow.localStorage.McpMemoryStorage(): an in-process map, for SSR and tests.McpCustomStorage({ ... }): your own load and save, for an app-controlled backend.
import { McpManagerResource, McpCustomStorage } from "@assistant-ui/react-mcp";
AuiConfig({
mcp: McpManagerResource({
connectors,
storage: McpCustomStorage({
scopeId: "api:/api/mcp",
loadCustomServers: async () => fetch("/api/mcp/servers").then((r) => r.json()),
saveCustomServers: async (records) =>
fetch("/api/mcp/servers", { method: "PUT", body: JSON.stringify(records) }),
loadAuthState: async (id) =>
fetch(`/api/mcp/auth/${id}`).then((r) => (r.ok ? r.json() : null)),
saveAuthState: async (id, state) =>
fetch(`/api/mcp/auth/${id}`, { method: "PUT", body: JSON.stringify(state) }),
clearAuthState: async (id) =>
fetch(`/api/mcp/auth/${id}`, { method: "DELETE" }),
}),
}),
});Warning
McpLocalStorage keeps tokens in plain text, readable by any script on the page. For anything beyond a prototype, use McpCustomStorage against an HTTP-only-cookie-backed endpoint, or wrap localStorage in your own encrypted serializer.
Scope. A storage can declare a scopeId, a stable identity for its backing data. Two storages with the same scopeId must read and write the same state. When the scope changes, the manager drops the previous scope's custom servers, sets isHydrated to false, loads the replacement, and reconnects bearer and oauth servers against it. Without a scopeId, swapping storage keeps the previous records loaded, and the next add or remove can write them into the replacement. Give every swappable storage a scopeId, or remount the manager instead. McpLocalStorage() derives one for the shared window.localStorage (pass scopeId yourself when you override its storage), and McpMemoryStorage() scopes each instance uniquely.
Failed loads. If loadCustomServers fails, the manager keeps later edits in memory and does not save them, because the persisted list is unknown. It logs the failed load and the first blocked edit. Remount the manager to retry before making changes that must persist.
URL binding. Credentials are stored with the MCP server URL and are used only for that exact endpoint. A custom storage must round-trip the serverUrl field passed to saveAuthState. If you write a bearer record yourself, set serverUrl to the server's configured url in the same record; both sides are normalized before comparing, so any spelling of the same URL matches. A mismatched credential is never sent. The server does not connect, and its lastError says the saved authentication belongs to a different URL. OAuth records written before this binding existed carry no serverUrl, so they surface that message once and the user connects again.
Auth
Auth is declared per connector or custom server:
{ type: "none" } // no auth header
{ type: "bearer", token?: "…" } // Authorization: Bearer …
{ type: "oauth", // PKCE, dynamic registration, refresh
scopes?: ["read"],
authorizationEndpoint?: "…", // overrides RFC 8414 discovery
tokenEndpoint?: "…",
registrationEndpoint?: "…",
clientId?: "…", // skip registration with a static client
clientSecret?: "…",
}The OAuth provider implements the MCP SDK's OAuthClientProvider. The SDK handles discovery (RFC 8414), dynamic client registration (RFC 7591), PKCE, token exchange, and refresh. This package persists the state through MCPStorage and handles the redirect. The server id is embedded in the OAuth state, so one /mcp/callback route serves every server. The authorization URL must use HTTPS or loopback HTTP.
Info
The 2026-07-28 spec revision deprecates dynamic client registration in favor of Client ID Metadata Documents, but keeps it for backwards compatibility with a minimum twelve-month window before removal. This package uses dynamic registration. Against an authorization server that offers only Client ID Metadata Documents and exposes no registration_endpoint, supply a pre-registered clientId instead.
State and methods
Read render-time state with useAuiState. Call imperative methods through useAui inside a callback, never during render:
import { useAui, useAuiState } from "@assistant-ui/react";
const isHydrated = useAuiState((s) => s.mcp.isHydrated);
const connectionState = useAuiState((s) => s.mcpServer.connectionState);
// ^ requires a server scope, such as McpServerPrimitive.Root
const aui = useAui();
// inside an event handler:
await aui.mcp.addCustomServer({ name, url, auth: { type: "bearer", token } });
await aui.mcp.server({ id }).connect();
await aui.mcp.server({ id }).callTool("echo", { text: "hi" });
// Resources: pass the previous page's nextCursor to continue.
const page = await aui.mcp.server({ id }).listResources({ cursor });
const preview = await aui.mcp.server({ id }).readResource(uri);connectionState is one of disconnected, authRequired, authPending, connecting, connected, or error. A server also exposes lastError, authorizationUrl, tools, and pendingElicitations. aui.mcp.removeServer(id) removes a custom server; it throws for a connector.
Security
- Tool descriptions and results are untrusted input. A server a user connects controls the text the model reads, so it can try to steer the model. That is why approval is on by default. Think before setting
requireApproval: falseon a server you do not run. - Calls run in the browser. The MCP server sees the user's own connection, and your route never proxies the call. Your route sees the result only when it comes back with the conversation.
- Stored tokens are readable by page scripts. See the storage warning above, and keep XSS defenses in place.
- HTTPS is enforced for authenticated servers, with a loopback exception for development.
- Published to WebMCP. The default WebMCP filter publishes every enabled frontend tool with an
execute, which includes these tools. Filter them out unless you want a browser agent calling them. A call from WebMCP cannot answer the approval prompt, so a gated tool fails there, while a tool on a server withrequireApproval: falseruns unasked.
Troubleshooting
A failed connection sets connectionState to error and lastError.message; nothing retries automatically, so show a reconnect control.
lastError or console message | Cause and fix |
|---|---|
Authenticated MCP server "id" must use HTTPS or loopback HTTP. | A bearer or oauth server on plain http:// to a non-loopback host. Use HTTPS. |
MCP server "id" has saved authentication for a different URL. Authenticate again to connect to ... | The stored credential was saved for another URL. Connect again, or fix serverUrl in custom storage. |
MCP server "id" timed out while connecting after 15000ms. | No answer within connectionTimeout. The phase reads listing tools when listing is the slow step. |
MCP server "id" failed to load saved authentication: ... | loadAuthState threw. Check your custom storage. |
MCP server "id" is not connected | callTool, listResources, or readResource ran before the server reached connected. |
MCP OAuth callback failed: ... | The callback page failed. The detail reads missing "state" parameter, state was not created by assistant-ui MCP, no pending OAuth authorization request for this server, OAuth state does not match the authorization request, or missing authorization code in callback URL. The pending request is gone (storage cleared, a second tab, or a stale URL), so start Authorize again. |
MCP server "id" authorization was interrupted before completion. | The server was disconnected or reconnected during the callback. Authorize again. |
MCP server id "..." must not contain "__", or received duplicate MCP server id | A connector id is invalid or repeated. Ids must be unique and cannot contain __. |
Cannot remove connector "id" | removeServer was called on a connector. Only custom servers are removable. |
A request fails with no lastError detail, or the browser console shows a CORS error | The MCP server does not allow your origin through CORS. |
The server is connected but the model never calls its tools | The route does not forward the uploaded tools, or sendAutomaticallyWhen is missing. See Use the tools in chat. |
[assistant-ui] Different MCP tools map to the tool name "..." | See Tool names. |
Scope and limits
Supported:
- Tool listing and calls, registered as frontend tools, with automatic refresh when the server's tool list changes
- Per-server approval before a tool runs
- Resource listing and reads, for browsers and previews you build
- Form-mode elicitation with fields and actions you compose
- OAuth, bearer, and no auth, over Streamable HTTP, with manual connect and disconnect
Not supported:
- SSE and stdio transports (use server-side MCP for those)
- Prompts and sampling
- Automatic reconnect with backoff
- Per-tool approval and per-tool enable or disable settings
- Built-in token encryption (use
McpCustomStorageagainst a server endpoint)