@modelcontextprotocol/ext-apps - v0.0.1
    Preparing search index...

    Class AppBridge

    Host-side bridge for communicating with a single Guest UI (App).

    AppBridge extends the MCP SDK's Protocol class and acts as a proxy between the host application and a Guest UI running in an iframe. It automatically forwards MCP server capabilities (tools, resources, prompts) to the Guest UI and handles the initialization handshake.

    Guest UI ↔ AppBridge ↔ Host ↔ MCP Server

    The bridge proxies requests from the Guest UI to the MCP server and forwards responses back. It also sends host-initiated notifications like tool input and results to the Guest UI.

    1. Create: Instantiate AppBridge with MCP client and capabilities
    2. Connect: Call connect() with transport to establish communication
    3. Wait for init: Guest UI sends initialize request, bridge responds
    4. Send data: Call sendToolInput(), sendToolResult(), etc.
    5. Teardown: Call sendResourceTeardown() before unmounting iframe
    import { AppBridge, PostMessageTransport } from '@modelcontextprotocol/ext-apps/app-bridge';
    import { Client } from '@modelcontextprotocol/sdk/client/index.js';

    // Create MCP client for the server
    const client = new Client({
    name: "MyHost",
    version: "1.0.0",
    });
    await client.connect(serverTransport);

    // Create bridge for the Guest UI
    const bridge = new AppBridge(
    client,
    { name: "MyHost", version: "1.0.0" },
    { openLinks: {}, serverTools: {}, logging: {} }
    );

    // Set up iframe and connect
    const iframe = document.getElementById('app') as HTMLIFrameElement;
    const transport = new PostMessageTransport(
    iframe.contentWindow!,
    iframe.contentWindow!,
    );

    bridge.oninitialized = () => {
    console.log("Guest UI initialized");
    // Now safe to send tool input
    bridge.sendToolInput({ arguments: { location: "NYC" } });
    };

    await bridge.connect(transport);

    Hierarchy

    • Protocol<Request, Notification, Result>
      • AppBridge
    Index

    Constructors

    • Create a new AppBridge instance.

      Parameters

      • _client: Client

        MCP client connected to the server (for proxying requests)

      • _hostInfo: {
            icons?: { mimeType?: string; sizes?: string[]; src: string }[];
            name: string;
            title?: string;
            version: string;
            websiteUrl?: string;
        }

        Host application identification (name and version)

      • _capabilities: McpUiHostCapabilities

        Features and capabilities the host supports

      • Optionaloptions: ProtocolOptions

        Configuration options (inherited from Protocol)

      Returns AppBridge

      const bridge = new AppBridge(
      mcpClient,
      { name: "MyHost", version: "1.0.0" },
      { openLinks: {}, serverTools: {}, logging: {} }
      );

    Properties

    fallbackNotificationHandler?: (
        notification: {
            method: string;
            params?: { _meta?: { [key: string]: unknown }; [key: string]: unknown };
        },
    ) => Promise<void>

    A handler to invoke for any notification types that do not have their own handler installed.

    fallbackRequestHandler?: (
        request: {
            id: string | number;
            jsonrpc: "2.0";
            method: string;
            params?: {
                _meta?: { progressToken?: string | number; [key: string]: unknown };
                [key: string]: unknown;
            };
        },
        extra: RequestHandlerExtra<
            {
                method: string;
                params?: {
                    _meta?: { progressToken?: string
                    | number; [key: string]: unknown };
                    [key: string]: unknown;
                };
            },
            {
                method: string;
                params?: { _meta?: { [key: string]: unknown }; [key: string]: unknown };
            },
        >,
    ) => Promise<{ _meta?: { [key: string]: unknown }; [key: string]: unknown }>

    A handler to invoke for any request types that do not have their own handler installed.

    onclose?: () => void

    Callback for when the connection is closed for any reason.

    This is invoked when close() is called as well.

    onerror?: (error: Error) => void

    Callback for when an error occurs.

    Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band.

    onping?: (
        params:
            | {
                _meta?: { progressToken?: string
                | number; [key: string]: unknown };
                [key: string]: unknown;
            }
            | undefined,
        extra: RequestHandlerExtra,
    ) => void

    Optional handler for ping requests from the Guest UI.

    The Guest UI can send standard MCP ping requests to verify the connection is alive. The AppBridge automatically responds with an empty object, but this handler allows the host to observe or log ping activity.

    Unlike the other handlers which use setters, this is a direct property assignment. It is optional; if not set, pings are still handled automatically.

    Type Declaration

      • (
            params:
                | {
                    _meta?: { progressToken?: string
                    | number; [key: string]: unknown };
                    [key: string]: unknown;
                }
                | undefined,
            extra: RequestHandlerExtra,
        ): void
      • Parameters

        • params:
              | {
                  _meta?: { progressToken?: string
                  | number; [key: string]: unknown };
                  [key: string]: unknown;
              }
              | undefined

          Empty params object from the ping request

          • {
                _meta?: { progressToken?: string | number; [key: string]: unknown };
                [key: string]: unknown;
            }
            • [key: string]: unknown
            • Optional_meta?: { progressToken?: string | number; [key: string]: unknown }

              See General fields: _meta for notes on _meta usage.

              • OptionalprogressToken?: string | number

                If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.

          • undefined
        • extra: RequestHandlerExtra

          Request metadata (abort signal, session info)

        Returns void

    bridge.onping = (params, extra) => {
    console.log("Received ping from Guest UI");
    };

    Accessors

    • set oninitialized(callback: (params: {} | undefined) => void): void

      Called when the Guest UI completes initialization.

      Set this callback to be notified when the Guest UI has finished its initialization handshake and is ready to receive tool input and other data.

      Parameters

      • callback: (params: {} | undefined) => void

      Returns void

      bridge.oninitialized = () => {
      console.log("Guest UI ready");
      bridge.sendToolInput({ arguments: toolArgs });
      };
    • set onloggingmessage(
          callback: (
              params: {
                  _meta?: { [key: string]: unknown };
                  data: unknown;
                  level:
                      | "error"
                      | "debug"
                      | "info"
                      | "notice"
                      | "warning"
                      | "critical"
                      | "alert"
                      | "emergency";
                  logger?: string;
                  [key: string]: unknown;
              },
          ) => void,
      ): void

      Register a handler for logging messages from the Guest UI.

      The Guest UI sends standard MCP notifications/message (logging) notifications to report debugging information, errors, warnings, and other telemetry to the host. The host can display these in a console, log them to a file, or send them to a monitoring service.

      This uses the standard MCP logging notification format, not a UI-specific message type.

      Parameters

      • callback: (
            params: {
                _meta?: { [key: string]: unknown };
                data: unknown;
                level:
                    | "error"
                    | "debug"
                    | "info"
                    | "notice"
                    | "warning"
                    | "critical"
                    | "alert"
                    | "emergency";
                logger?: string;
                [key: string]: unknown;
            },
        ) => void

        Handler that receives logging params

        • params.level - Log level: "debug" | "info" | "notice" | "warning" | "error" | "critical" | "alert" | "emergency"
        • params.logger - Optional logger name/identifier
        • params.data - Log message and optional structured data

      Returns void

      bridge.onloggingmessage = ({ level, logger, data }) => {
      const prefix = logger ? `[${logger}]` : "[Guest UI]";
      console[level === "error" ? "error" : "log"](
      `${prefix} ${level.toUpperCase()}:`,
      data
      );
      };
    • set onmessage(
          callback: (
              params: { content: ContentBlock[]; role: "user" },
              extra: RequestHandlerExtra,
          ) => Promise<McpUiMessageResult>,
      ): void

      Register a handler for message requests from the Guest UI.

      The Guest UI sends ui/message requests when it wants to add a message to the host's chat interface. This enables interactive apps to communicate with the user through the conversation thread.

      The handler should process the message (add it to the chat) and return a result indicating success or failure. For security, the host should NOT return conversation content or follow-up results to prevent information leakage.

      Parameters

      • callback: (
            params: { content: ContentBlock[]; role: "user" },
            extra: RequestHandlerExtra,
        ) => Promise<McpUiMessageResult>

        Handler that receives message params and returns a result

        • params.role - Message role (currently only "user" is supported)
        • params.content - Message content blocks (text, image, etc.)
        • extra - Request metadata (abort signal, session info)
        • Returns: Promise with optional isError flag

      Returns void

      bridge.onmessage = async ({ role, content }, extra) => {
      try {
      await chatManager.addMessage({ role, content, source: "app" });
      return {}; // Success
      } catch (error) {
      console.error("Failed to add message:", error);
      return { isError: true };
      }
      };
    • Register a handler for external link requests from the Guest UI.

      The Guest UI sends ui/open-link requests when it wants to open an external URL in the host's default browser. The handler should validate the URL and open it according to the host's security policy and user preferences.

      The host MAY:

      • Show a confirmation dialog before opening
      • Block URLs based on a security policy or allowlist
      • Log the request for audit purposes
      • Reject the request entirely

      Parameters

      • callback: (
            params: { url: string },
            extra: RequestHandlerExtra,
        ) => Promise<McpUiOpenLinkResult>

        Handler that receives URL params and returns a result

        • params.url - URL to open in the host's browser
        • extra - Request metadata (abort signal, session info)
        • Returns: Promise with optional isError flag

      Returns void

      bridge.onopenlink = async ({ url }, extra) => {
      if (!isAllowedDomain(url)) {
      console.warn("Blocked external link:", url);
      return { isError: true };
      }

      const confirmed = await showDialog({
      message: `Open external link?\n${url}`,
      buttons: ["Open", "Cancel"]
      });

      if (confirmed) {
      window.open(url, "_blank", "noopener,noreferrer");
      return {};
      }

      return { isError: true };
      };
    • set onsandboxready(callback: (params: {}) => void): void
      Internal

      Register a handler for sandbox proxy ready notifications.

      This is an internal callback used by web-based hosts implementing the double-iframe sandbox architecture. The sandbox proxy sends ui/notifications/sandbox-proxy-ready after it loads and is ready to receive HTML content.

      When this fires, the host should call sendSandboxResourceReady with the HTML content to load into the inner sandboxed iframe.

      Parameters

      • callback: (params: {}) => void

      Returns void

      bridge.onsandboxready = async () => {
      const resource = await mcpClient.request(
      { method: "resources/read", params: { uri: "ui://my-app" } },
      ReadResourceResultSchema
      );

      bridge.sendSandboxResourceReady({
      html: resource.contents[0].text,
      sandbox: "allow-scripts"
      });
      };
    • set onsizechange(
          callback: (params: { height?: number; width?: number }) => void,
      ): void

      Register a handler for size change notifications from the Guest UI.

      The Guest UI sends ui/notifications/size-change when its rendered content size changes, typically via ResizeObserver. Set this callback to dynamically adjust the iframe container dimensions based on the Guest UI's content.

      Note: This is for Guest UI → Host communication. To notify the Guest UI of host viewport changes, use app.App.sendSizeChange.

      Parameters

      • callback: (params: { height?: number; width?: number }) => void

      Returns void

      bridge.onsizechange = ({ width, height }) => {
      if (width != null) {
      iframe.style.width = `${width}px`;
      }
      if (height != null) {
      iframe.style.height = `${height}px`;
      }
      };
    • get transport(): Transport | undefined

      Returns Transport | undefined

    Methods

    • Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.

      Parameters

      • method: string

      Returns void

    • Internal

      Verify that the guest supports the capability required for the given request method.

      Parameters

      • method: string

      Returns void

    • Internal

      Verify that the host supports the capability required for the given notification method.

      Parameters

      • method: string

      Returns void

    • Internal

      Verify that a request handler is registered and supported for the given method.

      Parameters

      • method: string

      Returns void

    • Closes the connection.

      Returns Promise<void>

    • Connect to the Guest UI via transport and set up message forwarding.

      This method establishes the transport connection and automatically sets up request/notification forwarding based on the MCP server's capabilities. It proxies the following server capabilities to the Guest UI:

      • Tools (tools/call, tools/list_changed)
      • Resources (resources/list, resources/read, resources/templates/list, resources/list_changed)
      • Prompts (prompts/list, prompts/list_changed)

      After calling connect, wait for the oninitialized callback before sending tool input and other data to the Guest UI.

      Parameters

      • transport: Transport

        Transport layer (typically PostMessageTransport)

      Returns Promise<void>

      Promise resolving when connection is established

      If server capabilities are not available. This occurs when connect() is called before the MCP client has completed its initialization with the server. Ensure await client.connect() completes before calling bridge.connect().

      const bridge = new AppBridge(mcpClient, hostInfo, capabilities);
      const transport = new PostMessageTransport(
      iframe.contentWindow!,
      iframe.contentWindow!,
      );

      bridge.oninitialized = () => {
      console.log("Guest UI ready");
      bridge.sendToolInput({ arguments: toolArgs });
      };

      await bridge.connect(transport);
    • Get the Guest UI's capabilities discovered during initialization.

      Returns the capabilities that the Guest UI advertised during its initialization request. Returns undefined if called before initialization completes.

      Returns McpUiAppCapabilities | undefined

      Guest UI capabilities, or undefined if not yet initialized

      bridge.oninitialized = () => {
      const caps = bridge.getAppCapabilities();
      if (caps?.tools) {
      console.log("Guest UI provides tools");
      }
      };

      McpUiAppCapabilities for the capabilities structure

    • Get the Guest UI's implementation info discovered during initialization.

      Returns the Guest UI's name and version as provided in its initialization request. Returns undefined if called before initialization completes.

      Returns
          | {
              icons?: { mimeType?: string; sizes?: string[]; src: string }[];
              name: string;
              title?: string;
              version: string;
              websiteUrl?: string;
          }
          | undefined

      Guest UI implementation info, or undefined if not yet initialized

      bridge.oninitialized = () => {
      const appInfo = bridge.getAppVersion();
      if (appInfo) {
      console.log(`Guest UI: ${appInfo.name} v${appInfo.version}`);
      }
      };
    • Emits a notification, which is a one-way message that does not expect a response.

      Parameters

      • notification: {
            method: string;
            params?: { _meta?: { [key: string]: unknown }; [key: string]: unknown };
        }
      • Optionaloptions: NotificationOptions

      Returns Promise<void>

    • Removes the notification handler for the given method.

      Parameters

      • method: string

      Returns void

    • Removes the request handler for the given method.

      Parameters

      • method: string

      Returns void

    • Sends a request and wait for a response.

      Do not use this method to emit notifications! Use notification() instead.

      Type Parameters

      • T extends AnySchema

      Parameters

      • request: {
            method: string;
            params?: {
                _meta?: { progressToken?: string | number; [key: string]: unknown };
                [key: string]: unknown;
            };
        }
      • resultSchema: T
      • Optionaloptions: RequestOptions

      Returns Promise<SchemaOutput<T>>

    • Request graceful shutdown of the Guest UI.

      The host MUST send this request before tearing down the UI resource (before unmounting the iframe). This gives the Guest UI an opportunity to save state, cancel pending operations, or show confirmation dialogs.

      The host SHOULD wait for the response before unmounting to prevent data loss.

      Parameters

      • params: {}

        Empty params object

      • Optionaloptions: RequestOptions

        Request options (timeout, etc.)

      Returns Promise<McpUiResourceTeardownResult>

      Promise resolving when Guest UI confirms readiness for teardown

      try {
      await bridge.sendResourceTeardown({});
      // Guest UI is ready, safe to unmount iframe
      iframe.remove();
      } catch (error) {
      console.error("Teardown failed:", error);
      }
    • Internal

      Send HTML resource to the sandbox proxy for secure loading.

      This is an internal method used by web-based hosts implementing the double-iframe sandbox architecture. After the sandbox proxy signals readiness via ui/notifications/sandbox-proxy-ready, the host sends this notification with the HTML content to load.

      Parameters

      • params: { html: string; sandbox?: string }

        HTML content and sandbox configuration:

        • html: The HTML content to load into the sandboxed iframe
        • sandbox: Optional sandbox attribute value (e.g., "allow-scripts")
        • html: string

          HTML content to load into the inner iframe

        • Optionalsandbox?: string

          Optional override for the inner iframe's sandbox attribute

      Returns Promise<void>

      onsandboxready for handling the sandbox proxy ready notification

    • Send complete tool arguments to the Guest UI.

      The host MUST send this notification after the Guest UI completes initialization (after oninitialized callback fires) and complete tool arguments become available. This notification is sent exactly once and is required before sendToolResult.

      Parameters

      • params: { arguments?: Record<string, unknown> }

        Complete tool call arguments

        • Optionalarguments?: Record<string, unknown>

          Complete tool call arguments as key-value pairs

      Returns Promise<void>

      bridge.oninitialized = () => {
      bridge.sendToolInput({
      arguments: { location: "New York", units: "metric" }
      });
      };
    • Send tool execution result to the Guest UI.

      The host MUST send this notification when tool execution completes successfully, provided the UI is still displayed. If the UI was closed before execution completes, the host MAY skip this notification. This must be sent after sendToolInput.

      Parameters

      • params: {
            _meta?: { [key: string]: unknown };
            content: (
                | { _meta?: { [key: string]: unknown }; text: string; type: "text" }
                | {
                    _meta?: { [key: string]: unknown };
                    data: string;
                    mimeType: string;
                    type: "image";
                }
                | {
                    _meta?: { [key: string]: unknown };
                    data: string;
                    mimeType: string;
                    type: "audio";
                }
                | {
                    _meta?: { [key: string]: unknown };
                    description?: string;
                    icons?: { mimeType?: string; sizes?: string[]; src: string }[];
                    mimeType?: string;
                    name: string;
                    title?: string;
                    type: "resource_link";
                    uri: string;
                }
                | {
                    _meta?: { [key: string]: unknown };
                    resource:
                        | {
                            _meta?: { [key: string]: unknown };
                            mimeType?: string;
                            text: string;
                            uri: string;
                        }
                        | {
                            _meta?: { [key: string]: unknown };
                            blob: string;
                            mimeType?: string;
                            uri: string;
                        };
                    type: "resource";
                }
            )[];
            isError?: boolean;
            structuredContent?: { [key: string]: unknown };
            [key: string]: unknown;
        }

        Standard MCP tool execution result

      Returns Promise<void>

      import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';

      const result = await mcpClient.request(
      { method: "tools/call", params: { name: "get_weather", arguments: args } },
      CallToolResultSchema
      );
      bridge.sendToolResult(result);
    • Registers a handler to invoke when this protocol object receives a notification with the given method.

      Note that this will replace any previous notification handler for the same method.

      Type Parameters

      • T extends AnyObjectSchema

      Parameters

      • notificationSchema: T
      • handler: (notification: SchemaOutput<T>) => void | Promise<void>

      Returns void

    • Registers a handler to invoke when this protocol object receives a request with the given method.

      Note that this will replace any previous request handler for the same method.

      Type Parameters

      • T extends AnyObjectSchema

      Parameters

      • requestSchema: T
      • handler: (
            request: SchemaOutput<T>,
            extra: RequestHandlerExtra<
                {
                    method: string;
                    params?: {
                        _meta?: { progressToken?: string
                        | number; [key: string]: unknown };
                        [key: string]: unknown;
                    };
                },
                {
                    method: string;
                    params?: { _meta?: { [key: string]: unknown }; [key: string]: unknown };
                },
            >,
        ) => | { _meta?: { [key: string]: unknown }; [key: string]: unknown }
        | Promise<{ _meta?: { [key: string]: unknown }; [key: string]: unknown }>

      Returns void