@modelcontextprotocol/ext-apps - v1.1.2
    Preparing search index...

    Class AppBridge

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

    AppBridge extends the MCP SDK's Protocol class and acts as a proxy between the host application and a view running in an iframe. When an MCP client is provided to the constructor, it automatically forwards MCP server capabilities (tools, resources, prompts) to the view. It also handles the initialization handshake.

    View ↔ AppBridge ↔ Host ↔ MCP Server

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

    1. Create: Instantiate AppBridge with MCP client and capabilities
    2. Connect: Call connect() with transport to establish communication
    3. Wait for init: View sends initialize request, bridge responds
    4. Send data: Call sendToolInput, sendToolResult, etc.
    5. Teardown: Call teardownResource before unmounting iframe
    // Create MCP client for the server
    const client = new Client({
    name: "MyHost",
    version: "1.0.0",
    });
    await client.connect(serverTransport);

    // Create bridge for the View
    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("View initialized");
    // Now safe to send tool input
    bridge.sendToolInput({ arguments: { location: "NYC" } });
    };

    await bridge.connect(transport);

    Hierarchy

    Index

    Constructors

    • Create a new AppBridge instance.

      Parameters

      • _client:
            | Client<
                {
                    method: string;
                    params?: {
                        _meta?: {
                            "io.modelcontextprotocol/related-task"?: { taskId: string };
                            progressToken?: string | number;
                            [key: string]: unknown;
                        };
                        [key: string]: unknown;
                    };
                },
                {
                    method: string;
                    params?: {
                        _meta?: {
                            "io.modelcontextprotocol/related-task"?: { taskId: string };
                            progressToken?: string | number;
                            [key: string]: unknown;
                        };
                        [key: string]: unknown;
                    };
                },
                {
                    _meta?: {
                        "io.modelcontextprotocol/related-task"?: { taskId: string };
                        progressToken?: string | number;
                        [key: string]: unknown;
                    };
                    [key: string]: unknown;
                },
            >
            | null

        MCP client connected to the server, or null. When provided, connect will automatically set up forwarding of MCP requests/notifications between the View and the server. When null, you must register handlers manually using the oncalltool, onlistresources, etc. setters.

      • _hostInfo: {
            description?: string;
            icons?: {
                mimeType?: string;
                sizes?: string[];
                src: string;
                theme?: "light" | "dark";
            }[];
            name: string;
            title?: string;
            version: string;
            websiteUrl?: string;
        }

        Host application identification (name and version)

      • _capabilities: McpUiHostCapabilities

        Features and capabilities the host supports

      • Optionaloptions: HostOptions

        Configuration options (inherited from Protocol)

      Returns AppBridge

      const bridge = new AppBridge(
      mcpClient,
      { name: "MyHost", version: "1.0.0" },
      { openLinks: {}, serverTools: {}, logging: {} },
      );
      const bridge = new AppBridge(
      null,
      { name: "MyHost", version: "1.0.0" },
      { openLinks: {}, serverTools: {}, logging: {} },
      );
      bridge.oncalltool = async (params, extra) => {
      // Handle tool calls manually
      return { content: [] };
      };

    Properties

    fallbackNotificationHandler?: (
        notification: {
            method: string;
            params?: {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [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?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
                [key: string]: unknown;
            };
        },
        extra: RequestHandlerExtra<AppRequest, AppNotification>,
    ) => Promise<AppResult>

    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?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
            }
            | undefined,
        extra: RequestHandlerExtra,
    ) => void

    Optional handler for ping requests from the view.

    The View 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?: {
                        "io.modelcontextprotocol/related-task"?: { taskId: string };
                        progressToken?: string | number;
                        [key: string]: unknown;
                    };
                }
                | undefined,
            extra: RequestHandlerExtra,
        ): void
      • Parameters

        • params:
              | {
                  _meta?: {
                      "io.modelcontextprotocol/related-task"?: { taskId: string };
                      progressToken?: string | number;
                      [key: string]: unknown;
                  };
              }
              | undefined

          Empty params object from the ping request

        • extra: RequestHandlerExtra

          Request metadata (abort signal, session info)

        Returns void

    bridge.onping = (params, extra) => {
    console.log("Received ping from view");
    };
    sendResourceTeardown: (
        params: {},
        options?: RequestOptions,
    ) => Promise<Record<string, unknown>> = ...

    Type Declaration

      • (params: {}, options?: RequestOptions): Promise<Record<string, unknown>>
      • Request graceful shutdown of the view.

        The host MUST send this request before tearing down the UI resource (before unmounting the iframe). This gives the view 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<Record<string, unknown>>

        Promise resolving when view confirms readiness for teardown

        try {
        await bridge.teardownResource({});
        // View is ready, safe to unmount iframe
        iframe.remove();
        } catch (error) {
        console.error("Teardown failed:", error);
        }

    Use teardownResource instead

    Accessors

    • set oncalltool(
          callback: (
              params: {
                  _meta?: {
                      "io.modelcontextprotocol/related-task"?: { taskId: string };
                      progressToken?: string | number;
                      [key: string]: unknown;
                  };
                  arguments?: { [key: string]: unknown };
                  name: string;
                  task?: { ttl?: number };
              },
              extra: RequestHandlerExtra,
          ) => Promise<
              {
                  _meta?: {
                      "io.modelcontextprotocol/related-task"?: { taskId: string };
                      progressToken?: string | number;
                      [key: string]: unknown;
                  };
                  content: (
                      | {
                          _meta?: { [key: string]: unknown };
                          annotations?: {
                              audience?: ((...) | (...))[];
                              lastModified?: string;
                              priority?: number;
                          };
                          text: string;
                          type: "text";
                      }
                      | {
                          _meta?: { [key: string]: unknown };
                          annotations?: {
                              audience?: ((...) | (...))[];
                              lastModified?: string;
                              priority?: number;
                          };
                          data: string;
                          mimeType: string;
                          type: "image";
                      }
                      | {
                          _meta?: { [key: string]: unknown };
                          annotations?: {
                              audience?: ((...) | (...))[];
                              lastModified?: string;
                              priority?: number;
                          };
                          data: string;
                          mimeType: string;
                          type: "audio";
                      }
                      | {
                          _meta?: { [key: string]: unknown };
                          annotations?: {
                              audience?: ((...) | (...))[];
                              lastModified?: string;
                              priority?: number;
                          };
                          description?: string;
                          icons?: {
                              mimeType?: string;
                              sizes?: (...)[];
                              src: string;
                              theme?: "light" | "dark";
                          }[];
                          mimeType?: string;
                          name: string;
                          title?: string;
                          type: "resource_link";
                          uri: string;
                      }
                      | {
                          _meta?: { [key: string]: unknown };
                          annotations?: {
                              audience?: ((...) | (...))[];
                              lastModified?: string;
                              priority?: number;
                          };
                          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;
              },
          >,
      ): void

      Register a handler for tool call requests from the view.

      The view sends tools/call requests to execute MCP server tools. This handler allows the host to intercept and process these requests, typically by forwarding them to the MCP server.

      Parameters

      • callback: (
            params: {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
                arguments?: { [key: string]: unknown };
                name: string;
                task?: { ttl?: number };
            },
            extra: RequestHandlerExtra,
        ) => Promise<
            {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
                content: (
                    | {
                        _meta?: { [key: string]: unknown };
                        annotations?: {
                            audience?: ((...) | (...))[];
                            lastModified?: string;
                            priority?: number;
                        };
                        text: string;
                        type: "text";
                    }
                    | {
                        _meta?: { [key: string]: unknown };
                        annotations?: {
                            audience?: ((...) | (...))[];
                            lastModified?: string;
                            priority?: number;
                        };
                        data: string;
                        mimeType: string;
                        type: "image";
                    }
                    | {
                        _meta?: { [key: string]: unknown };
                        annotations?: {
                            audience?: ((...) | (...))[];
                            lastModified?: string;
                            priority?: number;
                        };
                        data: string;
                        mimeType: string;
                        type: "audio";
                    }
                    | {
                        _meta?: { [key: string]: unknown };
                        annotations?: {
                            audience?: ((...) | (...))[];
                            lastModified?: string;
                            priority?: number;
                        };
                        description?: string;
                        icons?: {
                            mimeType?: string;
                            sizes?: (...)[];
                            src: string;
                            theme?: "light" | "dark";
                        }[];
                        mimeType?: string;
                        name: string;
                        title?: string;
                        type: "resource_link";
                        uri: string;
                    }
                    | {
                        _meta?: { [key: string]: unknown };
                        annotations?: {
                            audience?: ((...) | (...))[];
                            lastModified?: string;
                            priority?: number;
                        };
                        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;
            },
        >

        Handler that receives tool call params and returns a CallToolResult

        • params - Tool call parameters (name and arguments)
        • extra - Request metadata (abort signal, session info)

      Returns void

      bridge.oncalltool = async (params, extra) => {
      return mcpClient.request(
      { method: "tools/call", params },
      CallToolResultSchema,
      { signal: extra.signal },
      );
      };
      • CallToolRequest from @modelcontextprotocol/sdk for the request type
      • CallToolResult from @modelcontextprotocol/sdk for the result type
    • set ondownloadfile(
          callback: (
              params: {
                  contents: (
                      | {
                          _meta?: { [key: string]: unknown };
                          annotations?: {
                              audience?: ("user" | "assistant")[];
                              lastModified?: string;
                              priority?: number;
                          };
                          resource: | {
                              _meta?: { [key: string]: unknown };
                              mimeType?: string;
                              text: string;
                              uri: string;
                          }
                          | {
                              _meta?: { [key: string]: unknown };
                              blob: string;
                              mimeType?: string;
                              uri: string;
                          };
                          type: "resource";
                      }
                      | {
                          _meta?: { [key: string]: unknown };
                          annotations?: {
                              audience?: ("user" | "assistant")[];
                              lastModified?: string;
                              priority?: number;
                          };
                          description?: string;
                          icons?: {
                              mimeType?: string;
                              sizes?: string[];
                              src: string;
                              theme?: "light"
                              | "dark";
                          }[];
                          mimeType?: string;
                          name: string;
                          title?: string;
                          type: "resource_link";
                          uri: string;
                      }
                  )[];
              },
              extra: RequestHandlerExtra,
          ) => Promise<McpUiDownloadFileResult>,
      ): void

      Register a handler for file download requests from the View.

      The View sends ui/download-file requests when the user wants to download a file. The params contain an array of MCP resource content items — either EmbeddedResource (inline data) or ResourceLink (URI the host can fetch). The host should show a confirmation dialog and then trigger the download.

      Parameters

      • callback: (
            params: {
                contents: (
                    | {
                        _meta?: { [key: string]: unknown };
                        annotations?: {
                            audience?: ("user" | "assistant")[];
                            lastModified?: string;
                            priority?: number;
                        };
                        resource: | {
                            _meta?: { [key: string]: unknown };
                            mimeType?: string;
                            text: string;
                            uri: string;
                        }
                        | {
                            _meta?: { [key: string]: unknown };
                            blob: string;
                            mimeType?: string;
                            uri: string;
                        };
                        type: "resource";
                    }
                    | {
                        _meta?: { [key: string]: unknown };
                        annotations?: {
                            audience?: ("user" | "assistant")[];
                            lastModified?: string;
                            priority?: number;
                        };
                        description?: string;
                        icons?: {
                            mimeType?: string;
                            sizes?: string[];
                            src: string;
                            theme?: "light"
                            | "dark";
                        }[];
                        mimeType?: string;
                        name: string;
                        title?: string;
                        type: "resource_link";
                        uri: string;
                    }
                )[];
            },
            extra: RequestHandlerExtra,
        ) => Promise<McpUiDownloadFileResult>

        Handler that receives download params and returns a result

        • params.contents - Array of EmbeddedResource or ResourceLink items
        • extra - Request metadata (abort signal, session info)
        • Returns: Promise<McpUiDownloadFileResult> with optional isError flag

      Returns void

      bridge.ondownloadfile = async ({ contents }, extra) => {
      for (const item of contents) {
      if (item.type === "resource") {
      // EmbeddedResource — inline content
      const res = item.resource;
      const blob = res.blob
      ? new Blob([Uint8Array.from(atob(res.blob), c => c.charCodeAt(0))], { type: res.mimeType })
      : new Blob([res.text ?? ""], { type: res.mimeType });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = res.uri.split("/").pop() ?? "download";
      link.click();
      URL.revokeObjectURL(url);
      } else if (item.type === "resource_link") {
      // ResourceLink — host fetches or opens directly
      window.open(item.uri, "_blank");
      }
      }
      return {};
      };
    • set oninitialized(callback: (params: {} | undefined) => void): void

      Called when the view completes initialization.

      Set this callback to be notified when the view 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("View ready");
      bridge.sendToolInput({ arguments: toolArgs });
      };
    • set onlistprompts(
          callback: (
              params:
                  | {
                      _meta?: {
                          "io.modelcontextprotocol/related-task"?: { taskId: string };
                          progressToken?: string | number;
                          [key: string]: unknown;
                      };
                      cursor?: string;
                  }
                  | undefined,
              extra: RequestHandlerExtra,
          ) => Promise<
              {
                  _meta?: {
                      "io.modelcontextprotocol/related-task"?: { taskId: string };
                      progressToken?: string | number;
                      [key: string]: unknown;
                  };
                  nextCursor?: string;
                  prompts: {
                      _meta?: { [key: string]: unknown };
                      arguments?: { description?: string; name: string; required?: boolean }[];
                      description?: string;
                      icons?: {
                          mimeType?: string;
                          sizes?: string[];
                          src: string;
                          theme?: "light" | "dark";
                      }[];
                      name: string;
                      title?: string;
                  }[];
                  [key: string]: unknown;
              },
          >,
      ): void

      Register a handler for list prompts requests from the view.

      The view sends prompts/list requests to enumerate available MCP prompts. This handler allows the host to intercept and process these requests, typically by forwarding them to the MCP server.

      Parameters

      • callback: (
            params:
                | {
                    _meta?: {
                        "io.modelcontextprotocol/related-task"?: { taskId: string };
                        progressToken?: string | number;
                        [key: string]: unknown;
                    };
                    cursor?: string;
                }
                | undefined,
            extra: RequestHandlerExtra,
        ) => Promise<
            {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
                nextCursor?: string;
                prompts: {
                    _meta?: { [key: string]: unknown };
                    arguments?: { description?: string; name: string; required?: boolean }[];
                    description?: string;
                    icons?: {
                        mimeType?: string;
                        sizes?: string[];
                        src: string;
                        theme?: "light" | "dark";
                    }[];
                    name: string;
                    title?: string;
                }[];
                [key: string]: unknown;
            },
        >

        Handler that receives list params and returns a ListPromptsResult

        • params - Request params (may include cursor for pagination)
        • extra - Request metadata (abort signal, session info)

      Returns void

      bridge.onlistprompts = async (params, extra) => {
      return mcpClient.request(
      { method: "prompts/list", params },
      ListPromptsResultSchema,
      { signal: extra.signal },
      );
      };
      • ListPromptsRequest from @modelcontextprotocol/sdk for the request type
      • ListPromptsResult from @modelcontextprotocol/sdk for the result type
    • set onlistresources(
          callback: (
              params:
                  | {
                      _meta?: {
                          "io.modelcontextprotocol/related-task"?: { taskId: string };
                          progressToken?: string | number;
                          [key: string]: unknown;
                      };
                      cursor?: string;
                  }
                  | undefined,
              extra: RequestHandlerExtra,
          ) => Promise<
              {
                  _meta?: {
                      "io.modelcontextprotocol/related-task"?: { taskId: string };
                      progressToken?: string | number;
                      [key: string]: unknown;
                  };
                  nextCursor?: string;
                  resources: {
                      _meta?: { [key: string]: unknown };
                      annotations?: {
                          audience?: ("user" | "assistant")[];
                          lastModified?: string;
                          priority?: number;
                      };
                      description?: string;
                      icons?: {
                          mimeType?: string;
                          sizes?: string[];
                          src: string;
                          theme?: "light"
                          | "dark";
                      }[];
                      mimeType?: string;
                      name: string;
                      title?: string;
                      uri: string;
                  }[];
                  [key: string]: unknown;
              },
          >,
      ): void

      Register a handler for list resources requests from the view.

      The view sends resources/list requests to enumerate available MCP resources. This handler allows the host to intercept and process these requests, typically by forwarding them to the MCP server.

      Parameters

      • callback: (
            params:
                | {
                    _meta?: {
                        "io.modelcontextprotocol/related-task"?: { taskId: string };
                        progressToken?: string | number;
                        [key: string]: unknown;
                    };
                    cursor?: string;
                }
                | undefined,
            extra: RequestHandlerExtra,
        ) => Promise<
            {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
                nextCursor?: string;
                resources: {
                    _meta?: { [key: string]: unknown };
                    annotations?: {
                        audience?: ("user" | "assistant")[];
                        lastModified?: string;
                        priority?: number;
                    };
                    description?: string;
                    icons?: {
                        mimeType?: string;
                        sizes?: string[];
                        src: string;
                        theme?: "light"
                        | "dark";
                    }[];
                    mimeType?: string;
                    name: string;
                    title?: string;
                    uri: string;
                }[];
                [key: string]: unknown;
            },
        >

        Handler that receives list params and returns a ListResourcesResult

        • params - Request params (may include cursor for pagination)
        • extra - Request metadata (abort signal, session info)

      Returns void

      bridge.onlistresources = async (params, extra) => {
      return mcpClient.request(
      { method: "resources/list", params },
      ListResourcesResultSchema,
      { signal: extra.signal },
      );
      };
      • ListResourcesRequest from @modelcontextprotocol/sdk for the request type
      • ListResourcesResult from @modelcontextprotocol/sdk for the result type
    • set onlistresourcetemplates(
          callback: (
              params:
                  | {
                      _meta?: {
                          "io.modelcontextprotocol/related-task"?: { taskId: string };
                          progressToken?: string | number;
                          [key: string]: unknown;
                      };
                      cursor?: string;
                  }
                  | undefined,
              extra: RequestHandlerExtra,
          ) => Promise<
              {
                  _meta?: {
                      "io.modelcontextprotocol/related-task"?: { taskId: string };
                      progressToken?: string | number;
                      [key: string]: unknown;
                  };
                  nextCursor?: string;
                  resourceTemplates: {
                      _meta?: { [key: string]: unknown };
                      annotations?: {
                          audience?: ("user" | "assistant")[];
                          lastModified?: string;
                          priority?: number;
                      };
                      description?: string;
                      icons?: {
                          mimeType?: string;
                          sizes?: string[];
                          src: string;
                          theme?: "light"
                          | "dark";
                      }[];
                      mimeType?: string;
                      name: string;
                      title?: string;
                      uriTemplate: string;
                  }[];
                  [key: string]: unknown;
              },
          >,
      ): void

      Register a handler for list resource templates requests from the view.

      The view sends resources/templates/list requests to enumerate available MCP resource templates. This handler allows the host to intercept and process these requests, typically by forwarding them to the MCP server.

      Parameters

      • callback: (
            params:
                | {
                    _meta?: {
                        "io.modelcontextprotocol/related-task"?: { taskId: string };
                        progressToken?: string | number;
                        [key: string]: unknown;
                    };
                    cursor?: string;
                }
                | undefined,
            extra: RequestHandlerExtra,
        ) => Promise<
            {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
                nextCursor?: string;
                resourceTemplates: {
                    _meta?: { [key: string]: unknown };
                    annotations?: {
                        audience?: ("user" | "assistant")[];
                        lastModified?: string;
                        priority?: number;
                    };
                    description?: string;
                    icons?: {
                        mimeType?: string;
                        sizes?: string[];
                        src: string;
                        theme?: "light"
                        | "dark";
                    }[];
                    mimeType?: string;
                    name: string;
                    title?: string;
                    uriTemplate: string;
                }[];
                [key: string]: unknown;
            },
        >

        Handler that receives list params and returns a ListResourceTemplatesResult

        • params - Request params (may include cursor for pagination)
        • extra - Request metadata (abort signal, session info)

      Returns void

      bridge.onlistresourcetemplates = async (params, extra) => {
      return mcpClient.request(
      { method: "resources/templates/list", params },
      ListResourceTemplatesResultSchema,
      { signal: extra.signal }
      );
      };
      • ListResourceTemplatesRequest from @modelcontextprotocol/sdk for the request type
      • ListResourceTemplatesResult from @modelcontextprotocol/sdk for the result type
    • set onloggingmessage(
          callback: (
              params: {
                  _meta?: {
                      "io.modelcontextprotocol/related-task"?: { taskId: string };
                      progressToken?: string | number;
                      [key: string]: unknown;
                  };
                  data: unknown;
                  level: | "error"
                  | "alert"
                  | "debug"
                  | "info"
                  | "notice"
                  | "warning"
                  | "critical"
                  | "emergency";
                  logger?: string;
              },
          ) => void,
      ): void

      Register a handler for logging messages from the view.

      The view 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?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
                data: unknown;
                level: | "error"
                | "alert"
                | "debug"
                | "info"
                | "notice"
                | "warning"
                | "critical"
                | "emergency";
                logger?: string;
            },
        ) => 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 }) => {
      console[level === "error" ? "error" : "log"](
      `[${logger ?? "View"}] ${level.toUpperCase()}:`,
      data,
      );
      };
    • set onmessage(
          callback: (
              params: { content: ContentBlock[]; role: "user" },
              extra: RequestHandlerExtra,
          ) => Promise<McpUiMessageResult>,
      ): void

      Register a handler for message requests from the view.

      The view 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<McpUiMessageResult> 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 view.

      The view 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<McpUiOpenLinkResult> 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 onreadresource(
          callback: (
              params: {
                  _meta?: {
                      "io.modelcontextprotocol/related-task"?: { taskId: string };
                      progressToken?: string | number;
                      [key: string]: unknown;
                  };
                  uri: string;
              },
              extra: RequestHandlerExtra,
          ) => Promise<
              {
                  _meta?: {
                      "io.modelcontextprotocol/related-task"?: { taskId: string };
                      progressToken?: string | number;
                      [key: string]: unknown;
                  };
                  contents: (
                      | {
                          _meta?: { [key: string]: unknown };
                          mimeType?: string;
                          text: string;
                          uri: string;
                      }
                      | {
                          _meta?: { [key: string]: unknown };
                          blob: string;
                          mimeType?: string;
                          uri: string;
                      }
                  )[];
                  [key: string]: unknown;
              },
          >,
      ): void

      Register a handler for read resource requests from the view.

      The view sends resources/read requests to retrieve the contents of an MCP resource. This handler allows the host to intercept and process these requests, typically by forwarding them to the MCP server.

      Parameters

      • callback: (
            params: {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
                uri: string;
            },
            extra: RequestHandlerExtra,
        ) => Promise<
            {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
                contents: (
                    | {
                        _meta?: { [key: string]: unknown };
                        mimeType?: string;
                        text: string;
                        uri: string;
                    }
                    | {
                        _meta?: { [key: string]: unknown };
                        blob: string;
                        mimeType?: string;
                        uri: string;
                    }
                )[];
                [key: string]: unknown;
            },
        >

        Handler that receives read params and returns a ReadResourceResult

        • params - Read parameters including the resource URI
        • extra - Request metadata (abort signal, session info)

      Returns void

      bridge.onreadresource = async (params, extra) => {
      return mcpClient.request(
      { method: "resources/read", params },
      ReadResourceResultSchema,
      { signal: extra.signal },
      );
      };
      • ReadResourceRequest from @modelcontextprotocol/sdk for the request type
      • ReadResourceResult from @modelcontextprotocol/sdk for the result type
    • set onrequestdisplaymode(
          callback: (
              params: { mode: McpUiDisplayMode },
              extra: RequestHandlerExtra,
          ) => Promise<McpUiRequestDisplayModeResult>,
      ): void

      Register a handler for display mode change requests from the view.

      The view sends ui/request-display-mode requests when it wants to change its display mode (e.g., from "inline" to "fullscreen"). The handler should check if the requested mode is in availableDisplayModes from the host context, update the display mode if supported, and return the actual mode that was set.

      If the requested mode is not available, the handler should return the current display mode instead.

      By default, AppBridge returns the current displayMode from host context (or "inline"). Setting this property replaces that default behavior.

      Parameters

      • callback: (
            params: { mode: McpUiDisplayMode },
            extra: RequestHandlerExtra,
        ) => Promise<McpUiRequestDisplayModeResult>

        Handler that receives the requested mode and returns the actual mode set

        • params.mode - The display mode being requested ("inline" | "fullscreen" | "pip")
        • extra - Request metadata (abort signal, session info)
        • Returns: Promise<McpUiRequestDisplayModeResult> with the actual mode set

      Returns void

      bridge.onrequestdisplaymode = async ({ mode }, extra) => {
      if (availableDisplayModes.includes(mode)) {
      currentDisplayMode = mode;
      }
      return { mode: currentDisplayMode };
      };
    • 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 view.

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

      Note: This is for View → Host communication. To notify the View of host container dimension changes, use setHostContext.

      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`;
      }
      };
    • set onupdatemodelcontext(
          callback: (
              params: {
                  content?: ContentBlock[];
                  structuredContent?: Record<string, unknown>;
              },
              extra: RequestHandlerExtra,
          ) => Promise<
              {
                  _meta?: {
                      "io.modelcontextprotocol/related-task"?: { taskId: string };
                      progressToken?: string | number;
                      [key: string]: unknown;
                  };
              },
          >,
      ): void

      Register a handler for model context updates from the view.

      The view sends ui/update-model-context requests to update the Host's model context. Each request overwrites the previous context stored by the view. Unlike logging messages, context updates are intended to be available to the model in future turns. Unlike messages, context updates do not trigger follow-ups.

      The host will typically defer sending the context to the model until the next user message (including ui/message), and will only send the last update received.

      Parameters

      • callback: (
            params: {
                content?: ContentBlock[];
                structuredContent?: Record<string, unknown>;
            },
            extra: RequestHandlerExtra,
        ) => Promise<
            {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
            },
        >

      Returns void

      bridge.onupdatemodelcontext = async (
      { content, structuredContent },
      extra,
      ) => {
      // Store the context snapshot for inclusion in the next model request
      modelContextManager.update({ content, structuredContent });
      return {};
      };

      McpUiUpdateModelContextRequest for the request type

    • 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:
            | "ui/open-link"
            | "ui/download-file"
            | "ui/message"
            | "ui/update-model-context"
            | "ui/resource-teardown"
            | "ui/initialize"
            | "ui/request-display-mode"
            | "tools/call"
            | "tools/list"
            | "resources/list"
            | "resources/templates/list"
            | "resources/read"
            | "prompts/list"
            | "ping"

      Returns void

    • Internal

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

      Parameters

      • method:
            | "ui/notifications/sandbox-proxy-ready"
            | "ui/notifications/sandbox-resource-ready"
            | "ui/notifications/size-changed"
            | "ui/notifications/tool-input"
            | "ui/notifications/tool-input-partial"
            | "ui/notifications/tool-result"
            | "ui/notifications/tool-cancelled"
            | "ui/notifications/host-context-changed"
            | "ui/notifications/initialized"
            | "notifications/tools/list_changed"
            | "notifications/resources/list_changed"
            | "notifications/prompts/list_changed"
            | "notifications/message"

      Returns void

    • Internal

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

      Parameters

      • method:
            | "ui/open-link"
            | "ui/download-file"
            | "ui/message"
            | "ui/update-model-context"
            | "ui/resource-teardown"
            | "ui/initialize"
            | "ui/request-display-mode"
            | "tools/call"
            | "tools/list"
            | "resources/list"
            | "resources/templates/list"
            | "resources/read"
            | "prompts/list"
            | "ping"

      Returns void

    • Internal

      Verify that task creation is supported for the given request method.

      Parameters

      • _method: string

      Returns void

    • Internal

      Verify that task handler is supported for the given method.

      Parameters

      • _method: string

      Returns void

    • Experimental

      Cancels a specific task.

      Use client.experimental.tasks.cancelTask() to access this method.

      Parameters

      • params: { taskId: string }
      • Optionaloptions: RequestOptions

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
              createdAt: string;
              lastUpdatedAt: string;
              pollInterval?: number;
              status: | "working"
              | "input_required"
              | "completed"
              | "failed"
              | "cancelled";
              statusMessage?: string;
              taskId: string;
              ttl: number
              | null;
          },
      >

    • Closes the connection.

      Returns Promise<void>

    • Connect to the view via transport and optionally set up message forwarding.

      This method establishes the transport connection. If an MCP client was passed to the constructor, it also automatically sets up request/notification forwarding based on the MCP server's capabilities, proxying the following to the view:

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

      If no client was passed to the constructor, no automatic forwarding is set up and you must register handlers manually using the oncalltool, onlistresources, etc. setters.

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

      Parameters

      Returns Promise<void>

      Promise resolving when connection is established

      If a client was passed but 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("View ready");
      bridge.sendToolInput({ arguments: toolArgs });
      };

      await bridge.connect(transport);
      const bridge = new AppBridge(null, hostInfo, capabilities);

      // Register handlers manually
      bridge.oncalltool = async (params, extra) => {
      // Custom tool call handling
      return { content: [] };
      };

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

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

      Returns McpUiAppCapabilities | undefined

      view capabilities, or undefined if not yet initialized

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

      McpUiAppCapabilities for the capabilities structure

    • Get the view's implementation info discovered during initialization.

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

      Returns
          | {
              description?: string;
              icons?: {
                  mimeType?: string;
                  sizes?: string[];
                  src: string;
                  theme?: "light"
                  | "dark";
              }[];
              name: string;
              title?: string;
              version: string;
              websiteUrl?: string;
          }
          | undefined

      view implementation info, or undefined if not yet initialized

      bridge.oninitialized = () => {
      const appInfo = bridge.getAppVersion();
      if (appInfo) {
      console.log(`View: ${appInfo.name} v${appInfo.version}`);
      }
      };
    • Experimental

      Gets the current status of a task.

      Use client.experimental.tasks.getTask() to access this method.

      Parameters

      • params: {
            _meta?: {
                "io.modelcontextprotocol/related-task"?: { taskId: string };
                progressToken?: string | number;
                [key: string]: unknown;
            };
            taskId: string;
        }
      • Optionaloptions: RequestOptions

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
              createdAt: string;
              lastUpdatedAt: string;
              pollInterval?: number;
              status: | "working"
              | "input_required"
              | "completed"
              | "failed"
              | "cancelled";
              statusMessage?: string;
              taskId: string;
              ttl: number
              | null;
          },
      >

    • Experimental

      Retrieves the result of a completed task.

      Use client.experimental.tasks.getTaskResult() to access this method.

      Type Parameters

      • T extends AnySchema

      Parameters

      • params: {
            _meta?: {
                "io.modelcontextprotocol/related-task"?: { taskId: string };
                progressToken?: string | number;
                [key: string]: unknown;
            };
            taskId: string;
        }
      • resultSchema: T
      • Optionaloptions: RequestOptions

      Returns Promise<SchemaOutput<T>>

    • Experimental

      Lists tasks, optionally starting from a pagination cursor.

      Use client.experimental.tasks.listTasks() to access this method.

      Parameters

      • Optionalparams: { cursor?: string }
      • Optionaloptions: RequestOptions

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                  progressToken?: string | number;
                  [key: string]: unknown;
              };
              nextCursor?: string;
              tasks: {
                  createdAt: string;
                  lastUpdatedAt: string;
                  pollInterval?: number;
                  status: | "working"
                  | "input_required"
                  | "completed"
                  | "failed"
                  | "cancelled";
                  statusMessage?: string;
                  taskId: string;
                  ttl: number
                  | null;
              }[];
              [key: string]: unknown;
          },
      >

    • Emits a notification, which is a one-way message that does not expect a response.

      Parameters

      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 waits for a response.

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

      Type Parameters

      • T extends AnySchema

      Parameters

      • request: AppRequest
      • resultSchema: T
      • Optionaloptions: RequestOptions

      Returns Promise<SchemaOutput<T>>

    • Experimental

      Sends a request and returns an AsyncGenerator that yields response messages. The generator is guaranteed to end with either a 'result' or 'error' message.

      Type Parameters

      • T extends AnySchema

      Parameters

      • request: AppRequest
      • resultSchema: T
      • Optionaloptions: RequestOptions

      Returns AsyncGenerator<ResponseMessage<SchemaOutput<T>>, void, void>

      const stream = protocol.requestStream(request, resultSchema, options);
      for await (const message of stream) {
      switch (message.type) {
      case 'taskCreated':
      console.log('Task created:', message.task.taskId);
      break;
      case 'taskStatus':
      console.log('Task status:', message.task.status);
      break;
      case 'result':
      console.log('Final result:', message.result);
      break;
      case 'error':
      console.error('Error:', message.error);
      break;
      }
      }

      Use client.experimental.tasks.requestStream() to access this method.

    • Low-level method to notify the view of host context changes.

      Most hosts should use setHostContext instead, which automatically detects changes and calls this method with only the modified fields. Use this directly only when you need fine-grained control over change detection.

      Parameters

      Returns void | Promise<void>

    • Notify the view that the MCP server's prompt list has changed.

      The host sends notifications/prompts/list_changed to the view when it receives this notification from the MCP server. This allows the view to refresh its prompt cache or UI accordingly.

      Parameters

      • params:
            | {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
            }
            | undefined = {}

        Optional notification params (typically empty)

      Returns Promise<void>

      // In your MCP client notification handler:
      mcpClient.setNotificationHandler(PromptListChangedNotificationSchema, () => {
      bridge.sendPromptListChanged();
      });

      PromptListChangedNotification from @modelcontextprotocol/sdk for the notification type

    • Notify the view that the MCP server's resource list has changed.

      The host sends notifications/resources/list_changed to the view when it receives this notification from the MCP server. This allows the view to refresh its resource cache or UI accordingly.

      Parameters

      • params:
            | {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
            }
            | undefined = {}

        Optional notification params (typically empty)

      Returns Promise<void>

      // In your MCP client notification handler:
      mcpClient.setNotificationHandler(ResourceListChangedNotificationSchema, () => {
      bridge.sendResourceListChanged();
      });

      ResourceListChangedNotification from @modelcontextprotocol/sdk for the notification type

    • 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: {
            csp?: McpUiResourceCsp;
            html: string;
            permissions?: McpUiResourcePermissions;
            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")
        • Optionalcsp?: McpUiResourceCsp

          CSP configuration from resource metadata.

        • html: string

          HTML content to load into the inner iframe.

        • Optionalpermissions?: McpUiResourcePermissions

          Sandbox permissions from resource metadata.

        • Optionalsandbox?: string

          Optional override for the inner iframe's sandbox attribute.

      Returns Promise<void>

      onsandboxready for handling the sandbox proxy ready notification

    • Notify the view that tool execution was cancelled.

      The host MUST send this notification if tool execution was cancelled for any reason, including user action, sampling error, classifier intervention, or any other interruption. This allows the view to update its state and display appropriate feedback to the user.

      Parameters

      • params: { reason?: string }

        Cancellation details object

        • reason: Human-readable explanation for why the tool was cancelled
        • Optionalreason?: string

          Optional reason for the cancellation (e.g., "user action", "timeout").

      Returns Promise<void>

      // User clicked "Cancel" button
      bridge.sendToolCancelled({ reason: "User cancelled the operation" });
      // Sampling error or timeout
      bridge.sendToolCancelled({ reason: "Request timeout after 30 seconds" });

      // Classifier intervention
      bridge.sendToolCancelled({ reason: "Content policy violation detected" });
    • Send complete tool arguments to the view.

      The host MUST send this notification after the View 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 streaming partial tool arguments to the view.

      The host MAY send this notification zero or more times while tool arguments are being streamed, before sendToolInput is called with complete arguments. This enables progressive rendering of tool arguments in the view.

      The arguments represent best-effort recovery of incomplete JSON. views SHOULD handle missing or changing fields gracefully between notifications.

      Parameters

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

        Partial tool call arguments (may be incomplete)

        • Optionalarguments?: Record<string, unknown>

          Partial tool call arguments (incomplete, may change).

      Returns Promise<void>

      // As streaming progresses...
      bridge.sendToolInputPartial({ arguments: { loc: "N" } });
      bridge.sendToolInputPartial({ arguments: { location: "New" } });
      bridge.sendToolInputPartial({ arguments: { location: "New York" } });

      // When complete, send final input
      bridge.sendToolInput({
      arguments: { location: "New York", units: "metric" },
      });
    • Notify the view that the MCP server's tool list has changed.

      The host sends notifications/tools/list_changed to the view when it receives this notification from the MCP server. This allows the view to refresh its tool cache or UI accordingly.

      Parameters

      • params:
            | {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
            }
            | undefined = {}

        Optional notification params (typically empty)

      Returns Promise<void>

      // In your MCP client notification handler:
      mcpClient.setNotificationHandler(ToolListChangedNotificationSchema, () => {
      bridge.sendToolListChanged();
      });

      ToolListChangedNotification from @modelcontextprotocol/sdk for the notification type

    • Send tool execution result to the view.

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

      Parameters

      • params: {
            _meta?: {
                "io.modelcontextprotocol/related-task"?: { taskId: string };
                progressToken?: string | number;
                [key: string]: unknown;
            };
            content: (
                | {
                    _meta?: { [key: string]: unknown };
                    annotations?: {
                        audience?: ("user" | "assistant")[];
                        lastModified?: string;
                        priority?: number;
                    };
                    text: string;
                    type: "text";
                }
                | {
                    _meta?: { [key: string]: unknown };
                    annotations?: {
                        audience?: ("user" | "assistant")[];
                        lastModified?: string;
                        priority?: number;
                    };
                    data: string;
                    mimeType: string;
                    type: "image";
                }
                | {
                    _meta?: { [key: string]: unknown };
                    annotations?: {
                        audience?: ("user" | "assistant")[];
                        lastModified?: string;
                        priority?: number;
                    };
                    data: string;
                    mimeType: string;
                    type: "audio";
                }
                | {
                    _meta?: { [key: string]: unknown };
                    annotations?: {
                        audience?: ("user" | "assistant")[];
                        lastModified?: string;
                        priority?: number;
                    };
                    description?: string;
                    icons?: {
                        mimeType?: string;
                        sizes?: string[];
                        src: string;
                        theme?: "light"
                        | "dark";
                    }[];
                    mimeType?: string;
                    name: string;
                    title?: string;
                    type: "resource_link";
                    uri: string;
                }
                | {
                    _meta?: { [key: string]: unknown };
                    annotations?: {
                        audience?: ("user" | "assistant")[];
                        lastModified?: string;
                        priority?: number;
                    };
                    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>

      const result = await mcpClient.request(
      { method: "tools/call", params: { name: "get_weather", arguments: args } },
      CallToolResultSchema,
      );
      bridge.sendToolResult(result);
    • Update the host context and notify the view of changes.

      Compares fields present in the new context with the current context and sends a ui/notifications/host-context-changed notification containing only fields that have been added or modified. If no fields have changed, no notification is sent. The new context fully replaces the internal state.

      Common use cases include notifying the view when:

      • Theme changes (light/dark mode toggle)
      • Viewport size changes (window resize)
      • Display mode changes (inline/fullscreen)
      • Locale or timezone changes

      Parameters

      Returns void

      bridge.setHostContext({ theme: "dark" });
      
      bridge.setHostContext({
      theme: "dark",
      containerDimensions: { maxHeight: 600, width: 800 },
      });
    • 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

      Returns void

    • Request graceful shutdown of the view.

      The host MUST send this request before tearing down the UI resource (before unmounting the iframe). This gives the view 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<Record<string, unknown>>

      Promise resolving when view confirms readiness for teardown

      try {
      await bridge.teardownResource({});
      // View is ready, safe to unmount iframe
      iframe.remove();
      } catch (error) {
      console.error("Teardown failed:", error);
      }