MCP App Navigation: Internal Routes, External Links, Modals, and Close Actions (October 2026)

MCP App navigation has to route internal views inside the iframe while asking the host to open trusted external links.
MCP App tutorials usually stop once the host renders the first resource. That leaves a practical question unanswered: what happens when the user clicks around?
Navigation is different inside an MCP App because your UI is not the top-level web page. It is a sandboxed iframe inside ChatGPT, Claude, or another MCP host. Internal routes can stay in the iframe. External URLs should go through the host bridge. Write actions should go through MCP tools. ChatGPT also has host-specific APIs for opening external flows, modals, close actions, and fullscreen destinations.
TL;DR: Keep internal views inside the resource iframe. Check the host’s openLinks capability before sending ui/open-link for a trusted external URL, and handle both denial and transport failure. Feature-detect ChatGPT extensions such as openExternal, modals, and close actions. Test reloads, links, and fallbacks in each target host.
Choose the Right Navigation Path
The first question is whether a click changes the current view, opens a website, writes data, or asks the host to change its own UI. These are separate contracts because the resource lives inside a sandboxed iframe.
The host owns the outer shell and link policy. The view owns local navigation, while the server owns writes and authorization. Map each click before picking an API:
| Job | Preferred path | Why |
|---|---|---|
| Move between views inside the same resource | Client-side router or local state | The user stays inside the iframe |
| Open a trusted external URL | ui/open-link or App.openLink | The host can apply link policy |
| Run a backend action | MCP tool call | The model and host keep a typed action record |
| Use an optional host feature | Feature-detected host extension | Other MCP hosts may not support it |
Keep Internal Routes Internal
Internal routes are screens that belong to the same resource. A list item opens a detail panel. A dashboard switches to a chart. A wizard moves from “review” to “confirm.” None of those needs a top-level browser navigation.
Use a router or local state. For a portable resource, hash routes keep the path after # and do not require your UI resource server to handle /invoice/123 on reload. ChatGPT’s host-backed navigation also mirrors BrowserRouter history into its navigation UI. If you choose browser history, test deep links and reloads in every host you support.
import { HashRouter, Link, Route, Routes, useParams } from 'react-router-dom';
import { SafeArea, useToolData } from 'sunpeak';
interface InvoiceSummary {
id: string;
number: string;
customer: string;
total: string;
}
interface InvoiceOutput {
invoices: InvoiceSummary[];
}
function InvoiceList() {
const { output } = useToolData<unknown, InvoiceOutput>();
return (
<div className="space-y-2">
{output?.invoices.map((invoice) => (
<Link
className="block rounded-md border p-3 hover:bg-slate-50"
key={invoice.id}
to={`/invoice/${invoice.id}`}
>
<span className="font-medium">{invoice.number}</span>
<span className="ml-2 text-sm opacity-70">{invoice.customer}</span>
</Link>
))}
</div>
);
}
function InvoiceDetail() {
const { invoiceId } = useParams();
const { output } = useToolData<unknown, InvoiceOutput>();
const invoice = output?.invoices.find((item) => item.id === invoiceId);
if (!invoice) return <p>Invoice not found.</p>;
return (
<article>
<Link className="text-sm underline" to="/">
Back to invoices
</Link>
<h1 className="mt-4 text-lg font-semibold">{invoice.number}</h1>
<p>{invoice.customer}</p>
<p className="mt-2">{invoice.total}</p>
</article>
);
}
export function InvoiceResource() {
return (
<SafeArea className="p-4 font-sans">
<HashRouter>
<Routes>
<Route path="/" element={<InvoiceList />} />
<Route path="/invoice/:invoiceId" element={<InvoiceDetail />} />
</Routes>
</HashRouter>
</SafeArea>
);
}
That pattern is fine when the route only changes what the resource displays. A hash route such as #/invoice/inv_123 can survive a reload of the same UI resource, but the invoice data still has to be available after that reload. If a route matters to the model later, update model-visible context with a short selection, such as “The user is viewing invoice INV-1042.” Do not send every route transition to the model.
Do Not Use Links for Writes
A link can move a user to another screen. A tool should change data.
For example, this is a routing action:
- Open ticket
TK-1234 - Switch to the “activity” tab
- Expand a chart fullscreen
This is a tool action:
- Assign ticket
TK-1234to a teammate - Submit an invoice update
- Create a reservation
- Cancel a subscription
The difference matters because the host and model understand MCP tool calls. A write can have an input schema, tool annotations, permission prompts, auth checks, server validation, and a tool result. A link click has none of that unless you build it back by hand.
For UI buttons that perform app-only actions, use an app-visible tool:
import { z } from 'zod';
import type { AppToolConfig } from 'sunpeak/mcp';
export const tool: AppToolConfig = {
title: 'Save Invoice Note',
description: 'Save a note the user entered in the invoice app UI.',
annotations: {
readOnlyHint: false,
destructiveHint: false,
openWorldHint: true,
},
_meta: {
ui: {
visibility: ['app'],
},
},
};
export const schema = {
invoiceId: z.string(),
body: z.string().min(1).max(2000),
};
In sunpeak’s tool-file format, tool holds metadata and the separate schema export describes input. Add a handler that checks authorization and validates the note before saving it. App-only visibility keeps the helper out of the model-facing list; it does not authorize the caller. The MCP Apps overview lists refresh, pagination, and form submissions as app-only tool uses.
Open External Links Through the Host
External links leave the iframe. The portable MCP Apps request is ui/open-link, exposed in the low-level SDK as App.openLink.
The request is small:
await app.openLink({ url: 'https://docs.example.com/invoices/INV-1042' });
The host may open the link, show a confirmation prompt, or deny it. The MCP Apps host capability reference exposes openLinks, which you can check after the bridge connects. A denial can return isError: true; a transport or bridge problem can reject the promise. Handle both.
import { useState } from 'react';
interface LinkBridge {
getHostCapabilities(): { openLinks?: object } | undefined;
openLink(params: { url: string }): Promise<{ isError?: boolean }>;
}
export function DocsLinkButton({ app, href }: { app: LinkBridge; href: string }) {
const [error, setError] = useState<string | null>(null);
async function openDocs() {
setError(null);
if (!app.getHostCapabilities()?.openLinks) {
setError('This host cannot open links from the app.');
return;
}
try {
const result = await app.openLink({ url: href });
if (result.isError) setError('The host did not open this link.');
} catch {
setError('The link request failed.');
}
}
return (
<div>
<button type="button" onClick={openDocs}>
Open docs
</button>
{error && (
<p className="mt-2 text-sm" role="status">
{error} Copy this URL instead: {href}
</p>
)}
</div>
);
}
The fallback matters. Some hosts do not advertise link opening, and some workspaces restrict destinations. Show a copyable URL only after your app has validated it; otherwise give an inline summary or a safe server-side alternative.
A successful openLink response means the host accepted the navigation request. It does not prove that the destination loaded or that the user finished checkout, OAuth, or another external task. Verify completion through your server’s own callback or status tool before showing a success state in the MCP App.
Do not rely on window.open, target="_blank", or parent-frame access. MCP App iframes are sandboxed on purpose. The host bridge is the contract.
ChatGPT openExternal and redirectUrl
ChatGPT also exposes window.openai.openExternal({ href, redirectUrl }). Use it when you need ChatGPT’s return-to-conversation behavior. For an approved redirect target, ChatGPT appends ?redirectUrl=... by default; pass redirectUrl: false when the destination must not receive it. A checkout or account handoff must treat that URL as a navigation hint, never as proof of identity or authorization.
async function openCheckout(app: LinkBridge, checkoutUrl: string) {
const openai = typeof window === 'undefined' ? undefined : window.openai;
if (openai?.openExternal) {
await openai.openExternal({
href: checkoutUrl,
redirectUrl: true,
});
return;
}
if (!app.getHostCapabilities()?.openLinks) {
throw new Error('This host cannot open external links.');
}
const result = await app.openLink({ url: checkoutUrl });
if (result.isError) throw new Error('The host denied this link.');
}
Feature-detect the method because optional host features vary across hosts and accounts. Validate checkoutUrl before using either path, and handle a rejected openExternal request in the calling UI. Claude Connectors and other compatible hosts should still render the component and offer the portable link path.
ChatGPT uses standard _meta.ui.csp for the app resource CSP, such as connectDomains, resourceDomains, and frameDomains. One ChatGPT-specific field still matters for trusted external redirects: redirect_domains inside _meta["openai/widgetCSP"].
export const resourceMeta = {
_meta: {
ui: {
csp: {
connectDomains: ['https://api.example.com'],
resourceDomains: ['https://cdn.example.com'],
},
domain: 'https://invoice-app.example.com',
},
'openai/widgetCSP': {
redirect_domains: ['https://billing.example.com'],
},
},
};
Keep this list tight. redirect_domains belongs on the resource contents metadata and is only for trusted ChatGPT openExternal redirect targets; it does not replace URL validation in your app. For ordinary docs and help links, the portable open-link path is enough.
Modals and Close Actions Are Host Features
ChatGPT can open host-controlled modals with window.openai.requestModal. The modal can use the current template or another registered template URI from the same app.
async function showTerms() {
const openai = typeof window === 'undefined' ? undefined : window.openai;
if (openai?.requestModal) {
try {
await openai.requestModal({ template: 'ui://invoice-app/terms.html' });
return;
} catch {
// The host may reject the modal request.
}
}
setInlinePanel('terms');
}
The fallback should be a normal inline panel. A modal is a presentation option, not the only way to complete the task.
The same rule applies to close actions. ChatGPT widgets can request close from the UI:
async function finishFlow() {
await saveDraft();
const openai = typeof window === 'undefined' ? undefined : window.openai;
if (openai?.requestClose) {
try {
await openai.requestClose();
return;
} catch {
// Keep the completion state visible if the host does not close.
}
}
setStatus('complete');
}
A server result can also ask ChatGPT to close a widget with openai/closeWidget metadata. That is useful after a compact confirmation flow, but it should not be the only success state. Other hosts may ignore the field, and even ChatGPT users may need visible confirmation before the app disappears.
setOpenInAppUrl and Fullscreen Destinations
ChatGPT fullscreen surfaces can expose an “Open in app” destination. By default, that target uses the current iframe path. window.openai.setOpenInAppUrl({ href }) lets you point it at a better URL, such as the same record in your hosted product.
import { useEffect } from 'react';
useEffect(() => {
if (!window.openai?.setOpenInAppUrl || !invoice) return;
window.openai.setOpenInAppUrl({
href: `https://app.example.com/invoices/${invoice.id}`,
});
}, [invoice]);
Use this for product-owned pages that are useful outside ChatGPT. Do not use it to smuggle internal iframe routes into a top-level browser context if those routes only work with host-provided tool data.
If the hosted page needs the same authorization state as your MCP server, design that flow explicitly. The ChatGPT App iframe, your MCP server, and your product web app may have different session models.
Routing, App State, and Model Context
Internal routing answers “what should the user see right now?” App state answers “what should survive app updates?” Model context answers “what should the model know after this UI interaction?”
Do not collapse those into one global object.
| State | Example | Store it where |
|---|---|---|
| Current tab | activity | Router, component state, or app state |
| Selected record | invoiceId: inv_123 | App state if follow-up turns need it |
| Model-visible summary | User selected invoice INV-1042 | ui/update-model-context |
| Draft text | Unsaved note body | Local component state |
| Server write | Saved note | MCP tool and backend database |
For a detail route, you might update app state and model context only when the selection becomes meaningful:
import { useEffect } from 'react';
import { useAppState, useUpdateModelContext } from 'sunpeak';
function useSelectedInvoice(invoice: InvoiceSummary | null) {
const [, setAppState] = useAppState<{ selectedInvoiceId: string } | null>(null);
const updateModelContext = useUpdateModelContext();
const invoiceId = invoice?.id;
const invoiceNumber = invoice?.number;
useEffect(() => {
if (!invoiceId || !invoiceNumber) return;
setAppState({ selectedInvoiceId: invoiceId });
void updateModelContext({
content: [
{
type: 'text',
text: `The user is viewing invoice ${invoiceNumber}.`,
},
],
}).catch(() => {
console.warn('Host did not accept the selected invoice context.');
});
}, [invoiceId, invoiceNumber, setAppState, updateModelContext]);
}
Keep this short. Stable primitive dependencies avoid sending the same context on each object re-render. In a production view, handle a rejected context update and do not claim the model saw the selection until the host accepts it. The model does not need a route dump, query string, scroll position, or every clicked tab.
Security Rules for Navigation
MCP App navigation bugs are often security bugs with a UI face.
Use these rules:
- Never pass arbitrary model-generated URLs directly into
openLink. - Parse and validate URLs on the server or against a local allowlist before opening them.
- Prefer fixed product origins and typed IDs over full URLs in tool results.
- Keep
redirect_domainsas small as possible for ChatGPT Apps. - Do not put secrets, tokens, or one-time auth codes in iframe routes.
- Do not use iframe navigation as a substitute for OAuth.
- Treat denied host actions as expected states.
Here is a simple URL guard:
const allowedOrigins = new Set(['https://docs.example.com', 'https://app.example.com']);
export function getTrustedUrl(rawUrl: string) {
const url = new URL(rawUrl);
if (url.protocol !== 'https:' || url.username || url.password || !allowedOrigins.has(url.origin)) {
throw new Error(`External origin is not allowed: ${url.origin}`);
}
return url.toString();
}
Do this before the URL reaches the resource. If the model can invent href values, reduce them to safe targets such as a route name or resource ID. Check the final destination of any redirect endpoint you control, and avoid putting tokens or sensitive data in URL query strings. An origin check cannot make an open redirect on that origin safe.
Test the Navigation Matrix
Navigation needs tests because host behavior differs in ways a standalone browser page will not catch.
At minimum, test these cases:
- Initial render at the default route
- Direct entry to a detail route
- Back navigation from detail to list
- Route state after a tool result update
- App state restoration after remount
- Mobile width with long labels and nested routes
- External link request success
- External link request denied
- Host does not support external links
- ChatGPT
openExternalpath, if used - Inline fallback for ChatGPT-only modals and close actions
In sunpeak, run the app in the local inspector and write Playwright tests against the rendered app frame:
import { expect, test } from 'sunpeak/test';
test('opens invoice detail inside the app iframe', async ({ inspector }) => {
// tests/simulations/show-invoices.json supplies INV-1042.
const result = await inspector.renderTool('show-invoices');
expect(result.source).toBe('fixture');
const app = result.app();
await app.getByRole('link', { name: /INV-1042/ }).click();
await expect(app.getByRole('heading', { name: 'INV-1042' })).toBeVisible();
await app.getByRole('link', { name: /Back to invoices/ }).click();
await expect(app.getByRole('link', { name: /INV-1042/ })).toBeVisible();
});
Use a focused unit test for the exact bridge request:
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test, vi } from 'vitest';
test('requests external links through the host bridge', async () => {
const openLink = vi.fn().mockResolvedValue({});
render(
<DocsLinkButton
app={{ getHostCapabilities: () => ({ openLinks: {} }), openLink }}
href="https://docs.example.com/invoices/INV-1042"
/>,
);
await userEvent.click(screen.getByRole('button', { name: 'Open docs' }));
expect(openLink).toHaveBeenCalledWith({
url: 'https://docs.example.com/invoices/INV-1042',
});
});
test('shows a copyable URL when the host denies a link', async () => {
render(
<DocsLinkButton
app={{
getHostCapabilities: () => ({ openLinks: {} }),
openLink: vi.fn().mockResolvedValue({ isError: true }),
}}
href="https://docs.example.com/invoices/INV-1042"
/>,
);
await userEvent.click(screen.getByRole('button', { name: 'Open docs' }));
expect((await screen.findByRole('status')).textContent).toContain('Copy this URL instead');
});
In sunpeak, renderTool(name, input) calls the real server when input is supplied. Omitting it uses a matching simulation fixture when available. Keep a small real-server test for tool data, and use the fixture for the route matrix. For link tests, assert the exact bridge request and the denial or missing-capability path, not just the button’s presence.
For ChatGPT-specific APIs, mock window.openai in a unit test and keep a small live smoke test for review:
test('uses ChatGPT openExternal when available', async () => {
const openExternal = vi.fn().mockResolvedValue(undefined);
vi.stubGlobal('openai', { openExternal });
try {
await openCheckout(
{ getHostCapabilities: () => ({ openLinks: {} }), openLink: vi.fn() },
'https://billing.example.com/checkout/session_123',
);
expect(openExternal).toHaveBeenCalledWith({
href: 'https://billing.example.com/checkout/session_123',
redirectUrl: true,
});
} finally {
vi.unstubAllGlobals();
}
});
Also run the same component with window.openai absent and assert the portable openLink call. This catches the cross-host branch before a live host smoke test.
A Practical Decision Tree
When a user clicks something in an MCP App, ask one question first: does this stay inside the resource?
If yes, use internal routing or local state. If the new view matters to future model turns, update app state or model context with a short summary.
If no, ask whether the click opens an external page or changes backend data. External pages go through ui/open-link or window.openai.openExternal when ChatGPT-specific redirect behavior is needed. Backend changes go through tools.
If the click changes the host surface, such as modal, fullscreen, close, or “open in app,” treat it as an optional host feature. Feature-detect it and provide inline fallback UI.
That split keeps the app portable, testable, and easier to review.
Where sunpeak Fits
The fastest way to debug MCP App navigation is to get out of the live host loop. With sunpeak, you can run a local inspector, render the same tool output in ChatGPT and Claude-style host replicas, switch display modes, inspect app state, and assert bridge requests in tests.
For a new app:
npx sunpeak new
For an existing MCP server:
npx sunpeak inspect --server http://localhost:8000/mcp
Navigation is exactly the kind of behavior worth testing locally because the failure cases are slow to reproduce by hand: denied external links, missing host capabilities, iframe route restoration, mobile clipping, and ChatGPT-only APIs running in a non-ChatGPT host.
Start with the MCP App framework, inspect your current server with the sunpeak inspector, or add coverage with the MCP testing framework. The goal is simple: when a user clicks, the app should either route, ask the host, or call a tool, and your tests should prove which path happened.
Get Started
npx sunpeak newFurther Reading
- MCP App resource metadata - CSP, permissions, and ChatGPT widget fields
- MCP App actions - callServerTool, sendMessage, and updateModelContext
- MCP App capability detection - host features, fallbacks, and tests
- MCP App CSP domains - connectDomains, resourceDomains, and frameDomains
- MCP App lifecycle - connect, tool input, results, and teardown
- Cross-host compatibility testing for MCP Apps
- MCP App forms - validation and submit actions
- MCP App framework
- ChatGPT App framework
- Claude Connector framework
- sunpeak docs - MCP Apps openLink
- MCP Apps open-link request reference
- OpenAI guide to MCP Apps UI and optional ChatGPT extensions
- OpenAI reference for host-backed navigation and openExternal
- MCP Apps host capabilities reference
Frequently Asked Questions
How should navigation work inside an MCP App?
Use client-side routing for screens inside the resource iframe. A hash router avoids depending on server fallback routes when the host reloads the iframe; ChatGPT also mirrors BrowserRouter history into its navigation UI. For external URLs, check the host openLinks capability and use App.openLink or ui/open-link. Keep writes behind server tools.
Can an MCP App open an external link?
Yes, when the host advertises openLinks. The portable ui/open-link request is exposed as App.openLink. Check the capability after the bridge connects, use a trusted absolute URL, and handle an isError response or a rejected request. Keep a copyable URL or useful inline fallback if the host cannot open it.
What is the difference between App.openLink and window.openai.openExternal?
App.openLink is the portable MCP Apps bridge request for opening a URL through the host. window.openai.openExternal is a ChatGPT-specific compatibility API with ChatGPT-only options such as redirectUrl. For cross-host MCP Apps, use the portable bridge as the default path and keep window.openai calls behind feature detection when you need ChatGPT-specific behavior.
What is redirect_domains in a ChatGPT App?
redirect_domains is a ChatGPT-specific allowlist in resource _meta["openai/widgetCSP"]. ChatGPT uses it for approved window.openai.openExternal redirect targets. On approved targets, ChatGPT appends a redirectUrl back to the conversation by default; pass redirectUrl: false to suppress it. Standard _meta.ui.csp covers connect, resource, and frame domains.
Should an MCP App use React Router?
Yes. A hash router keeps paths inside the resource URL and usually needs no server rewrite. BrowserRouter can also work, and ChatGPT mirrors its history into host navigation, but verify reloads and deep links in every target host. Keep routed views in the same resource and test them inside the host iframe.
Can a ChatGPT App close its widget?
ChatGPT-specific widgets can request close from the UI with window.openai.requestClose. A server response can also ask ChatGPT to close a widget by setting openai/closeWidget in response metadata. Treat this as host-specific behavior and provide a normal inline completion state for hosts that do not support close actions.
How do I test MCP App navigation and external links?
Test internal routes with inspector E2E tests, including direct entry, back navigation, state restoration, and mobile widths. Mock host bridge requests for external links, assert the exact URL, and test denial or unavailable-capability paths. For ChatGPT-only openExternal behavior, add a focused compatibility test and a small live smoke test before submission.