Skip to content

feat(react-core): implement MCP Apps ui/request-display-mode host handler - #6689

Closed
yannj-fr wants to merge 7 commits into
CopilotKit:mainfrom
yannj-fr:feat/mcp-apps-update-context-display-mode
Closed

yannj-fr wants to merge 7 commits into
CopilotKit:mainfrom
yannj-fr:feat/mcp-apps-update-context-display-mode

Conversation

@yannj-fr

Copy link
Copy Markdown
Contributor

What

Implements the host-side handler for the MCP Apps (ext-apps) ui/request-display-mode request in MCPAppsActivityRenderer. Today a widget calling app.requestDisplayMode(...) gets -32601 Method not found; this lets widgets switch between inline and fullscreen.

Changes

  • Handle ui/request-display-mode: grant inline / fullscreen, fall back to inline for pip and unknown values. The result reports the mode actually applied (may differ from the requested one), per the ext-apps contract.
  • Advertise displayMode and availableDisplayModes in hostContext at ui/initialize.
  • Render a fullscreen overlay with a host-provided close (X) button; Escape also exits. Host-initiated exits emit ui/notifications/host-context-changed so the widget stays in sync. Widget-initiated changes rely on the request response (no redundant notification).
  • Lock the background page scroll while fullscreen and restore it on exit (including on unmount).

Scope is intentionally minimal: inline + fullscreen only, pip falls back to inline. ui/update-model-context is left for a follow-up PR.

Spec

Follows @modelcontextprotocol/ext-apps (specification 2026-01-26): request/response { mode }, and ui/notifications/host-context-changed (Partial<HostContext>) as the mechanism to signal a host-initiated display-mode change.

Testing

  • New MCPAppsRequestDisplayMode.e2e.test.tsx (8 cases), mirroring the existing MCP Apps e2e style (MockMCPProxyAgent, renderWithCopilotKit): fullscreen grant, pip/unknown fallback, inline round-trip, ui/initialize advertisement, close button + Escape exit with host-context-changed, and scroll lock/restore.
  • All MCP Apps e2e tests pass (36/36); package type-check is green.
  • No .changeset/ files added.

A note from the contributors

