import { App, type McpUiHostContext, type RegisteredAppTool } from "@modelcontextprotocol/ext-apps"; import type { CallToolResult, ContentBlock } from "@modelcontextprotocol/server"; import type { DisplayMode } from "../types/host-types.js"; import type { FileMetadata } from "../types/file-types.js"; import { type ToolContextError } from "../types/result-types.js"; import { ModelContextStore } from "./model-context-store.js"; import type { NormalizedViewConfig } from "./view-config.js"; /** Transport accepted by {@link App.connect}. */ export type ViewRuntimeTransport = NonNullable[0]>; type Listener = () => void; /** * Tool-channel snapshot for the invocation that rendered this View. * * Input notifications replace `toolInput` while the invocation is pending. * The first structured result, tool error, or host cancellation latches a * terminal state; all later ambient lifecycle notifications are ignored. * * @internal */ export interface ToolSnapshot { /** * Pending until the first structured result, tool error, or host * cancellation, then terminal. */ status: "pending" | "ready" | "error"; /** Model-visible tool output from the last ready result's `structuredContent`. */ toolOutput: unknown; /** Model-visible content blocks from the last tool result (ready or error). */ content: ContentBlock[] | undefined; /** * Latest progressive tool arguments from the host. Partial and complete * notifications replace the same snapshot; last write wins. */ toolInput: Record | undefined; /** View-only result `_meta` channel. */ meta: Record | undefined; /** * Tool error or host cancellation for the rendering invocation. */ error: ToolContextError | undefined; } /** * Host-channel snapshot: negotiated host context and connection status. * * @internal */ export interface HostSnapshot { /** Current host context (updated on `host-context-changed`). */ hostContext: McpUiHostContext | undefined; /** Whether the App handshake completed. */ isConnected: boolean; /** Terminal connection failure for this mount, if any. */ connectionError: Error | undefined; } /** * Display-channel snapshot: current mode and negotiated available modes. * * @internal */ export interface DisplaySnapshot { /** How the host is currently displaying the view. */ displayMode: DisplayMode; /** * Negotiated modes: intersection of normalized * {@link NormalizedViewConfig.displayModes} and * `hostContext.availableDisplayModes`. When the host omits available modes, * only `"inline"`. */ availableDisplayModes: readonly DisplayMode[]; } /** * ChatGPT file-extension channel snapshot. * * This channel deliberately represents only the optional file APIs used by * `useFiles`; the runtime does not mirror other `window.openai` globals. * * @internal */ export interface FilesSnapshot { /** Whether both upload and temporary-download-url helpers are available. */ isSupported: boolean; } /** * Parameters for {@link McpAppRuntime.callServerTool}. * * @internal */ export type CallToolParams = Parameters[0]; /** * Parameters for {@link McpAppRuntime.sendMessage}. * * @internal */ export type SendMessageParams = Parameters[0]; /** * Parameters for {@link McpAppRuntime.openLink}. * * @internal */ export type OpenLinkParams = Parameters[0]; /** * Parameters for {@link McpAppRuntime.requestDisplayMode}. * * @internal */ export type RequestDisplayModeParams = Parameters[0]; /** * Parameters for {@link McpAppRuntime.sendSizeChanged}. * * @internal */ export type SizeChangedParams = Parameters[0]; /** * Config passed to {@link McpAppRuntime.registerViewTool} (ext-apps shape). * * @internal */ export type ViewToolConfig = Parameters[1]; /** * Callback passed to {@link McpAppRuntime.registerViewTool}. * * @internal */ export type ViewToolCallback = Parameters[2]; /** * Per-document MCP Apps runtime: owns one guest {@link App}, one cached * connection attempt, tool-handler handoff, narrow external-store channels, * one shared view-state/model-context store, and disposal. * * Created by {@link createMcpAppRuntime} / {@link bootstrapView}. Hooks obtain * the instance from {@link ViewRuntimeContext}. * * @internal */ export interface McpAppRuntime { /** Normalized immutable view configuration fixed at construction. */ readonly config: NormalizedViewConfig; /** * Per-runtime structured view state, model-context tree, and async flush pump. * * Constructed with this runtime and disposed with it. React components obtain * it via {@link useViewRuntime}. */ readonly modelContextStore: ModelContextStore; /** Connect once, or return the cached in-flight / settled connection promise. */ connect(): Promise; /** * Dispose the model-context store (so late in-flight completions are * ignored), prevent late event delivery, clear listeners and snapshots, and * close the App/transport. * * Callers should unmount the view tree first (see `disposeView`) so hook * cleanup can run while the App connection still exists. */ dispose(): Promise; /** Subscribe to tool-channel changes. */ subscribeTool(listener: Listener): () => void; /** Current tool-channel snapshot (stable until a tool field changes). */ getToolSnapshot(): ToolSnapshot; /** Subscribe to host-channel changes. */ subscribeHost(listener: Listener): () => void; /** Current host-channel snapshot (stable until host/connection fields change). */ getHostSnapshot(): HostSnapshot; /** Subscribe to theme-channel changes. */ subscribeTheme(listener: Listener): () => void; /** Current theme (`"light"` until the host reports otherwise). Primitive; stable until theme changes. */ getThemeSnapshot(): "light" | "dark"; /** Subscribe to display-channel changes. */ subscribeDisplay(listener: Listener): () => void; /** * Current display-channel snapshot (stable until `displayMode` or * negotiated `availableDisplayModes` change). */ getDisplaySnapshot(): DisplaySnapshot; /** Subscribe to ChatGPT file-extension availability changes. */ subscribeFiles(listener: Listener): () => void; /** Current ChatGPT file-extension snapshot. */ getFilesSnapshot(): FilesSnapshot; /** Runtime-owned guest {@link App}, or `null` after disposal. */ getApp(): App | null; /** Call a server tool through the host. */ callServerTool(params: CallToolParams): Promise; /** Send a follow-up message through the host. */ sendMessage(params: SendMessageParams): Promise; /** Ask the host to open an external link. */ openLink(params: OpenLinkParams): Promise; /** Request a display-mode change from the host. */ requestDisplayMode(params: RequestDisplayModeParams): Promise; /** Notify the host of a size change. */ sendSizeChanged(params: SizeChangedParams): Promise; /** Upload a file through ChatGPT's optional file extension. */ uploadFile(file: File): Promise; /** Request a temporary download URL through ChatGPT's file extension. */ getFileDownloadUrl(file: FileMetadata): Promise<{ downloadUrl: string; }>; /** * Register a view tool, performing the empty-handler → registry handoff on * the first call. Must remain synchronous relative to the handoff. */ registerViewTool(name: string, config: ViewToolConfig, callback: ViewToolCallback): RegisteredAppTool; } /** * Options for {@link createMcpAppRuntime}. * * @internal */ interface CreateMcpAppRuntimeOptions { /** * Transport used by the runtime's single {@link McpAppRuntime.connect} * attempt (tests). * Defaults to {@link PostMessageTransport} against `window.parent`. */ transport?: ViewRuntimeTransport; } /** * Create a fresh {@link McpAppRuntime} for one iframe document / view mount. * * Constructs and configures the guest {@link App} eagerly so event handlers * and view tools can be registered before or during initialization. The App is * connected at most once and remains owned by the runtime until disposal. * * @param config - Normalized {@link NormalizedViewConfig} from bootstrap. * @param options - Optional transport injection for tests. * @returns A runtime owning connection, snapshots, and view-tool registration. * * @internal */ export declare function createMcpAppRuntime(config: NormalizedViewConfig, options?: CreateMcpAppRuntimeOptions): McpAppRuntime; /** * Register `runtime` as the document-active instance. * * @param runtime - Runtime to activate, or `null` to clear. * * @internal */ export declare function setActiveRuntime(runtime: McpAppRuntime | null): void; /** * Return the document-active runtime, if any. * * @internal */ export declare function getActiveRuntime(): McpAppRuntime | null; /** * Inject a transport before the next bootstrap-created runtime. * * A mounted runtime has already started its sole connection attempt, so its * transport cannot be replaced. * * @param transport - Guest-side paired transport, or `null` to clear. * * @internal */ export declare function _setTransportForTesting(transport: ViewRuntimeTransport | null): void; /** * Consume and clear any transport queued by {@link _setTransportForTesting}. * * @internal */ export declare function takePendingTestTransport(): ViewRuntimeTransport | undefined; /** * Register {@link disposeView} for {@link _resetViewBridgeForTesting}. * * @param disposer - The document dispose function from bootstrap-view. * * @internal */ export declare function _registerDisposeViewForTesting(disposer: () => Promise): void; /** * @internal Reset runtime module seams between tests. * * Uses the real {@link disposeView} path when bootstrap has registered it * (unmount React, then close the App). Falls back to disposing an orphaned * active runtime when nothing is mounted through bootstrap. */ export declare function _resetViewBridgeForTesting(): void; /** @internal Guest `App` for the active runtime (bridge tests only). */ export declare function _getAppForTesting(): App | null; /** @internal Active runtime instance (Phase 5 runtime tests). */ export declare function _getRuntimeForTesting(): McpAppRuntime | null; export {};