MCP Apps
    Preparing search index...

    Class App

    Main class for MCP Apps to communicate with their host.

    The App class provides a framework-agnostic way to build interactive MCP Apps that run inside host applications. It extends the base MCP SDK's public Protocol class, composes an EventDispatcher, and adds the Apps handshake, lifecycle, and high-level APIs.

    Views (Apps) act as MCP clients connecting to the host via PostMessageTransport. The host proxies requests to the actual MCP server and forwards responses back to the App.

    1. Create: Instantiate App with info and capabilities
    2. Connect: Call connect() to establish transport and perform handshake
    3. Interactive: Send requests, receive notifications, call tools
    4. Teardown: Host sends teardown request before unmounting

    From the base MCP SDK's Protocol, App provides:

    • setRequestHandler() - Register handlers for requests from host
    • setNotificationHandler() - Register handlers for notifications from host

    From its composed EventDispatcher, App also provides:

    • addEventListener() - Append a listener for a notification event (multi-listener)
    • removeEventListener() - Remove a previously added listener

    For common notifications, the App class provides getter/setter properties that follow DOM-model replace semantics (like el.onclick):

    • ontoolinput - Complete tool arguments from host
    • ontoolinputpartial - Streaming partial tool arguments
    • ontoolresult - Tool execution results
    • ontoolcancelled - Tool execution was cancelled by user or host
    • onhostcontextchanged - Host context changes (theme, locale, etc.)

    Assigning replaces the previous handler; assigning undefined clears it. Use addEventListener to attach multiple listeners without replacing.

    const app = new App(
    { name: "WeatherApp", version: "1.0.0" },
    {}, // capabilities
    );

    // Register handlers before connecting to ensure no notifications are missed
    app.ontoolinput = (params) => {
    console.log("Tool arguments:", params.arguments);
    };

    await app.connect();

    Hierarchy

    • Protocol<BaseContext>
      • App
    Index

    Accessors

    • get oncalltool(): | (
          (
              params: {
                  _meta?: {
                      "io.modelcontextprotocol/related-task"?: { taskId: string };
                      progressToken?: string | number;
                      [key: string]: unknown;
                  };
                  arguments?: { [key: string]: unknown };
                  name: string;
                  task?: { ttl?: number };
              },
              extra: BaseContext,
          ) => Promise<
              {
                  _meta?: {
                      "io.modelcontextprotocol/serverInfo"?: {
                          description?: string;
                          icons?: { mimeType?: ...; sizes?: ...; src: ...; theme?: ... }[];
                          name: string;
                          title?: string;
                          version: string;
                          websiteUrl?: string;
                      };
                      [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?: (...)
                              | (...);
                              sizes?: (...) | (...);
                              src: string;
                              theme?: (...) | (...) | (...);
                          }[];
                          mimeType?: string;
                          name: string;
                          size?: number;
                          title?: string;
                          type: "resource_link";
                          uri: string;
                      }
                      | {
                          _meta?: { [key: string]: unknown };
                          annotations?: {
                              audience?: (...)[];
                              lastModified?: string;
                              priority?: number;
                          };
                          resource: | {
                              _meta?: { [key: ...]: ... };
                              mimeType?: string;
                              text: string;
                              uri: string;
                          }
                          | {
                              _meta?: { [key: ...]: ... };
                              blob: string;
                              mimeType?: string;
                              uri: string;
                          };
                          type: "resource";
                      }
                  )[];
                  isError?: boolean;
                  structuredContent?: unknown;
                  [key: string]: unknown;
              },
          >
      )
      | undefined

      Returns
          | (
              (
                  params: {
                      _meta?: {
                          "io.modelcontextprotocol/related-task"?: { taskId: string };
                          progressToken?: string | number;
                          [key: string]: unknown;
                      };
                      arguments?: { [key: string]: unknown };
                      name: string;
                      task?: { ttl?: number };
                  },
                  extra: BaseContext,
              ) => Promise<
                  {
                      _meta?: {
                          "io.modelcontextprotocol/serverInfo"?: {
                              description?: string;
                              icons?: { mimeType?: ...; sizes?: ...; src: ...; theme?: ... }[];
                              name: string;
                              title?: string;
                              version: string;
                              websiteUrl?: string;
                          };
                          [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?: (...)
                                  | (...);
                                  sizes?: (...) | (...);
                                  src: string;
                                  theme?: (...) | (...) | (...);
                              }[];
                              mimeType?: string;
                              name: string;
                              size?: number;
                              title?: string;
                              type: "resource_link";
                              uri: string;
                          }
                          | {
                              _meta?: { [key: string]: unknown };
                              annotations?: {
                                  audience?: (...)[];
                                  lastModified?: string;
                                  priority?: number;
                              };
                              resource: | {
                                  _meta?: { [key: ...]: ... };
                                  mimeType?: string;
                                  text: string;
                                  uri: string;
                              }
                              | {
                                  _meta?: { [key: ...]: ... };
                                  blob: string;
                                  mimeType?: string;
                                  uri: string;
                              };
                              type: "resource";
                          }
                      )[];
                      isError?: boolean;
                      structuredContent?: unknown;
                      [key: string]: unknown;
                  },
              >
          )
          | undefined

    • 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: BaseContext,
                  ) => Promise<
                      {
                          _meta?: {
                              "io.modelcontextprotocol/serverInfo"?: {
                                  description?: string;
                                  icons?: { mimeType?: ...; sizes?: ...; src: ...; theme?: ... }[];
                                  name: string;
                                  title?: string;
                                  version: string;
                                  websiteUrl?: string;
                              };
                              [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?: (...)
                                      | (...);
                                      sizes?: (...) | (...);
                                      src: string;
                                      theme?: (...) | (...) | (...);
                                  }[];
                                  mimeType?: string;
                                  name: string;
                                  size?: number;
                                  title?: string;
                                  type: "resource_link";
                                  uri: string;
                              }
                              | {
                                  _meta?: { [key: string]: unknown };
                                  annotations?: {
                                      audience?: (...)[];
                                      lastModified?: string;
                                      priority?: number;
                                  };
                                  resource: | {
                                      _meta?: { [key: ...]: ... };
                                      mimeType?: string;
                                      text: string;
                                      uri: string;
                                  }
                                  | {
                                      _meta?: { [key: ...]: ... };
                                      blob: string;
                                      mimeType?: string;
                                      uri: string;
                                  };
                                  type: "resource";
                              }
                          )[];
                          isError?: boolean;
                          structuredContent?: unknown;
                          [key: string]: unknown;
                      },
                  >
              )
              | undefined,
      ): void

      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: BaseContext,
                ) => Promise<
                    {
                        _meta?: {
                            "io.modelcontextprotocol/serverInfo"?: {
                                description?: string;
                                icons?: { mimeType?: ...; sizes?: ...; src: ...; theme?: ... }[];
                                name: string;
                                title?: string;
                                version: string;
                                websiteUrl?: string;
                            };
                            [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?: (...)
                                    | (...);
                                    sizes?: (...) | (...);
                                    src: string;
                                    theme?: (...) | (...) | (...);
                                }[];
                                mimeType?: string;
                                name: string;
                                size?: number;
                                title?: string;
                                type: "resource_link";
                                uri: string;
                            }
                            | {
                                _meta?: { [key: string]: unknown };
                                annotations?: {
                                    audience?: (...)[];
                                    lastModified?: string;
                                    priority?: number;
                                };
                                resource: | {
                                    _meta?: { [key: ...]: ... };
                                    mimeType?: string;
                                    text: string;
                                    uri: string;
                                }
                                | {
                                    _meta?: { [key: ...]: ... };
                                    blob: string;
                                    mimeType?: string;
                                    uri: string;
                                };
                                type: "resource";
                            }
                        )[];
                        isError?: boolean;
                        structuredContent?: unknown;
                        [key: string]: unknown;
                    },
                >
            )
            | undefined

      Returns void

    • get onhostcontextchanged(): ((params: McpUiHostContext) => void) | undefined

      Convenience handler for host context changes (theme, locale, etc.).

      Set this property to register a handler that will be called when the host's context changes, such as theme switching (light/dark), locale changes, or other environmental updates. Apps should respond by updating their UI accordingly.

      Assigning replaces the previous handler; assigning undefined clears it. Use addEventListener to attach multiple listeners without replacing.

      Notification params are automatically merged into the internal host context before any handler or listener fires. This means getHostContext will return the updated values even before your callback runs.

      Register handlers before calling connect to avoid missing notifications.

      Returns ((params: McpUiHostContext) => void) | undefined

      app.onhostcontextchanged = (ctx) => {
      if (ctx.theme === "dark") {
      document.body.classList.add("dark-theme");
      } else {
      document.body.classList.remove("dark-theme");
      }
      };

      Use addEventListener("hostcontextchanged", handler) instead — it composes with other listeners and supports cleanup via removeEventListener.

    • set onhostcontextchanged(
          callback: ((params: McpUiHostContext) => void) | undefined,
      ): void

      Parameters

      Returns void

    • get onlisttools(): | (
          (
              params:
                  | {
                      _meta?: {
                          "io.modelcontextprotocol/related-task"?: { taskId: string };
                          progressToken?: string | number;
                          [key: string]: unknown;
                      };
                      cursor?: string;
                  }
                  | undefined,
              extra: BaseContext,
          ) => Promise<
              {
                  _meta?: {
                      "io.modelcontextprotocol/serverInfo"?: {
                          description?: string;
                          icons?: { mimeType?: ...; sizes?: ...; src: ...; theme?: ... }[];
                          name: string;
                          title?: string;
                          version: string;
                          websiteUrl?: string;
                      };
                      [key: string]: unknown;
                  };
                  nextCursor?: string;
                  tools: {
                      _meta?: { [key: string]: unknown };
                      annotations?: {
                          destructiveHint?: boolean;
                          idempotentHint?: boolean;
                          openWorldHint?: boolean;
                          readOnlyHint?: boolean;
                          title?: string;
                      };
                      description?: string;
                      execution?: { taskSupport?: "optional"
                      | "required"
                      | "forbidden" };
                      icons?: {
                          mimeType?: string;
                          sizes?: (...)[];
                          src: string;
                          theme?: "light" | "dark";
                      }[];
                      inputSchema: {
                          properties?: {
                              [key: string]: | string
                              | number
                              | boolean
                              | { [key: ...]: ... }
                              | (...)[]
                              | null;
                          };
                          required?: string[];
                          type: "object";
                          [key: string]: unknown;
                      };
                      name: string;
                      outputSchema?: { $schema?: string; [key: string]: unknown };
                      title?: string;
                  }[];
                  [key: string]: unknown;
              },
          >
      )
      | undefined

      Returns
          | (
              (
                  params:
                      | {
                          _meta?: {
                              "io.modelcontextprotocol/related-task"?: { taskId: string };
                              progressToken?: string | number;
                              [key: string]: unknown;
                          };
                          cursor?: string;
                      }
                      | undefined,
                  extra: BaseContext,
              ) => Promise<
                  {
                      _meta?: {
                          "io.modelcontextprotocol/serverInfo"?: {
                              description?: string;
                              icons?: { mimeType?: ...; sizes?: ...; src: ...; theme?: ... }[];
                              name: string;
                              title?: string;
                              version: string;
                              websiteUrl?: string;
                          };
                          [key: string]: unknown;
                      };
                      nextCursor?: string;
                      tools: {
                          _meta?: { [key: string]: unknown };
                          annotations?: {
                              destructiveHint?: boolean;
                              idempotentHint?: boolean;
                              openWorldHint?: boolean;
                              readOnlyHint?: boolean;
                              title?: string;
                          };
                          description?: string;
                          execution?: { taskSupport?: "optional"
                          | "required"
                          | "forbidden" };
                          icons?: {
                              mimeType?: string;
                              sizes?: (...)[];
                              src: string;
                              theme?: "light" | "dark";
                          }[];
                          inputSchema: {
                              properties?: {
                                  [key: string]: | string
                                  | number
                                  | boolean
                                  | { [key: ...]: ... }
                                  | (...)[]
                                  | null;
                              };
                              required?: string[];
                              type: "object";
                              [key: string]: unknown;
                          };
                          name: string;
                          outputSchema?: { $schema?: string; [key: string]: unknown };
                          title?: string;
                      }[];
                      [key: string]: unknown;
                  },
              >
          )
          | undefined

    • set onlisttools(
          callback:
              | (
                  (
                      params:
                          | {
                              _meta?: {
                                  "io.modelcontextprotocol/related-task"?: { taskId: string };
                                  progressToken?: string | number;
                                  [key: string]: unknown;
                              };
                              cursor?: string;
                          }
                          | undefined,
                      extra: BaseContext,
                  ) => Promise<
                      {
                          _meta?: {
                              "io.modelcontextprotocol/serverInfo"?: {
                                  description?: string;
                                  icons?: { mimeType?: ...; sizes?: ...; src: ...; theme?: ... }[];
                                  name: string;
                                  title?: string;
                                  version: string;
                                  websiteUrl?: string;
                              };
                              [key: string]: unknown;
                          };
                          nextCursor?: string;
                          tools: {
                              _meta?: { [key: string]: unknown };
                              annotations?: {
                                  destructiveHint?: boolean;
                                  idempotentHint?: boolean;
                                  openWorldHint?: boolean;
                                  readOnlyHint?: boolean;
                                  title?: string;
                              };
                              description?: string;
                              execution?: { taskSupport?: "optional"
                              | "required"
                              | "forbidden" };
                              icons?: {
                                  mimeType?: string;
                                  sizes?: (...)[];
                                  src: string;
                                  theme?: "light" | "dark";
                              }[];
                              inputSchema: {
                                  properties?: {
                                      [key: string]: | string
                                      | number
                                      | boolean
                                      | { [key: ...]: ... }
                                      | (...)[]
                                      | null;
                                  };
                                  required?: string[];
                                  type: "object";
                                  [key: string]: unknown;
                              };
                              name: string;
                              outputSchema?: { $schema?: string; [key: string]: unknown };
                              title?: string;
                          }[];
                          [key: string]: unknown;
                      },
                  >
              )
              | undefined,
      ): void

      Parameters

      • callback:
            | (
                (
                    params:
                        | {
                            _meta?: {
                                "io.modelcontextprotocol/related-task"?: { taskId: string };
                                progressToken?: string | number;
                                [key: string]: unknown;
                            };
                            cursor?: string;
                        }
                        | undefined,
                    extra: BaseContext,
                ) => Promise<
                    {
                        _meta?: {
                            "io.modelcontextprotocol/serverInfo"?: {
                                description?: string;
                                icons?: { mimeType?: ...; sizes?: ...; src: ...; theme?: ... }[];
                                name: string;
                                title?: string;
                                version: string;
                                websiteUrl?: string;
                            };
                            [key: string]: unknown;
                        };
                        nextCursor?: string;
                        tools: {
                            _meta?: { [key: string]: unknown };
                            annotations?: {
                                destructiveHint?: boolean;
                                idempotentHint?: boolean;
                                openWorldHint?: boolean;
                                readOnlyHint?: boolean;
                                title?: string;
                            };
                            description?: string;
                            execution?: { taskSupport?: "optional"
                            | "required"
                            | "forbidden" };
                            icons?: {
                                mimeType?: string;
                                sizes?: (...)[];
                                src: string;
                                theme?: "light" | "dark";
                            }[];
                            inputSchema: {
                                properties?: {
                                    [key: string]: | string
                                    | number
                                    | boolean
                                    | { [key: ...]: ... }
                                    | (...)[]
                                    | null;
                                };
                                required?: string[];
                                type: "object";
                                [key: string]: unknown;
                            };
                            name: string;
                            outputSchema?: { $schema?: string; [key: string]: unknown };
                            title?: string;
                        }[];
                        [key: string]: unknown;
                    },
                >
            )
            | undefined

      Returns void

    • get ontoolcancelled(): ((params: { reason?: string }) => void) | undefined

      Convenience handler for receiving tool cancellation notifications from the host.

      Set this property to register a handler that will be called when the host notifies that tool execution was cancelled. This can occur for various reasons including user action, sampling error, classifier intervention, or other interruptions. Apps should update their state and display appropriate feedback.

      Assigning replaces the previous handler; assigning undefined clears it. Use addEventListener to attach multiple listeners without replacing.

      Register handlers before calling connect to avoid missing notifications.

      Returns ((params: { reason?: string }) => void) | undefined

      app.ontoolcancelled = (params) => {
      console.log("Tool cancelled:", params.reason);
      // Update your UI to show cancellation state
      };

      Use addEventListener("toolcancelled", handler) instead — it composes with other listeners and supports cleanup via removeEventListener.

    • set ontoolcancelled(
          callback: ((params: { reason?: string }) => void) | undefined,
      ): void

      Parameters

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

      Returns void

    • get ontoolinput(): | ((params: { arguments?: Record<string, unknown> }) => void)
      | undefined

      Convenience handler for receiving complete tool input from the host.

      Set this property to register a handler that will be called when the host sends a tool's complete arguments. This is sent after a tool call begins and before the tool result is available.

      Assigning replaces the previous handler; assigning undefined clears it. Use addEventListener to attach multiple listeners without replacing.

      Register handlers before calling connect to avoid missing notifications.

      Returns ((params: { arguments?: Record<string, unknown> }) => void) | undefined

      // Register before connecting to ensure no notifications are missed
      app.ontoolinput = (params) => {
      console.log("Tool:", params.arguments);
      // Update your UI with the tool arguments
      };
      await app.connect();

      Use addEventListener("toolinput", handler) instead — it composes with other listeners and supports cleanup via removeEventListener.

      McpUiToolInputNotification for the notification structure

    • set ontoolinput(
          callback:
              | ((params: { arguments?: Record<string, unknown> }) => void)
              | undefined,
      ): void

      Parameters

      • callback: ((params: { arguments?: Record<string, unknown> }) => void) | undefined

      Returns void

    • get ontoolinputpartial(): | (
          (params: { arguments?: Record<string, unknown> }) => void
      )
      | undefined

      Convenience handler for receiving streaming partial tool input from the host.

      Set this property to register a handler that will be called as the host streams partial tool arguments during tool call initialization. This enables progressive rendering of tool arguments before they're complete.

      Important: Partial arguments are "healed" JSON — the host closes unclosed brackets/braces to produce valid JSON. This means objects may be incomplete (e.g., the last item in an array may be truncated). Use partial data only for preview UI, not for critical operations.

      Assigning replaces the previous handler; assigning undefined clears it. Use addEventListener to attach multiple listeners without replacing.

      Register handlers before calling connect to avoid missing notifications.

      Returns ((params: { arguments?: Record<string, unknown> }) => void) | undefined

      const codePreview = document.querySelector<HTMLPreElement>("#code-preview")!;
      const canvas = document.querySelector<HTMLCanvasElement>("#canvas")!;

      app.ontoolinputpartial = (params) => {
      codePreview.textContent = (params.arguments?.code as string) ?? "";
      codePreview.style.display = "block";
      canvas.style.display = "none";
      };

      app.ontoolinput = (params) => {
      codePreview.style.display = "none";
      canvas.style.display = "block";
      render(params.arguments?.code as string);
      };

      Use addEventListener("toolinputpartial", handler) instead — it composes with other listeners and supports cleanup via removeEventListener.

    • set ontoolinputpartial(
          callback:
              | ((params: { arguments?: Record<string, unknown> }) => void)
              | undefined,
      ): void

      Parameters

      • callback: ((params: { arguments?: Record<string, unknown> }) => void) | undefined

      Returns void

    • get ontoolresult(): | (
          (
              params: {
                  _meta?: {
                      "io.modelcontextprotocol/serverInfo"?: {
                          description?: string;
                          icons?: {
                              mimeType?: (...) | (...);
                              sizes?: (...) | (...);
                              src: string;
                              theme?: (...) | (...) | (...);
                          }[];
                          name: string;
                          title?: string;
                          version: string;
                          websiteUrl?: string;
                      };
                      [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;
                          size?: number;
                          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?: unknown;
                  [key: string]: unknown;
              },
          ) => void
      )
      | undefined

      Convenience handler for receiving tool execution results from the host.

      Set this property to register a handler that will be called when the host sends the result of a tool execution. This is sent after the tool completes on the MCP server, allowing your app to display the results or update its state.

      Assigning replaces the previous handler; assigning undefined clears it. Use addEventListener to attach multiple listeners without replacing.

      Register handlers before calling connect to avoid missing notifications.

      Returns
          | (
              (
                  params: {
                      _meta?: {
                          "io.modelcontextprotocol/serverInfo"?: {
                              description?: string;
                              icons?: {
                                  mimeType?: (...) | (...);
                                  sizes?: (...) | (...);
                                  src: string;
                                  theme?: (...) | (...) | (...);
                              }[];
                              name: string;
                              title?: string;
                              version: string;
                              websiteUrl?: string;
                          };
                          [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;
                              size?: number;
                              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?: unknown;
                      [key: string]: unknown;
                  },
              ) => void
          )
          | undefined

      app.ontoolresult = (params) => {
      if (params.isError) {
      console.error("Tool execution failed:", params.content);
      } else if (params.content) {
      console.log("Tool output:", params.content);
      }
      };

      Use addEventListener("toolresult", handler) instead — it composes with other listeners and supports cleanup via removeEventListener.

    • set ontoolresult(
          callback:
              | (
                  (
                      params: {
                          _meta?: {
                              "io.modelcontextprotocol/serverInfo"?: {
                                  description?: string;
                                  icons?: {
                                      mimeType?: (...) | (...);
                                      sizes?: (...) | (...);
                                      src: string;
                                      theme?: (...) | (...) | (...);
                                  }[];
                                  name: string;
                                  title?: string;
                                  version: string;
                                  websiteUrl?: string;
                              };
                              [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;
                                  size?: number;
                                  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?: unknown;
                          [key: string]: unknown;
                      },
                  ) => void
              )
              | undefined,
      ): void

      Parameters

      • callback:
            | (
                (
                    params: {
                        _meta?: {
                            "io.modelcontextprotocol/serverInfo"?: {
                                description?: string;
                                icons?: {
                                    mimeType?: (...) | (...);
                                    sizes?: (...) | (...);
                                    src: string;
                                    theme?: (...) | (...) | (...);
                                }[];
                                name: string;
                                title?: string;
                                version: string;
                                websiteUrl?: string;
                            };
                            [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;
                                size?: number;
                                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?: unknown;
                        [key: string]: unknown;
                    },
                ) => void
            )
            | undefined

      Returns void

    • get transport(): Transport | undefined

      Returns Transport | undefined

    Constructors

    • Create a new MCP App instance.

      Parameters

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

        App identification (name and version)

      • _appCapabilities: McpUiAppCapabilities = {}

        Features and capabilities this app provides

      • options: AppOptions = ...

        Configuration options including autoResize behavior

      Returns App

      const app = new App(
      { name: "MyApp", version: "1.0.0" },
      { tools: { listChanged: true } }, // capabilities
      { autoResize: true }, // options
      );

    Methods

    • Protected accessor for a registered request handler. Used by role classes that dispatch synthesized requests through the same stored handler chain (e.g. the Client fulfilling an embedded multi-round-trip input request).

      Parameters

      • method: string

      Returns
          | (
              (
                  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;
                      };
                  },
                  ctx: BaseContext,
              ) => Promise<
                  {
                      _meta?: {
                          "io.modelcontextprotocol/serverInfo"?: {
                              description?: string;
                              icons?: { mimeType?: ...; sizes?: ...; src: ...; theme?: ... }[];
                              name: string;
                              title?: string;
                              version: string;
                              websiteUrl?: string;
                          };
                          [key: string]: unknown;
                      };
                      [key: string]: unknown;
                  },
              >
          )
          | undefined

    • Transport-close hook. Subclass overrides MUST call super._onclose() after their own cleanup — base teardown (response-handler settlement, timeout clearing, in-flight request abort) does not run otherwise.

      Returns void

    • Inbound-notification dispatch. Subclass overrides MUST delegate unmatched traffic to super._onnotification(rawNotification, extra) — an override that consumes only what it owns and falls through to base dispatch for everything else.

      Parameters

      • rawNotification: {
            jsonrpc: "2.0";
            method: string;
            params?: {
                _meta?: {
                    "io.modelcontextprotocol/related-task"?: { taskId: string };
                    progressToken?: string | number;
                    [key: string]: unknown;
                };
                [key: string]: unknown;
            };
        }
      • Optionalextra: MessageExtraInfo

      Returns void

    • Inbound-response dispatch. Subclass overrides MUST delegate unmatched traffic to super._onresponse(response) — an override that consumes only what it owns and falls through to base dispatch for everything else.

      Parameters

      • response: JSONRPCResponse

      Returns void

    • The per-request _meta envelope this instance attaches to every outgoing request and notification, when one applies. The base implementation returns undefined (no envelope — the 2025-era posture, so legacy-era outbound traffic is byte-identical to a build without this seam). Client overrides it on a connection that negotiated a modern (2026-07-28+) era to return the reserved protocol-version / client-info / client-capabilities keys. User-supplied _meta keys take precedence over the auto-attached ones.

      Returns Readonly<Record<string, unknown>> | undefined

    • Hook for subclasses to supply the implementation identity the 2026-era encode seam stamps into outbound result _meta under io.modelcontextprotocol/serverInfo (spec PR #3002: servers SHOULD identify themselves on every response). The default is undefined — no stamp. Only Server overrides this: the key identifies the software producing a response, and the 2025-era codec never stamps anything regardless (the never-stamp guarantee).

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

    • Sends a request and waits for a response, using the provided schema for validation instead of the era registry's method-keyed entry.

      This is the internal implementation used by SDK methods whose result schema cannot be expressed as a method-keyed registry entry — the one surviving case is server.createMessage, whose result schema depends on the REQUEST params (tools vs no tools) — and by callers passing explicit compatibility schemas. Spec methods are still era-gated here: an explicit schema never smuggles a deleted method onto the wire.

      Type Parameters

      • T$1 extends StandardSchemaV1<unknown, unknown>

      Parameters

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

      Returns Promise<InferOutput<T$1>>

    • Extension point for non-complete decoded results in the response funnel: a result the wire codec discriminated into a kind other than 'complete' or 'invalid' is handed here for the role class to resolve. The base default surfaces it as a typed SdkErrorCode.UnsupportedResultType error (no retry).

      Intended consumers (named so the seam stays accountable):

      • the Client's multi-round-trip auto-fulfilment engine, which fulfils 'input_required' results through the registered elicitation/sampling/roots handlers and retries via flow.retry;
      • a future client-side terminal-result handler for subscriptions/listen, when the spec defines one.

      Server instances never receive input_required responses on their outbound legs and leave the base behavior in place.

      Type Parameters

      • T$1 extends StandardSchemaV1<unknown, unknown>

      Parameters

      • decoded: DecodedResult & { kind: "input_required" }
      • flow: NonCompleteResultFlow<T$1>

      Returns Promise<unknown>

    • Drop consult for inbound messages whose transport did not classify them at the edge — long-lived channels such as stdio, where a role class may need to decline traffic the negotiated era has no answer for (the client-side inbound-request drop on modern-era connections: the 2026-07-28 era has no server→client request channel, and on stdio the client must never write JSON-RPC responses).

      Consulted ONLY when the transport supplied no MessageExtraInfo.classification: edge-classified traffic never reaches the hook. Returning 'drop' discards the message without writing any response (requests are surfaced via onerror). The base implementation returns undefined: unclassified traffic keeps today's dispatch path unchanged. Era selection never happens here — era is instance state, owned by the serving entry that constructed and connected the instance.

      Parameters

      • _message:
            | {
                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;
                };
            }
            | {
                jsonrpc: "2.0";
                method: string;
                params?: {
                    _meta?: {
                        "io.modelcontextprotocol/related-task"?: { taskId: string };
                        progressToken?: string | number;
                        [key: string]: unknown;
                    };
                    [key: string]: unknown;
                };
            }

      Returns "drop" | undefined

    • Protected accessor for the instance's negotiated wire codec, for role classes (Client/Server/McpServer) routing era-dependent behavior through the codec's function-only surface — samplingResultVariant, outboundEnvelope, projectCallToolResult — instead of branching on the protocol version themselves.

      Returns WireCodec

    • Hook for subclasses to wrap a registered request handler with role-specific validation or behavior (e.g. Server validates tools/call results, Client validates elicitation/create mode and result). Runs for both the 2-arg and 3-arg registration paths. The default implementation is identity.

      Subclasses overriding this hook avoid redeclaring setRequestHandler's overload set.

      Parameters

      • _method: string
      • handler: (
            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;
                };
            },
            ctx: BaseContext,
        ) => Promise<
            {
                _meta?: {
                    "io.modelcontextprotocol/serverInfo"?: {
                        description?: string;
                        icons?: {
                            mimeType?: (...)
                            | (...);
                            sizes?: (...) | (...);
                            src: string;
                            theme?: (...) | (...) | (...);
                        }[];
                        name: string;
                        title?: string;
                        version: string;
                        websiteUrl?: string;
                    };
                    [key: string]: unknown;
                };
                [key: string]: unknown;
            },
        >

      Returns (
          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;
              };
          },
          ctx: BaseContext,
      ) => Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/serverInfo"?: {
                      description?: string;
                      icons?: {
                          mimeType?: (...)
                          | (...);
                          sizes?: (...) | (...);
                          src: string;
                          theme?: (...) | (...) | (...);
                      }[];
                      name: string;
                      title?: string;
                      version: string;
                      websiteUrl?: string;
                  };
                  [key: string]: unknown;
              };
              [key: string]: unknown;
          },
      >

    • 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 host supports the capability required for the given request method.

      Parameters

      • method: string

      Returns void

    • Internal

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

      Parameters

      • _method: string

      Returns void

    • Internal

      Verify that the app declared the capability required for the given request method.

      Parameters

      • method: string

      Returns void

    • Internal

      Parameters

      • ctx: BaseContext

      Returns BaseContext

    • Call a tool on the originating MCP server (proxied through the host).

      Apps can call tools to fetch fresh data or trigger server-side actions. The host proxies the request to the actual MCP server and returns the result.

      Parameters

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

        Tool name and arguments

      • Optionaloptions: RequestOptions

        Request options (timeout, etc.)

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/serverInfo"?: {
                      description?: string;
                      icons?: {
                          mimeType?: string;
                          sizes?: (...)[];
                          src: string;
                          theme?: "light" | "dark";
                      }[];
                      name: string;
                      title?: string;
                      version: string;
                      websiteUrl?: string;
                  };
                  [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;
                      size?: number;
                      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?: unknown;
              [key: string]: unknown;
          },
      >

      Tool execution result

      If the tool does not exist on the server

      If the request times out or the connection is lost

      If the host rejects the request

      Note: Tool-level execution errors are returned in the result with isError: true rather than throwing exceptions. Always check result.isError to distinguish between transport failures (thrown) and tool execution failures (returned).

      try {
      const result = await app.callServerTool({
      name: "get_weather",
      arguments: { location: "Tokyo" },
      });
      if (result.isError) {
      console.error("Tool returned error:", result.content);
      } else {
      console.log(result.content);
      }
      } catch (error) {
      console.error("Tool call failed:", error);
      }
    • Closes the connection.

      Returns Promise<void>

    • Establish connection with the host and perform initialization handshake.

      This method performs the following steps:

      1. Connects the transport layer
      2. Sends ui/initialize request with app info and capabilities
      3. Receives host capabilities and context in response
      4. Sends ui/notifications/initialized notification
      5. Sets up auto-resize using setupSizeChangedNotifications if enabled (default)

      If initialization fails, the connection is automatically closed and an error is thrown.

      Parameters

      • transport: Transport = ...

        Transport layer (typically PostMessageTransport)

      • Optionaloptions: RequestOptions

        Request options for the initialize request

      Returns Promise<void>

      If initialization fails or connection is lost

      const app = new App({ name: "MyApp", version: "1.0.0" }, {});

      try {
      await app.connect(new PostMessageTransport(window.parent, window.parent));
      console.log("Connected successfully!");
      } catch (error) {
      console.error("Failed to connect:", error);
      }
    • Request an LLM completion from the host (standard MCP sampling/createMessage).

      Enables the app to use the host's model connection for completions. The host has full discretion over which model to select and MAY modify or reject the request (human-in-the-loop). Check getHostCapabilities()?.sampling before calling — hosts without this capability will reject the request.

      This method reuses the stock MCP CreateMessageRequest shape. When params.tools is provided, the result is parsed with the extended schema that permits stopReason: "toolUse" and array content containing tool_use blocks.

      Parameters

      • params: {
            _meta?: {
                "io.modelcontextprotocol/related-task"?: { taskId: string };
                progressToken?: string | number;
                [key: string]: unknown;
            };
            includeContext?: "none"
            | "thisServer"
            | "allServers";
            maxTokens: number;
            messages: {
                _meta?: { [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 };
                        id: string;
                        input: { [key: string]: unknown };
                        name: string;
                        type: "tool_use";
                    }
                    | {
                        _meta?: { [key: string]: unknown };
                        content: (
                            | {
                                _meta?: { [key: ...]: ... };
                                annotations?: { audience?: ...; lastModified?: ...; priority?: ... };
                                text: string;
                                type: "text";
                            }
                            | {
                                _meta?: { [key: ...]: ... };
                                annotations?: { audience?: ...; lastModified?: ...; priority?: ... };
                                data: string;
                                mimeType: string;
                                type: "image";
                            }
                            | {
                                _meta?: { [key: ...]: ... };
                                annotations?: { audience?: ...; lastModified?: ...; priority?: ... };
                                data: string;
                                mimeType: string;
                                type: "audio";
                            }
                            | {
                                _meta?: { [key: ...]: ... };
                                annotations?: { audience?: ...; lastModified?: ...; priority?: ... };
                                description?: string;
                                icons?: (...)[];
                                mimeType?: string;
                                name: string;
                                size?: number;
                                title?: string;
                                type: "resource_link";
                                uri: string;
                            }
                            | {
                                _meta?: { [key: ...]: ... };
                                annotations?: { audience?: ...; lastModified?: ...; priority?: ... };
                                resource:
                                    | { _meta?: ...; mimeType?: ...; text: ...; uri: ... }
                                    | { _meta?: ...; blob: ...; mimeType?: ...; uri: ... };
                                type: "resource";
                            }
                        )[];
                        isError?: boolean;
                        structuredContent?: unknown;
                        toolUseId: string;
                        type: "tool_result";
                    }
                    | (
                        | {
                            _meta?: { [key: string]: unknown };
                            annotations?: {
                                audience?: (...) | (...);
                                lastModified?: (...) | (...);
                                priority?: (...) | (...);
                            };
                            text: string;
                            type: "text";
                        }
                        | {
                            _meta?: { [key: string]: unknown };
                            annotations?: {
                                audience?: (...) | (...);
                                lastModified?: (...) | (...);
                                priority?: (...) | (...);
                            };
                            data: string;
                            mimeType: string;
                            type: "image";
                        }
                        | {
                            _meta?: { [key: string]: unknown };
                            annotations?: {
                                audience?: (...) | (...);
                                lastModified?: (...) | (...);
                                priority?: (...) | (...);
                            };
                            data: string;
                            mimeType: string;
                            type: "audio";
                        }
                        | {
                            _meta?: { [key: string]: unknown };
                            id: string;
                            input: { [key: string]: unknown };
                            name: string;
                            type: "tool_use";
                        }
                        | {
                            _meta?: { [key: string]: unknown };
                            content: (
                                | { _meta?: ...; annotations?: ...; text: ...; type: ... }
                                | {
                                    _meta?: ...;
                                    annotations?: ...;
                                    data: ...;
                                    mimeType: ...;
                                    type: ...;
                                }
                                | {
                                    _meta?: ...;
                                    annotations?: ...;
                                    data: ...;
                                    mimeType: ...;
                                    type: ...;
                                }
                                | {
                                    _meta?: ...;
                                    annotations?: ...;
                                    description?: ...;
                                    icons?: ...;
                                    mimeType?: ...;
                                    name: ...;
                                    size?: ...;
                                    title?: ...;
                                    type: ...;
                                    uri: ...;
                                }
                                | { _meta?: ...; annotations?: ...; resource: ...; type: ... }
                            )[];
                            isError?: boolean;
                            structuredContent?: unknown;
                            toolUseId: string;
                            type: "tool_result";
                        }
                    )[];
                role: "user"
                | "assistant";
            }[];
            metadata?: {
                [key: string]: | string
                | number
                | boolean
                | (
                    { [x: string]: string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | ... 4 more ... | null)[] | null)[] | null)[] | null)[] | null)[] | null; }
                )
                | (
                    string | number | boolean | { [x: string]: string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | ... 4 more ... | null)[] | null)[] | null)[] | null)[] | null; } | (string | ... 4 more ... | null)[] | null
                )[]
                | null;
            };
            modelPreferences?: {
                costPriority?: number;
                hints?: { name?: string }[];
                intelligencePriority?: number;
                speedPriority?: number;
            };
            stopSequences?: string[];
            systemPrompt?: string;
            task?: { ttl?: number };
            temperature?: number;
            toolChoice?: { mode?: "required" | "none" | "auto" };
            tools?: {
                _meta?: { [key: string]: unknown };
                annotations?: {
                    destructiveHint?: boolean;
                    idempotentHint?: boolean;
                    openWorldHint?: boolean;
                    readOnlyHint?: boolean;
                    title?: string;
                };
                description?: string;
                execution?: { taskSupport?: "optional"
                | "required"
                | "forbidden" };
                icons?: {
                    mimeType?: string;
                    sizes?: string[];
                    src: string;
                    theme?: "light" | "dark";
                }[];
                inputSchema: {
                    properties?: {
                        [key: string]: | string
                        | number
                        | boolean
                        | {
                            [key: string]: string | number | boolean | { [x: string]: string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | ... 4 more ... | null)[] | null)[] | null)[] | null)[] | null; } | (string | ... 4 more ... | null)[] | null;
                        }
                        | (
                            string | number | boolean | { [x: string]: string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | ... 4 more ... | null)[] | null)[] | null)[] | null)[] | null; } | (string | ... 4 more ... | null)[] | null
                        )[]
                        | null;
                    };
                    required?: string[];
                    type: "object";
                    [key: string]: unknown;
                };
                name: string;
                outputSchema?: { $schema?: string; [key: string]: unknown };
                title?: string;
            }[];
        } & { tools?: undefined }

        Standard MCP CreateMessageRequest params (messages, maxTokens, systemPrompt, temperature, modelPreferences, tools, toolChoice, etc.)

      • Optionaloptions: RequestOptions

        Request options (timeout, abort signal)

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/serverInfo"?: {
                      description?: string;
                      icons?: {
                          mimeType?: string;
                          sizes?: (...)[];
                          src: string;
                          theme?: "light" | "dark";
                      }[];
                      name: string;
                      title?: string;
                      version: string;
                      websiteUrl?: string;
                  };
                  [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";
              };
              model: string;
              role: "user"
              | "assistant";
              stopReason?: string;
              [key: string]: unknown;
          },
      >

      CreateMessageResult (single content block) or CreateMessageResultWithTools (array content, may include tool_use blocks) depending on whether tools was set

      If the host rejects the request or does not support sampling

      If the request times out or the connection is lost

      const result = await app.createSamplingMessage({
      messages: [
      {
      role: "user",
      content: { type: "text", text: "Summarize this in one line." },
      },
      ],
      maxTokens: 100,
      });
      console.log(result.content);
      if (!app.getHostCapabilities()?.sampling?.tools) return;

      const result = await app.createSamplingMessage({
      messages,
      maxTokens: 1024,
      tools: [
      {
      name: "get_weather",
      description: "Get the current weather",
      inputSchema: {
      type: "object",
      properties: { city: { type: "string" } },
      },
      },
      ],
      });
      if (result.stopReason === "toolUse") {
      // result.content may be an array containing tool_use blocks
      }
      • CreateMessageRequest from @modelcontextprotocol/client for the request type
      • CreateMessageResult / CreateMessageResultWithTools from @modelcontextprotocol/client for result types
    • Request an LLM completion from the host (standard MCP sampling/createMessage).

      Enables the app to use the host's model connection for completions. The host has full discretion over which model to select and MAY modify or reject the request (human-in-the-loop). Check getHostCapabilities()?.sampling before calling — hosts without this capability will reject the request.

      This method reuses the stock MCP CreateMessageRequest shape. When params.tools is provided, the result is parsed with the extended schema that permits stopReason: "toolUse" and array content containing tool_use blocks.

      Parameters

      • params: {
            _meta?: {
                "io.modelcontextprotocol/related-task"?: { taskId: string };
                progressToken?: string | number;
                [key: string]: unknown;
            };
            includeContext?: "none"
            | "thisServer"
            | "allServers";
            maxTokens: number;
            messages: {
                _meta?: { [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 };
                        id: string;
                        input: { [key: string]: unknown };
                        name: string;
                        type: "tool_use";
                    }
                    | {
                        _meta?: { [key: string]: unknown };
                        content: (
                            | {
                                _meta?: { [key: string]: unknown };
                                annotations?: {
                                    audience?: (...) | (...);
                                    lastModified?: (...) | (...);
                                    priority?: (...) | (...);
                                };
                                text: string;
                                type: "text";
                            }
                            | {
                                _meta?: { [key: string]: unknown };
                                annotations?: {
                                    audience?: (...) | (...);
                                    lastModified?: (...) | (...);
                                    priority?: (...) | (...);
                                };
                                data: string;
                                mimeType: string;
                                type: "image";
                            }
                            | {
                                _meta?: { [key: string]: unknown };
                                annotations?: {
                                    audience?: (...) | (...);
                                    lastModified?: (...) | (...);
                                    priority?: (...) | (...);
                                };
                                data: string;
                                mimeType: string;
                                type: "audio";
                            }
                            | {
                                _meta?: { [key: string]: unknown };
                                annotations?: {
                                    audience?: (...) | (...);
                                    lastModified?: (...) | (...);
                                    priority?: (...) | (...);
                                };
                                description?: string;
                                icons?: { mimeType?: ...; sizes?: ...; src: ...; theme?: ... }[];
                                mimeType?: string;
                                name: string;
                                size?: number;
                                title?: string;
                                type: "resource_link";
                                uri: string;
                            }
                            | {
                                _meta?: { [key: string]: unknown };
                                annotations?: {
                                    audience?: (...) | (...);
                                    lastModified?: (...) | (...);
                                    priority?: (...) | (...);
                                };
                                resource: | {
                                    _meta?: (...)
                                    | (...);
                                    mimeType?: (...) | (...);
                                    text: string;
                                    uri: string;
                                }
                                | {
                                    _meta?: (...)
                                    | (...);
                                    blob: string;
                                    mimeType?: (...) | (...);
                                    uri: string;
                                };
                                type: "resource";
                            }
                        )[];
                        isError?: boolean;
                        structuredContent?: unknown;
                        toolUseId: string;
                        type: "tool_result";
                    }
                    | (
                        | {
                            _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 };
                            id: string;
                            input: { [key: string]: unknown };
                            name: string;
                            type: "tool_use";
                        }
                        | {
                            _meta?: { [key: string]: unknown };
                            content: (
                                | {
                                    _meta?: (...)
                                    | (...);
                                    annotations?: (...) | (...);
                                    text: string;
                                    type: "text";
                                }
                                | {
                                    _meta?: (...)
                                    | (...);
                                    annotations?: (...) | (...);
                                    data: string;
                                    mimeType: string;
                                    type: "image";
                                }
                                | {
                                    _meta?: (...)
                                    | (...);
                                    annotations?: (...) | (...);
                                    data: string;
                                    mimeType: string;
                                    type: "audio";
                                }
                                | {
                                    _meta?: (...)
                                    | (...);
                                    annotations?: (...) | (...);
                                    description?: (...) | (...);
                                    icons?: (...) | (...);
                                    mimeType?: (...) | (...);
                                    name: string;
                                    size?: (...) | (...);
                                    title?: (...) | (...);
                                    type: "resource_link";
                                    uri: string;
                                }
                                | {
                                    _meta?: (...)
                                    | (...);
                                    annotations?: (...) | (...);
                                    resource: (...) | (...);
                                    type: "resource";
                                }
                            )[];
                            isError?: boolean;
                            structuredContent?: unknown;
                            toolUseId: string;
                            type: "tool_result";
                        }
                    )[];
                role: "user"
                | "assistant";
            }[];
            metadata?: {
                [key: string]: | string
                | number
                | boolean
                | (
                    { [x: string]: string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | ... 4 more ... | null)[] | null)[] | null)[] | null)[] | null)[] | null; }
                )
                | (
                    string | number | boolean | { [x: string]: string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | ... 4 more ... | null)[] | null)[] | null)[] | null)[] | null; } | (string | ... 4 more ... | null)[] | null
                )[]
                | null;
            };
            modelPreferences?: {
                costPriority?: number;
                hints?: { name?: string }[];
                intelligencePriority?: number;
                speedPriority?: number;
            };
            stopSequences?: string[];
            systemPrompt?: string;
            task?: { ttl?: number };
            temperature?: number;
            toolChoice?: { mode?: "required" | "none" | "auto" };
            tools?: {
                _meta?: { [key: string]: unknown };
                annotations?: {
                    destructiveHint?: boolean;
                    idempotentHint?: boolean;
                    openWorldHint?: boolean;
                    readOnlyHint?: boolean;
                    title?: string;
                };
                description?: string;
                execution?: { taskSupport?: "optional"
                | "required"
                | "forbidden" };
                icons?: {
                    mimeType?: string;
                    sizes?: string[];
                    src: string;
                    theme?: "light" | "dark";
                }[];
                inputSchema: {
                    properties?: {
                        [key: string]: | string
                        | number
                        | boolean
                        | {
                            [key: string]: string | number | boolean | { [x: string]: string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | ... 4 more ... | null)[] | null)[] | null)[] | null)[] | null; } | (string | ... 4 more ... | null)[] | null;
                        }
                        | (
                            string | number | boolean | { [x: string]: string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | number | boolean | ... | (string | ... 4 more ... | null)[] | null)[] | null)[] | null)[] | null; } | (string | ... 4 more ... | null)[] | null
                        )[]
                        | null;
                    };
                    required?: string[];
                    type: "object";
                    [key: string]: unknown;
                };
                name: string;
                outputSchema?: { $schema?: string; [key: string]: unknown };
                title?: string;
            }[];
        }

        Standard MCP CreateMessageRequest params (messages, maxTokens, systemPrompt, temperature, modelPreferences, tools, toolChoice, etc.)

      • Optionaloptions: RequestOptions

        Request options (timeout, abort signal)

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/serverInfo"?: {
                      description?: string;
                      icons?: {
                          mimeType?: string;
                          sizes?: (...)[];
                          src: string;
                          theme?: "light" | "dark";
                      }[];
                      name: string;
                      title?: string;
                      version: string;
                      websiteUrl?: string;
                  };
                  [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 };
                  id: string;
                  input: { [key: string]: unknown };
                  name: string;
                  type: "tool_use";
              }
              | {
                  _meta?: { [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?: (...)
                              | (...);
                              sizes?: (...) | (...);
                              src: string;
                              theme?: (...) | (...) | (...);
                          }[];
                          mimeType?: string;
                          name: string;
                          size?: number;
                          title?: string;
                          type: "resource_link";
                          uri: string;
                      }
                      | {
                          _meta?: { [key: string]: unknown };
                          annotations?: {
                              audience?: (...)[];
                              lastModified?: string;
                              priority?: number;
                          };
                          resource: | {
                              _meta?: { [key: ...]: ... };
                              mimeType?: string;
                              text: string;
                              uri: string;
                          }
                          | {
                              _meta?: { [key: ...]: ... };
                              blob: string;
                              mimeType?: string;
                              uri: string;
                          };
                          type: "resource";
                      }
                  )[];
                  isError?: boolean;
                  structuredContent?: unknown;
                  toolUseId: string;
                  type: "tool_result";
              }
              | (
                  | {
                      _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 };
                      id: string;
                      input: { [key: string]: unknown };
                      name: string;
                      type: "tool_use";
                  }
                  | {
                      _meta?: { [key: string]: unknown };
                      content: (
                          | {
                              _meta?: { [key: ...]: ... };
                              annotations?: { audience?: ...; lastModified?: ...; priority?: ... };
                              text: string;
                              type: "text";
                          }
                          | {
                              _meta?: { [key: ...]: ... };
                              annotations?: { audience?: ...; lastModified?: ...; priority?: ... };
                              data: string;
                              mimeType: string;
                              type: "image";
                          }
                          | {
                              _meta?: { [key: ...]: ... };
                              annotations?: { audience?: ...; lastModified?: ...; priority?: ... };
                              data: string;
                              mimeType: string;
                              type: "audio";
                          }
                          | {
                              _meta?: { [key: ...]: ... };
                              annotations?: { audience?: ...; lastModified?: ...; priority?: ... };
                              description?: string;
                              icons?: (...)[];
                              mimeType?: string;
                              name: string;
                              size?: number;
                              title?: string;
                              type: "resource_link";
                              uri: string;
                          }
                          | {
                              _meta?: { [key: ...]: ... };
                              annotations?: { audience?: ...; lastModified?: ...; priority?: ... };
                              resource:
                                  | { _meta?: ...; mimeType?: ...; text: ...; uri: ... }
                                  | { _meta?: ...; blob: ...; mimeType?: ...; uri: ... };
                              type: "resource";
                          }
                      )[];
                      isError?: boolean;
                      structuredContent?: unknown;
                      toolUseId: string;
                      type: "tool_result";
                  }
              )[];
              model: string;
              role: "user"
              | "assistant";
              stopReason?: string;
              [key: string]: unknown;
          },
      >

      CreateMessageResult (single content block) or CreateMessageResultWithTools (array content, may include tool_use blocks) depending on whether tools was set

      If the host rejects the request or does not support sampling

      If the request times out or the connection is lost

      const result = await app.createSamplingMessage({
      messages: [
      {
      role: "user",
      content: { type: "text", text: "Summarize this in one line." },
      },
      ],
      maxTokens: 100,
      });
      console.log(result.content);
      if (!app.getHostCapabilities()?.sampling?.tools) return;

      const result = await app.createSamplingMessage({
      messages,
      maxTokens: 1024,
      tools: [
      {
      name: "get_weather",
      description: "Get the current weather",
      inputSchema: {
      type: "object",
      properties: { city: { type: "string" } },
      },
      },
      ],
      });
      if (result.stopReason === "toolUse") {
      // result.content may be an array containing tool_use blocks
      }
      • CreateMessageRequest from @modelcontextprotocol/client for the request type
      • CreateMessageResult / CreateMessageResultWithTools from @modelcontextprotocol/client for result types
    • Request the host to download a file.

      Since MCP Apps run in sandboxed iframes where direct downloads are blocked, this provides a host-mediated mechanism for file exports. The host will typically show a confirmation dialog before initiating the download.

      Uses standard MCP resource types: EmbeddedResource for inline content and ResourceLink for content the host can fetch directly.

      Parameters

      • 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;
                    size?: number;
                    title?: string;
                    type: "resource_link";
                    uri: string;
                }
            )[];
        }

        Resource contents to download

        • 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;
                  size?: number;
                  title?: string;
                  type: "resource_link";
                  uri: string;
              }
          )[]

          Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.

      • Optionaloptions: RequestOptions

        Request options (timeout, etc.)

      Returns Promise<{ isError?: boolean; [key: string]: unknown }>

      Result with isError: true if the host denied the request (e.g., user cancelled)

      If the request times out or the connection is lost

      const data = JSON.stringify({ items: selectedItems }, null, 2);
      const { isError } = await app.downloadFile({
      contents: [{
      type: "resource",
      resource: {
      uri: "file:///export.json",
      mimeType: "application/json",
      text: data,
      },
      }],
      });
      if (isError) {
      console.warn("Download denied or cancelled");
      }
      const { isError } = await app.downloadFile({
      contents: [{
      type: "resource",
      resource: {
      uri: "file:///image.png",
      mimeType: "image/png",
      blob: base64EncodedPng,
      },
      }],
      });
      const { isError } = await app.downloadFile({
      contents: [{
      type: "resource_link",
      uri: "https://api.example.com/reports/q4.pdf",
      name: "Q4 Report",
      mimeType: "application/pdf",
      }],
      });
    • Get the host's capabilities discovered during initialization.

      Returns the capabilities that the host advertised during the connect handshake. Returns undefined if called before connection is established.

      Returns McpUiHostCapabilities | undefined

      Host capabilities, or undefined if not yet connected

      await app.connect();
      if (app.getHostCapabilities()?.serverTools) {
      console.log("Host supports server tool calls");
      }
    • Get the host context discovered during initialization.

      Returns the host context that was provided in the initialization response, including tool info, theme, locale, and other environment details. This context is automatically updated when the host sends ui/notifications/host-context-changed notifications.

      Returns undefined if called before connection is established.

      Returns McpUiHostContext | undefined

      Host context, or undefined if not yet connected

      await app.connect(transport);
      const context = app.getHostContext();
      if (context?.theme === "dark") {
      document.body.classList.add("dark-theme");
      }
      if (context?.toolInfo) {
      console.log("Tool:", context.toolInfo.tool.name);
      }
    • Get the host's implementation info discovered during initialization.

      Returns the host's name and version as advertised during the connect handshake. Returns undefined if called before connection is established.

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

      Host implementation info, or undefined if not yet connected

      await app.connect(transport);
      const { name, version } = app.getHostVersion() ?? {};
      console.log(`Connected to ${name} v${version}`);

      connect for the initialization handshake

    • List available resources from the originating MCP server (proxied through the host).

      Apps can list resources to discover what content is available on the MCP server. This enables dynamic resource discovery and building resource browsers or pickers. The host proxies the request to the actual MCP server and returns the resource list.

      Results may be paginated using the cursor parameter for servers with many resources.

      Parameters

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

        Optional parameters (omit for all resources, or { cursor } for pagination)

      • Optionaloptions: RequestOptions

        Request options (timeout, etc.)

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/serverInfo"?: {
                      description?: string;
                      icons?: {
                          mimeType?: string;
                          sizes?: (...)[];
                          src: string;
                          theme?: "light" | "dark";
                      }[];
                      name: string;
                      title?: string;
                      version: string;
                      websiteUrl?: string;
                  };
                  [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;
                  size?: number;
                  title?: string;
                  uri: string;
              }[];
              [key: string]: unknown;
          },
      >

      List of resources with their URIs, names, descriptions, mimeTypes, and optional pagination cursor

      If the request times out or the connection is lost

      If the host rejects the request

      try {
      const result = await app.listServerResources();
      const videoResources = result.resources.filter((r) =>
      r.mimeType?.startsWith("video/"),
      );
      videoResources.forEach((resource) => {
      const option = document.createElement("option");
      option.value = resource.uri;
      option.textContent = resource.description || resource.name;
      selectElement.appendChild(option);
      });
      } catch (error) {
      console.error("Failed to list resources:", error);
      }

      readServerResource to read a specific resource

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

      Parameters

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

      Returns Promise<void>

    • Request the host to open an external URL in the default browser.

      The host may deny this request based on user preferences or security policy. Apps should handle rejection gracefully by checking result.isError.

      Parameters

      • params: { url: string }

        URL to open

        • url: string

          URL to open in the host's browser

      • Optionaloptions: RequestOptions

        Request options (timeout, etc.)

      Returns Promise<{ isError?: boolean; [key: string]: unknown }>

      Result with isError: true if the host denied the request (e.g., blocked domain, user cancelled)

      If the request times out or the connection is lost

      const { isError } = await app.openLink({ url: "https://docs.example.com" });
      if (isError) {
      // Host denied the request (e.g., blocked domain, user cancelled)
      // Optionally show fallback: display URL for manual copy
      console.warn("Link request denied");
      }
    • Read a resource from the originating MCP server (proxied through the host).

      Apps can read resources to access files, data, or other content provided by the MCP server. Resources are identified by URI (e.g., file:///path/to/file or custom schemes like videos://bunny-1mb). The host proxies the request to the actual MCP server and returns the resource content.

      Parameters

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

        Resource URI to read

      • Optionaloptions: RequestOptions

        Request options (timeout, etc.)

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/serverInfo"?: {
                      description?: string;
                      icons?: {
                          mimeType?: string;
                          sizes?: (...)[];
                          src: string;
                          theme?: "light" | "dark";
                      }[];
                      name: string;
                      title?: string;
                      version: string;
                      websiteUrl?: string;
                  };
                  [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;
          },
      >

      Resource content with URI, name, description, mimeType, and contents array

      If the resource does not exist on the server

      If the request times out or the connection is lost

      If the host rejects the request

      try {
      const result = await app.readServerResource({
      uri: "videos://bunny-1mb",
      });
      const content = result.contents[0];
      if (content && "blob" in content) {
      const binary = Uint8Array.from(atob(content.blob), (c) =>
      c.charCodeAt(0),
      );
      const url = URL.createObjectURL(
      new Blob([binary], { type: content.mimeType || "video/mp4" }),
      );
      videoElement.src = url;
      videoElement.play();
      }
      } catch (error) {
      console.error("Failed to read resource:", error);
      }

      listServerResources to discover available resources

    • Type Parameters

      Parameters

      • name: string
      • config: {
            _meta?: Record<string, unknown>;
            annotations?: {
                destructiveHint?: boolean;
                idempotentHint?: boolean;
                openWorldHint?: boolean;
                readOnlyHint?: boolean;
                title?: string;
            };
            description?: string;
            inputSchema?: InputArgs;
            outputSchema?: OutputArgs;
            title?: string;
        }
      • cb: AppToolCallback<InputArgs, OutputArgs>

      Returns RegisteredAppTool

    • Sends a request and waits for a response.

      For spec methods the result schema is resolved automatically from the method name and the return type is method-keyed. For custom (non-spec) methods, pass a resultSchema as the second argument; the response is validated against it and the return type is inferred from the schema.

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

      Type Parameters

      • M$1 extends RequestMethod

      Parameters

      • request: { method: M$1; params?: Record<string, unknown> }
      • Optionaloptions: RequestOptions

      Returns Promise<ResultTypeMap[M$1]>

    • Sends a request and waits for a response.

      For spec methods the result schema is resolved automatically from the method name and the return type is method-keyed. For custom (non-spec) methods, pass a resultSchema as the second argument; the response is validated against it and the return type is inferred from the schema.

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

      Type Parameters

      • T$1 extends StandardSchemaV1<unknown, unknown>

      Parameters

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

      Returns Promise<InferOutput<T$1>>

    • Request a change to the display mode.

      Requests the host to change the UI container to the specified display mode (e.g., "inline", "fullscreen", "pip"). The host will respond with the actual display mode that was set, which may differ from the requested mode if the requested mode is not available (check availableDisplayModes in host context).

      Parameters

      • params: { mode: McpUiDisplayMode }

        The display mode being requested

      • Optionaloptions: RequestOptions

        Request options (timeout, etc.)

      Returns Promise<{ mode: "inline" | "fullscreen" | "pip"; [key: string]: unknown }>

      Result containing the actual display mode that was set

      const container = document.getElementById("main")!;
      const ctx = app.getHostContext();
      const newMode = ctx?.displayMode === "inline" ? "fullscreen" : "inline";
      if (ctx?.availableDisplayModes?.includes(newMode)) {
      const result = await app.requestDisplayMode({ mode: newMode });
      container.classList.toggle("fullscreen", result.mode === "fullscreen");
      }
    • Request the host to tear down this app.

      Apps call this method to request that the host tear them down. The host decides whether to proceed - if approved, the host will send ui/resource-teardown to allow the app to perform gracefull termination before being unmounted. This piggybacks on the existing teardown mechanism, ensuring the app only needs a single shutdown procedure (via onteardown) regardless of whether the teardown was initiated by the app or the host.

      This is a fire-and-forget notification - no response is expected. If the host approves, the app will receive a ui/resource-teardown request via the onteardown handler to persist unsaved state.

      Parameters

      • params: {} | undefined = {}

        Empty params object (reserved for future use)

      Returns Promise<void>

      Promise that resolves when the notification is sent

      // User clicks "Done" button in the app
      async function handleDoneClick() {
      // Request the host to tear down the app
      await app.requestTeardown();
      // If host approves, onteardown handler will be called for termination
      }

      // Set up teardown handler (called for both app-initiated and host-initiated teardown)
      app.onteardown = async () => {
      await saveState();
      closeConnections();
      return {};
      };
    • Send log messages to the host for debugging and telemetry.

      Logs are not added to the conversation but may be recorded by the host for debugging purposes.

      Parameters

      • 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;
        }

        Log level and message

      Returns Promise<void>

      Promise that resolves when the log notification is sent

      app.sendLog({
      level: "info",
      data: "Weather data refreshed",
      logger: "WeatherApp",
      });
    • Send a message to the host's chat interface.

      Enables the app to add messages to the conversation thread. Useful for user-initiated messages or app-to-conversation communication.

      Parameters

      • params: { content: ContentBlock[]; role: "user" }

        Message role and content

        • content: ContentBlock[]

          Message content blocks (text, image, etc.).

        • role: "user"

          Message role, currently only "user" is supported.

      • Optionaloptions: RequestOptions

        Request options (timeout, etc.)

      Returns Promise<{ isError?: boolean; [key: string]: unknown }>

      Result with optional isError flag indicating host rejection

      If the request times out or the connection is lost

      try {
      const result = await app.sendMessage({
      role: "user",
      content: [{ type: "text", text: "Show me details for item #42" }],
      });
      if (result.isError) {
      console.error("Host rejected the message");
      // Handle rejection appropriately for your app
      }
      } catch (error) {
      console.error("Failed to send message:", error);
      // Handle transport/protocol error
      }
      const markdown = `---
      word-count: ${fullTranscript.split(/\s+/).length}
      speaker-names: ${speakerNames.join(", ")}
      ---

      ${fullTranscript}`;

      // Offload long transcript to model context
      await app.updateModelContext({ content: [{ type: "text", text: markdown }] });

      // Send brief trigger message
      await app.sendMessage({
      role: "user",
      content: [{ type: "text", text: "Summarize the key points" }],
      });

      McpUiMessageRequest for request structure

    • Notify the host of UI size changes.

      Apps can manually report size changes to help the host adjust the container. If autoResize is enabled (default), this is called automatically.

      Parameters

      • params: { height?: number; width?: number }

        New width and height in pixels

        • Optionalheight?: number

          New height in pixels.

        • Optionalwidth?: number

          New width in pixels.

      Returns Promise<void>

      Promise that resolves when the notification is sent

      app.sendSizeChanged({
      width: 400,
      height: 600,
      });

      McpUiSizeChangedNotification for notification structure

    • Parameters

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

      Returns Promise<void>

    • Set up automatic size change notifications using ResizeObserver.

      Observes both document.documentElement and document.body for size changes and automatically sends ui/notifications/size-changed notifications to the host. The notifications are debounced using requestAnimationFrame to avoid duplicates.

      Note: This method is automatically called by connect() if the autoResize option is true (default). You typically don't need to call this manually unless you disabled autoResize and want to enable it later.

      Returns () => void

      Cleanup function to disconnect the observer

      const app = new App(
      { name: "MyApp", version: "1.0.0" },
      {},
      { autoResize: false },
      );
      await app.connect(transport);

      // Later, enable auto-resize manually
      const cleanup = app.setupSizeChangedNotifications();

      // Clean up when done
      cleanup();
    • Update the host's model context with app state.

      Context updates are intended to be available to the model in future turns, without triggering an immediate model response (unlike sendMessage).

      The host will typically defer sending the context to the model until the next user message — either from the actual user or via sendMessage. Only the last update is sent; each call overwrites any previous context.

      Parameters

      • params: { content?: ContentBlock[]; structuredContent?: Record<string, unknown> }

        Context content and/or structured content

        • Optionalcontent?: ContentBlock[]

          Context content blocks (text, image, etc.).

        • OptionalstructuredContent?: Record<string, unknown>

          Structured content for machine-readable context data.

      • Optionaloptions: RequestOptions

        Request options (timeout, etc.)

      Returns Promise<
          {
              _meta?: {
                  "io.modelcontextprotocol/serverInfo"?: {
                      description?: string;
                      icons?: {
                          mimeType?: string;
                          sizes?: (...)[];
                          src: string;
                          theme?: "light" | "dark";
                      }[];
                      name: string;
                      title?: string;
                      version: string;
                      websiteUrl?: string;
                  };
                  [key: string]: unknown;
              };
          },
      >

      Promise that resolves when the context update is acknowledged

      If the host rejects the context update (e.g., unsupported content type)

      If the request times out or the connection is lost

      const markdown = `---
      item-count: ${itemList.length}
      total-cost: ${totalCost}
      currency: ${currency}
      ---

      User is viewing their shopping cart with ${itemList.length} items selected:

      ${itemList.map((item) => `- ${item}`).join("\n")}`;

      await app.updateModelContext({
      content: [{ type: "text", text: markdown }],
      });
      try {
      const _stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      // ... use _stream for transcription
      } catch (err) {
      // Inform the model that the app is in a degraded state
      await app.updateModelContext({
      content: [
      {
      type: "text",
      text: "Error: transcription unavailable",
      },
      ],
      });
      }
    • Parameters

      • name: string
      • previous: unknown
      • next: unknown

      Returns void

    Properties

    _negotiatedProtocolVersion?: string

    The protocol version negotiated for the current connection (undefined before negotiation completes), which determines the wire era this instance speaks. Set by the SDK's negotiation and initialize paths (Client.connect, Server._oninitialize).

    _supportedProtocolVersions: string[]
    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;
            };
        },
        ctx: BaseContext,
    ) => Promise<
        {
            _meta?: {
                "io.modelcontextprotocol/serverInfo"?: {
                    description?: string;
                    icons?: { mimeType?: ...; sizes?: ...; src: ...; theme?: ... }[];
                    name: string;
                    title?: string;
                    version: string;
                    websiteUrl?: string;
                };
                [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.

    removeNotificationHandler: (method: string) => void = ...

    Removes the notification handler for the given method.

    removeRequestHandler: (method: string) => void = ...

    Removes the request handler for the given method.

    replaceRequestHandler: {
        <M$1 extends RequestMethod>(
            method: M$1,
            handler: (
                request: RequestTypeMap[M$1],
                ctx: BaseContext,
            ) => HandlerResultTypeMap[M$1] | Promise<HandlerResultTypeMap[M$1]>,
        ): void;
        <
            P extends StandardSchemaV1<unknown, unknown>,
            R extends StandardSchemaV1<unknown, unknown> | undefined = undefined,
        >(
            method: string,
            schemas: { params: P; result?: R },
            handler: (
                params: InferOutput<P>,
                ctx: BaseContext,
            ) => InferHandlerResult<R> | Promise<InferHandlerResult<R>>,
        ): void;
    } = ...

    Register a request handler with replace semantics, bypassing the double-set protection of setRequestHandler. Used by the on* request-handler setters.

    Type Declaration

      • <M$1 extends RequestMethod>(
            method: M$1,
            handler: (
                request: RequestTypeMap[M$1],
                ctx: BaseContext,
            ) => HandlerResultTypeMap[M$1] | Promise<HandlerResultTypeMap[M$1]>,
        ): 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.

        For spec methods, pass (method, handler); the request is parsed with the spec schema and the handler receives the typed Request. For custom (non-spec) methods, pass (method, schemas, handler); params are validated against schemas.params and the handler receives the parsed params object directly. Supplying schemas.result types the handler's return value.

        Type Parameters

        • M$1 extends RequestMethod

        Parameters

        • method: M$1
        • handler: (
              request: RequestTypeMap[M$1],
              ctx: BaseContext,
          ) => HandlerResultTypeMap[M$1] | Promise<HandlerResultTypeMap[M$1]>

        Returns void

        const SearchParams = z.object({ query: z.string(), limit: z.number().optional() });
        const SearchResult = z.object({ hits: z.array(z.string()) });

        protocol.setRequestHandler('acme/search', { params: SearchParams, result: SearchResult }, async (params, _ctx) => {
        return { hits: [`result for ${params.query}`] };
        });
      • <
            P extends StandardSchemaV1<unknown, unknown>,
            R extends StandardSchemaV1<unknown, unknown> | undefined = undefined,
        >(
            method: string,
            schemas: { params: P; result?: R },
            handler: (
                params: InferOutput<P>,
                ctx: BaseContext,
            ) => InferHandlerResult<R> | Promise<InferHandlerResult<R>>,
        ): 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.

        For spec methods, pass (method, handler); the request is parsed with the spec schema and the handler receives the typed Request. For custom (non-spec) methods, pass (method, schemas, handler); params are validated against schemas.params and the handler receives the parsed params object directly. Supplying schemas.result types the handler's return value.

        Type Parameters

        • P extends StandardSchemaV1<unknown, unknown>
        • R extends StandardSchemaV1<unknown, unknown> | undefined = undefined

        Parameters

        • method: string
        • schemas: { params: P; result?: R }
        • handler: (
              params: InferOutput<P>,
              ctx: BaseContext,
          ) => InferHandlerResult<R> | Promise<InferHandlerResult<R>>

        Returns void

        const SearchParams = z.object({ query: z.string(), limit: z.number().optional() });
        const SearchResult = z.object({ hits: z.array(z.string()) });

        protocol.setRequestHandler('acme/search', { params: SearchParams, result: SearchResult }, async (params, _ctx) => {
        return { hits: [`result for ${params.query}`] };
        });
    sendOpenLink: (
        params: { url: string },
        options?: RequestOptions,
    ) => Promise<{ isError?: boolean; [key: string]: unknown }> = ...

    Type Declaration

      • (
            params: { url: string },
            options?: RequestOptions,
        ): Promise<{ isError?: boolean; [key: string]: unknown }>
      • Request the host to open an external URL in the default browser.

        The host may deny this request based on user preferences or security policy. Apps should handle rejection gracefully by checking result.isError.

        Parameters

        • params: { url: string }

          URL to open

          • url: string

            URL to open in the host's browser

        • Optionaloptions: RequestOptions

          Request options (timeout, etc.)

        Returns Promise<{ isError?: boolean; [key: string]: unknown }>

        Result with isError: true if the host denied the request (e.g., blocked domain, user cancelled)

        If the request times out or the connection is lost

        const { isError } = await app.openLink({ url: "https://docs.example.com" });
        if (isError) {
        // Host denied the request (e.g., blocked domain, user cancelled)
        // Optionally show fallback: display URL for manual copy
        console.warn("Link request denied");
        }

    Use openLink instead

    setNotificationHandler: LegacyNotificationHandlerSetter<
        {
            <M$1 extends NotificationMethod>(
                method: M$1,
                handler: (notification: NotificationTypeMap[M$1]) => void | Promise<void>,
            ): void;
            <P extends StandardSchemaV1<unknown, unknown>>(
                method: string,
                schemas: { params: P },
                handler: (
                    params: InferOutput<P>,
                    notification: {
                        method: string;
                        params?: {
                            _meta?: {
                                "io.modelcontextprotocol/related-task"?: { taskId: string };
                                progressToken?: string | number;
                                [key: string]: unknown;
                            };
                            [key: string]: unknown;
                        };
                    },
                ) => void
                | Promise<void>,
            ): void;
        },
    > = ...

    Registers a notification handler. Throws if a handler for the same method has already been registered — use the on* setter (replace semantics) or addEventListener (multi-listener) for mapped events.

    if a handler for this method is already registered.

    setRequestHandler: LegacyRequestHandlerSetter<
        {
            <M$1 extends RequestMethod>(
                method: M$1,
                handler: (
                    request: RequestTypeMap[M$1],
                    ctx: BaseContext,
                ) => HandlerResultTypeMap[M$1] | Promise<HandlerResultTypeMap[M$1]>,
            ): void;
            <
                P extends StandardSchemaV1<unknown, unknown>,
                R extends StandardSchemaV1<unknown, unknown> | undefined = undefined,
            >(
                method: string,
                schemas: { params: P; result?: R },
                handler: (
                    params: InferOutput<P>,
                    ctx: BaseContext,
                ) => InferHandlerResult<R> | Promise<InferHandlerResult<R>>,
            ): void;
        },
    > = ...

    Registers a request handler. Throws if a handler for the same method has already been registered — use the on* setter for replace semantics.

    if a handler for this method is already registered.