We are the team at MCP Apps Builders, and we are happy to contribute this upstream. This is the first of a planned series of contributions aimed at bringing MCP Apps host support in CopilotKit to 100% coverage of the ext-apps protocol (next up: ui/update-model-context, then the remaining unimplemented ui/* methods and notifications). Feedback from maintainers on direction and conventions is very welcome.

Opening as a draft for early review.

🤖 Generated with Claude Code

…dler

Add the host-side handler for the MCP Apps (ext-apps) ui/request-display-mode
request so widgets can switch between inline and fullscreen instead of getting
-32601 Method not found.

- Handle ui/request-display-mode: grant "inline"/"fullscreen", fall back to
  "inline" for "pip" and unknown values; the result reports the applied mode.
- Advertise displayMode and availableDisplayModes in hostContext at
  ui/initialize.
- Render a fullscreen overlay with a host-provided close (X) button; Escape
  also exits. Host-initiated exits emit ui/notifications/host-context-changed
  so the widget stays in sync (widget-initiated changes rely on the response).
- Lock the background page scroll while fullscreen and restore it on exit
  (including on unmount).

Covered by MCPAppsRequestDisplayMode.e2e.test.tsx (8 cases), mirroring the
existing MCP Apps e2e test style.
@yannj-fr
yannj-fr marked this pull request as ready for review August 25, 2026 15:52

@BenTaylorDev BenTaylorDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this — and for the note about what you're planning next. The protocol layer here is accurate: I checked the method name, { mode } params/result, hostContext.displayMode / availableDisplayModes, and host-context-changed-as-partial-context against modelcontextprotocol/ext-apps src/spec.types.ts directly, and they all match. Scope is clean too — just the handler and its tests, no changeset, no incidental churn.

Since this is a fork PR, CI doesn't run automatically, so I ran it locally: the four MCPApps* e2e suites pass 36/36, the full react-core/src/v2 suite is 1410 passed / 2 skipped / 0 failed, and tsc --noEmit is clean apart from three pre-existing errors in my local tree from a stale web-inspector dist. I also mutation-checked the new tests — weakening the pip/unknown fallback kills two of them, and removing the host-context-changed emit kills the two exit-path ones — so they're testing real behavior.

Two things I'd like resolved before merge.

1. Please emit host-context-changed for widget-initiated changes too.

In the app SDK, App._hostContext is set at initialize (src/app.ts:1978) and afterwards merged only from hostcontextchanged (src/app.ts:450-451); requestDisplayMode() returns the result without updating the cache (src/app.ts:1788-1801). The SDK's own documented toggle reads that cache:

const ctx = app.getHostContext();
const newMode = ctx?.displayMode === "inline" ? "fullscreen" : "inline";

So with the response treated as sole authority: first click grants fullscreen, the widget's cached displayMode stays "inline", and the second click requests "fullscreen" again — the widget's own toggle can never get back to inline, and the user is stuck with the host X button. The reference host sends the notification and returns { mode } (examples/basic-host/src/implementation.ts:396-404). The test that asserts zero notifications would need to flip with it.

2. Fullscreen grows the container but not the render surface.

The container becomes 100vw/100vh, but the sandbox iframe keeps the widget-reported content height (Effect 2, MCPAppsActivityRenderer.tsx:821-832), and no containerDimensions is sent, so the widget can't discover the new space either — inside a 220px iframe, its own 100vh is 220px. I probed it:

container height after fullscreen: 100vh
iframe height after fullscreen:    220px

In practice that renders as a full-viewport white panel with the widget pinned at its inline height. Setting the iframe to height: 100% while fullscreen and sending containerDimensions on the mode change should cover it — the reference host drives the latter off a ResizeObserver (implementation.ts:311-322).

Smaller notes, none blocking:

  • The keydown listener is on window, so Escape won't fire while focus is inside the sandboxed iframe — which is most of the time in fullscreen. The test uses fireEvent.keyDown(window), so it passes either way. Worth qualifying in the description; the X button is the real exit path.
  • background: "#fff" is hardcoded on a full-viewport overlay, and v2 supports a .dark theme (globals.css:45). A token/CSS var would avoid a white flash in dark mode. Same thought for the inline zIndex: 2147483000 versus the cpk-* class conventions.
  • The overlay has no role="dialog"/aria-modal or focus trap, and position: fixed anchors to a transformed or filtered ancestor if a consumer app has one (v2's own chat CSS doesn't today). A createPortal(document.body) would be sturdier.
  • Two fullscreen instances can unlock body scroll when the first exits while the second is still up.
  • ui/initialize reads displayMode from the effect closure, whose deps deliberately exclude it — correct as written, since adding the dep would tear down and rebuild the iframe on every toggle. A short comment saying so would keep the next reader from "fixing" it.
  • Vue and Angular still answer -32601 for this method. Not asking you to take that on here; flagging it since this file carries the cross-frontend surface-contract note.
  • Unrelated to your change, but adjacent: PROTOCOL_VERSION is "2025-06-18" (:59) while ext-apps is at "2026-01-26", so the host now advertises newer-spec fields under an older handshake. Happy to take that separately.

If you can, the most valuable check on the next push is a real widget from the ext-apps examples: confirm the surface actually fills the viewport and that a getHostContext()-driven toggle can return to inline. Both items above are invisible to the jsdom suite. Looking forward to the ui/update-model-context follow-up.

@yannj-fr

Copy link
Copy Markdown
Contributor Author

Will update, separately I will check the full implementation of :

  • hostcontextchanged
  • styling provided at initialize step
  • capability negocitation (location, microphone....)
  • update-context

Respond to maintainer review on the ui/request-display-mode PR:

- Emit ui/notifications/host-context-changed for widget-initiated changes too,
  not only host-initiated ones. The app SDK caches hostContext solely from this
  notification (not from the request response), so a getHostContext()-driven
  widget toggle could otherwise never return to inline.
- Make fullscreen actually grow the render surface: the iframe now fills the
  overlay (height 100%) and the host advertises containerDimensions on the mode
  change, refreshed on viewport resize, so the widget can lay out against the
  real space.
- Robustness/a11y: role="dialog" + aria-modal + aria-label on the overlay, move
  focus to the close button, theme-aware overlay background (var(--background))
  to avoid a white flash in dark mode, and a ref-counted body scroll lock so
  concurrent fullscreen widgets do not unlock the page early.
- Document why the overlay uses position:fixed rather than a portal (the
  imperatively-mounted iframe would reload on reparent) and why the initialize
  effect intentionally omits displayMode from its deps.

Tests updated accordingly (host-context-changed on widget-initiated changes,
containerDimensions, fullscreen iframe fill); MCP Apps e2e 37/37, tsc clean.
@yannj-fr

Copy link
Copy Markdown
Contributor Author

Thank you for the exceptionally thorough review, including running the suites and mutation-checking the tests. Both blocking items are addressed in the latest push, along with most of the smaller notes. I merged latest main first; after a stale-dist rebuild the four MCPApps* e2e suites are green (37/37, incl. the new cases) and tsc --noEmit on react-core is clean.

1. Emit host-context-changed for widget-initiated changes too. Done. Both the widget-initiated ui/request-display-mode and the host-initiated exit now go through a single applyDisplayMode() that sets state and emits ui/notifications/host-context-changed (params are a partial McpUiHostContext, verified against spec.types.ts). So a getHostContext()-driven toggle can return to inline. The former "zero notifications" test was flipped to assert the notification fires for both directions.

2. Fullscreen render surface. Done. In fullscreen the iframe is set to height/width: 100% so it fills the overlay, and the host now advertises containerDimensions in the host-context-changed payload on the mode change, refreshed on viewport resize. New test asserts both the containerDimensions payload and the iframe fill.

Smaller notes:

  • a11y: the overlay now has role="dialog" + aria-modal + aria-label, and focus moves to the close button on enter.
  • Dark mode: overlay background is now var(--background) instead of #fff, so no white flash under .dark.
  • Concurrent fullscreen: the body scroll lock is ref-counted across instances, so the first widget to exit no longer unlocks the page while a second is still open.
  • Escape caveat: kept as a convenience and documented in a comment that it will not fire while focus is inside the sandboxed iframe, so the X button is the primary exit.
  • ui/initialize deps comment: added, explaining why displayMode is intentionally excluded from the effect deps.
  • Portal: I kept position: fixed rather than createPortal, with a code comment explaining why: the iframe is created imperatively and appended to the container, so reparenting it into a portal would reload the sandboxed srcdoc (losing widget state) on every fullscreen toggle. Open to a different approach if you would prefer the portal despite that.

Deferred to follow-ups (to keep this PR scoped to display-mode, as you noted):

  • Hardcoded theme: "light" and the PROTOCOL_VERSION vs ext-apps date mismatch: I will take these in a dedicated host-context PR.
  • Vue/Angular parity for this method: happy to follow up once the React shape is settled here.

Next up remains ui/update-model-context; I will open it as a separate PR. On the manual check with a real ext-apps example widget: I will confirm the viewport-fill and the getHostContext()-driven return-to-inline on the next pass and report back.

@yannj-fr
yannj-fr requested a review from BenTaylorDev August 25, 2026 19:07
…t-display-mode

Complete the display-mode host handling by respecting what the View declares:

- Read appCapabilities.availableDisplayModes from ui/initialize. A requested mode
  is granted only if the host supports it AND, when the View declared its modes,
  it appears there (ext-apps: "Host MUST NOT switch the View to a display mode
  that does not appear in its appCapabilities.availableDisplayModes, if set").
  When the View declares nothing, no restriction is applied.
- When the requested mode is not available, the host leaves the mode unchanged
  and returns the CURRENT display mode in the response (per spec), instead of a
  hardcoded inline fallback. No host-context-changed is emitted in that case.
- Example widgets declare appCapabilities.availableDisplayModes: ["inline"].

Adds e2e coverage for the app-capabilities restriction and the current-mode
response on an unavailable request.
@yannj-fr
yannj-fr marked this pull request as draft August 26, 2026 13:05
@yannj-fr

Copy link
Copy Markdown
Contributor Author

Need first to discuss #6707

yannj-fr added a commit to yannj-fr/CopilotKit that referenced this pull request Aug 28, 2026
- Load the ext-apps bridge lazily. AppBridge/PostMessageTransport now come from a
  dynamic import() inside Effect 1, with a type-only import at the top. A
  <CopilotKit> app no longer pays the ~40-50 kB gzipped ext-apps cost unless it
  actually renders an MCP App. Verified: the built output has no static ext-apps
  import, only import("@modelcontextprotocol/ext-apps/app-bridge").
- Move @modelcontextprotocol/sdk out of dependencies. It is now an optional
  peerDependency (mirroring how ext-apps declares it) plus a devDependency for
  our own build, so the sdk tree (express, hono, jose, ajv, cross-spawn) is no
  longer an install/audit surface for every React consumer. Nothing in the
  bundle reaches sdk at runtime; the only sdk usage is a type import.
- Raise the zod peer floor to >=3.25. The ext-apps/sdk schema slice imports
  zod/v4 and zod/v4-mini, which only exist in zod >= 3.25; the old >=3.0.0 peer
  let a consumer on zod 3.24 hit an unresolvable import at build time.
- Seed the host context at AppBridge construction (hostContext option) instead of
  calling setHostContext after connect, so it is deterministically in place when
  the widget's ui/initialize is handled (the seam CopilotKit#6689 needs to advertise
  displayMode / availableDisplayModes at initialize).
- Restore the full cross-frontend testid surface-contract comment.
- Split the oncalltool guard so "no server hash" and "no agent" report distinctly.
@yannj-fr yannj-fr closed this Aug 31, 2026
BenTaylorDev added a commit that referenced this pull request Sep 1, 2026
…apps (AppBridge) (#6707)

## What

Migrate the MCP Apps host (`MCPAppsActivityRenderer`, react-core) from a
hand-rolled protocol to the `@modelcontextprotocol/ext-apps` host
library (`AppBridge` + `PostMessageTransport`).

Today the renderer reimplements the whole app↔host protocol by hand:
method names as string literals, `PROTOCOL_VERSION = "2025-06-18"`
hardcoded, hand-written types, a manual `postMessage` + `switch` router,
and a custom sandbox proxy. There is no compile-time tie to the spec,
which is the root cause of recurring drift (e.g. widgets sending
`ui/notifications/size-change` vs the host/spec `size-changed`, and the
stale protocol version).

## Changes

- Add `@modelcontextprotocol/ext-apps` (^1.7.5) to `react-core`.
`@modelcontextprotocol/sdk` (^1.29.0) is a `peerDependency` (mirroring
how ext-apps declares it) plus a `devDependency`, not a direct
dependency: react-core does not use the SDK directly (type import only),
the runtime use is inside ext-apps.
- Per widget instance, connect an `AppBridge` over a
`PostMessageTransport` to the sandboxed iframe (the existing sandbox
proxy is kept as the transport relay). The bridge owns:
- `ui/initialize` + capability/protocol-version negotiation — now
advertises `LATEST_PROTOCOL_VERSION` (`2026-01-26`).
- host context (`setHostContext`), tool input/result (`sendToolInput` /
`sendToolResult`), and the sandbox handshake (`onsandboxready` →
`sendSandboxResourceReady`).
- App→host requests/notifications are mapped to the existing CopilotKit
behavior via bridge handlers: `open-link` (window.open), `tools/call`
(runAgent proxy), `size-changed` (iframe sizing), `initialized`,
logging. The runAgent queue and the issue #5819 thread-capture semantics
are preserved.
- Remove the hand-rolled `PROTOCOL_VERSION`, the send/response helpers,
and the JSON-RPC `switch` now owned by the bridge.

### ui/message: CopilotKit extensions preserved

The ext-apps `ui/message` schema only allows `role: "user"` and has no
`followUp`, but CopilotKit intentionally extends `ui/message` with
`role` ("user" | "assistant") and `followUp` (documented behavior,
dedicated tests). To stay behavior-preserving for widgets in the wild,
`ui/message` uses a custom request handler instead of the bridge's
strict `onmessage`:

- Extensions are read from `params._meta.copilotkit` first (the
forward-looking, spec-friendly channel), then from the legacy top-level
`params.role` / `params.followUp` (kept for backward compatibility,
slated for deprecation).

### Behavior changes to note

- `ui/open-link` **without** a `url` now fails with JSON-RPC `-32603`
(InternalError) instead of the previous hand-rolled `-32602`
(InvalidParams). The bridge validates the request against the spec
schema ahead of the handler, so a missing `url` surfaces as the bridge's
validation error rather than a params error we raise ourselves. Widgets
that read JSON-RPC error codes for this case will see the new code. A
well-formed `ui/open-link` is unaffected.
- `ui/open-link` now enforces a scheme **denylist** before
`window.open`: `javascript:`, `data:`, `vbscript:`, `blob:`, and `file:`
are refused (they can execute script / render attacker HTML). Everything
else is allowed, including `https:` universal links and custom-scheme
deep links (`myapp:`, `whatsapp:`, ...), which hand off to an OS handler
rather than executing in the page. A denylist on purpose: an allowlist
could never enumerate app-defined deep-link schemes, and it matches the
Anthropic Software Directory policy (https origins + owned custom URI
schemes).
- `ui/initialize` is now validated against the spec schema by the
bridge. A widget that omits the required fields (e.g. `appCapabilities`,
or empty/absent params) fails initialize with JSON-RPC `-32603` instead
of the lenient response the hand-rolled host gave; a compliant widget
(including any built with the ext-apps `App` class, which always sends
`appInfo` + `appCapabilities` + `protocolVersion`) is unaffected.
- Protocol-version negotiation: the host now advertises the **MCP Apps**
protocol version `2026-01-26` (`LATEST_PROTOCOL_VERSION`) and returns it
rather than echoing whatever a widget sends. Note this is the MCP
**Apps** protocol version, which is independent from the base MCP
protocol version — the old hand-rolled host confusingly hardcoded
`2025-06-18`, which is a base-MCP-protocol version, not an MCP Apps one.
Covered both ways by new e2e tests.

### Review round (addressing @BenTaylorDev)

- **Lazy-load the bridge.** `AppBridge` / `PostMessageTransport` are now
a dynamic `import()` inside Effect 1 (type-only import at the top), so a
`<CopilotKit>` app only pays the ~40-50 kB gzipped ext-apps cost when it
actually renders an MCP App. The built output has no static ext-apps
import, only `import("@modelcontextprotocol/ext-apps/app-bridge")`.
- **`@modelcontextprotocol/sdk` is no longer a direct dependency** (see
Changes above): optional `peerDependency` + `devDependency`.
- **zod peer floor raised to `>=3.25`.** The ext-apps/sdk schema slice
imports `zod/v4` and `zod/v4-mini`, which only exist in zod `>= 3.25`;
the old `>=3.0.0` peer let a consumer on zod 3.24 hit an unresolvable
import at build time.
- **Deterministic host context.** It is now seeded at `AppBridge`
construction (the `hostContext` option) rather than via `setHostContext`
after `connect`, so it is in place when the widget's `ui/initialize` is
handled instead of winning that race by luck. This is the seam #6689
needs to advertise `displayMode` / `availableDisplayModes` at
initialize.
- Restored the full cross-frontend testid surface-contract comment, and
split the `oncalltool` guard so "no server hash" and "no agent" report
distinctly.

## Testing

- `react-core` type-check green; MCP Apps e2e green (34 tests), incl.
the `_meta.copilotkit` extension-channel test, `ui/open-link` scheme
allow/deny (deep link vs `javascript:`), and `ui/initialize` negotiation
(well-formed success, missing-fields `-32603`, version returned).
- One e2e assertion updated: `ui/open-link` without `url` is now a
schema-validation error surfaced by the bridge (JSON-RPC `-32603`)
rather than the previous hand-rolled `-32602` (see "Behavior changes to
note" above).
- Validated end-to-end in a browser against a live MCP server + LLM: the
widget renders, `ui/initialize` negotiates `2026-01-26`, tool-result is
delivered, and `ui/message` works; console clean.

## Scope / follow-ups

- React-first (pilot). Vue and Angular ship their own hand-rolled
renderers with the same drift; a shared, framework-agnostic extraction
consumed by all three is the natural follow-up.
- Display-mode / update-model-context / theme host-context work layers
on top of this bridge.

This PR is intentionally not adding more features (like
requestDisplayMode from #6689 ), if we validate the approach to use
ext-app instead of reimplementing the ext-app specs, I will continue
ext-apps support to align as much as possible.



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Enhanced MCP app integration with streamlined initialization and
secure message/tool handling (including logging, sizing, and sandbox
delivery).
* Preserved role and follow-up behavior from app messages, with support
for safe custom deep links.
* Improved link handling with stricter URL validation and safer scheme
rules.
* **Bug Fixes**
* Prevented unsafe/malformed links and rejected script/HTML-executing
schemes.
  * Dropped queued follow-ups when the active conversation changes.
* **Dependency Updates**
* Updated MCP runtime/dev dependencies and tightened `zod` peer
dependency requirements.
* **Tests**
* Expanded e2e coverage for initialization negotiation, schema
validation errors, metadata-driven behavior, and link safety.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
menotbobbybrown pushed a commit to menotbobbybrown/CopilotKit that referenced this pull request Nov 23, 2026
…de in React, Vue and Angular (CopilotKit#7760)

## Summary

Implements `ui/request-display-mode` for MCP Apps widgets, in the shared
host package and in all three frontends. Until now the host left the
request to AppBridge's default handler, which answers the current mode
and never changes it; a widget that calls
`app.requestDisplayMode("fullscreen")` now gets a surface that really
covers the viewport, in React, Vue and Angular, with the same behaviour
in each.

Supersedes CopilotKit#6689 (the pre-consolidation, React-only version, closed) and
takes the first item of CopilotKit#6824. Built on the shared package from CopilotKit#6823,
so the protocol side is written once.

## Why a native `<dialog>`

The obvious implementation, a `position: fixed; inset: 0` overlay, does
not fill the viewport in CopilotKit v2. The chat container
(`.copilotKitChat`) uses `container-type: inline-size`, and a container
establishes the containing block for its `position: fixed` descendants.
The overlay therefore stays inside the chat panel: measured live in
CopilotKit#6689's review, it landed at `x=757, width=1512` on a 1512px viewport,
half off screen. This affects every v2 host, not just the demo, and no
z-index fixes it.

The widget surface is therefore a native `<dialog>` in all three
frontends:

- `fullscreen` opens it with `showModal()`, which places it in the
browser **top layer**. The top layer sits outside every containing
block, so the dialog fills the viewport whatever ancestors do. Measured
in the browser: `x=0`, full viewport width, with the dialog matching
`:modal`.
- `inline` leaves the dialog closed and renders it in normal flow with
`display: block`. It is never opened, not even with `show()`, because
opening a dialog runs the browser's dialog focusing steps: a widget
arriving in the chat would move the focus off the composer while the
user types. Inline, the widget is chat content, so the element is
exposed as a labelled `role="group"`, not as a dialog; fullscreen keeps
the modal dialog's semantics.
- The iframe lives inside the dialog and is never reparented: a mode
change is `showModal()` or `close()` on the same element, so the widget
keeps its state (no `srcdoc` reload).
- The modal dialog brings focus containment, focus restore and Escape
natively. Escape fires the dialog's `cancel` event, which is mapped to
the host-initiated exit so the widget is told exactly as for the close
button.
- Where the top layer is unavailable (jsdom) the helper falls back to
the `open` attribute, so the suites keep asserting protocol and DOM
without relying on `:modal`.

The DOM helpers, `ɵshowDialogForMode(dialog, mode)`,
`ɵdialogRoleForMode(mode)` and the page-wide ref-counted
`ɵlockBodyScroll()`, live in the package's bridge-free `/activity`
entry, so the three adapters share them without loading the ext-apps
bridge.

## When a widget gets fullscreen

The modal dialog makes the rest of the page inert, so fullscreen needs a
user action on the widget itself. Transient activation
(`navigator.userActivation.isActive`) belongs to the whole page: a key
press in the chat composer activates it as much as a click in the
widget, so on its own it would let a widget that asks in a loop take the
page as soon as the user types. The gate (`fullscreen-gate.ts`) grants
fullscreen only when:

- the widget's iframe holds the focus (a click or key press in the
widget gives it the focus; one in the composer or in another widget does
not);
- no `pointerdown` or `keydown` reached the host page in the last 5
seconds, the transient activation window of Chromium and Firefox. Events
inside the iframe never reach the host document, so a recent host-side
gesture means the activation may come from the host;
- the page is activated, where the browser exposes the API.

After the host took a widget out of fullscreen (close button, Escape),
every widget on the page is refused until the activation has been
observed inactive; without the activation API the block stays. The state
is page-wide, not per session.

One consequence: a user who types in the chat and clicks a widget's
fullscreen button within the next 5 seconds is refused once and has to
click again a moment later.

## What the host does

- Renders `inline` and `fullscreen`; `pip` is never granted. An
unavailable request leaves the mode untouched and answers with the mode
still applied.
- Honours `appCapabilities.availableDisplayModes`: a mode the app did
not declare at `ui/initialize` is refused the same way.
`options.hostContext.availableDisplayModes` narrows what the host offers
(`inline` always stays).
- Can be kept inline by the integrator in every frontend: `<CopilotKit
mcpApps={{ hostContext: { availableDisplayModes: ["inline"] } }}>` in
React, `<CopilotKitProvider :mcp-apps="...">` in Vue, `provideMCPApps({
hostContext })` in Angular. The docs page shows the three. In React and
Vue, `mcpApps` is one option shape (`MCPAppsOptions`) that also carries
`allowSameOriginFallback` from CopilotKit#7896 and `modelContext` from CopilotKit#7811,
passed whole to the session through the provider context; the renderer's
own `allowSameOriginFallback` and `modelContext` props take precedence
when given. The pre-wrapped renderers both PRs had added are gone.
- Advertises `displayMode` and `availableDisplayModes` in `hostContext`
from construction on, so the `ui/initialize` response already carries
them.
- Routes every change, widget-initiated or host-initiated, through one
path that ends in `ui/notifications/host-context-changed` (the app SDK
caches host context from the notification, not from the response).
`fullscreen` advertises the viewport as `containerDimensions`; `inline`
advertises the width of the nearest laid-out ancestor, and only a width,
since the inline container grows with the widget's content.

## What the frontends render

Fullscreen shows a close button and lands focus on it; the button and
Escape exit through `session.setDisplayMode("inline")`. The iframe fills
the surface in fullscreen and returns to the height the widget last
reported. The page scroll is locked behind a fullscreen widget and
released on exit, ref-counted across widgets. The surface carries an
accessible name in both modes. While fullscreen, the viewport is
re-advertised only when it actually changed, once per animation frame.

One limit, found in the browser and documented in the package README:
Escape reaches the dialog only while focus is on the host side. A key
pressed inside the sandboxed widget stays in its iframe, which is why
fullscreen entry moves focus to the exit button. Once the user has
clicked into the widget, the button or the widget's own
`requestDisplayMode("inline")` is the way out.

## Session API

- `hooks.onDisplayModeChange(mode)`: what was granted, for the adapter
to render.
- `session.setDisplayMode(mode, containerDimensions?)`: host-initiated
change.
- `session.getDisplayMode()`.
- Exports: `McpAppsDisplayMode`, `HOST_SUPPORTED_DISPLAY_MODES`,
`McpAppContainerDimensions`, `resolveHostDisplayModes`,
`defaultContainerDimensions`, and the internal `ɵresetFullscreenGate`
test hook for the adapters' suites.

## Tests

- Shared package: initialize advertisement, grant with notification,
`pip` keeps the current mode, app-declared refusal, option narrowing,
host-initiated change. The fullscreen gate: refusal without activation,
refusal when the activation may come from the host page (even once the
widget holds the focus), refusal to a widget that does not hold the
focus, grant once the host gesture is older than the activation window,
the post-exit block applying to every widget on the page, and the block
without the activation API. Dialog helpers: inline never calls `show()`
and never blurs the composer, fullscreen opens modally and closes back
to inline without reparenting, the role per mode.
- React, Vue and Angular: grants, refusals, round-trip notifications,
close button, Escape, container dimensions and iframe fill, scroll lock,
focus on entry, the inline surface exposed as a closed `group` and the
fullscreen one as an open dialog, the opt-out through `mcpApps`, and a
refusal when the user's last gesture was on the host page.

Merged with current `main`, which now includes CopilotKit#7811
(`ui/update-model-context`): both features live side by side in the
shared session, the adapters and the docs page. Checks: build and
check-types for core, mcp-apps-renderer, react-core, vue and angular;
tests with the Nx cache skipped for mcp-apps-renderer, react-core, vue
and angular; `check:public-api-manifest` current. The diff against
`main` contains only this feature's files.

## Browser run

In Chrome, against the host-primitives test widget (an MCP App whose
buttons call `requestDisplayMode`), through the React demo linked to
this branch:

- Inline: the dialog stays closed, renders in flow (`display: block`)
and appears in the accessibility tree as `group "Interactive MCP
application"`. The composer keeps the focus while the widget mounts,
with no blur.
- A real click on the widget's fullscreen button grants fullscreen
(`:modal`, focus on the exit button).
- Right after an exit (button or Escape), a click in the widget is
refused; more than 5 seconds later, it is granted.
- Typing in the composer, then clicking the widget's button within 5
seconds: refused, with the page activated and the iframe focused.

An earlier run of this branch drove the same widget through the Vue
(Nuxt) and Angular demos: the modal dialog covers the viewport at x=0
from inside the chat sidebar, the widget receives `host-context-changed`
with `containerDimensions`, the exit button and Escape return inline,
`pip` changes nothing, the inline height is restored, the scroll is
locked and released, and the widget's in-memory log survives every
toggle (no reload).

## Docs

`packages/mcp-apps-renderer/README.md` (display-mode contract, the
fullscreen gate, the dialog surface and the Escape limit), the MCP Apps
docs page (display modes, when fullscreen is granted, and how to keep
widgets inline), the Angular README, and `packages/vue/PARITY.md`.

## Out of scope

Theme propagation beyond the existing `.dark` detection, and reporting
the actual fullscreen surface instead of the viewport in
`containerDimensions` (all tracked in CopilotKit#6824).

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* MCP Apps widgets can switch between inline and fullscreen in React,
Vue, and Angular. Requests are honored only when supported by both the
host and the widget; unsupported requests leave the current mode
unchanged.
* Fullscreen views provide an exit button, support returning to inline
mode with Escape, and lock page scrolling until fullscreen ends.
* Widgets receive display-mode and container-size updates. Their content
remains mounted when switching modes, and the previous inline height is
restored on return.
* **Documentation**
* Added guidance on display modes, host-supported options, and
configuring Angular widgets to stay inline.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants